test.cc 879 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167
  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_PRIVATE_KEY_FILE "./key.pem"
  43. #define CA_CERT_FILE "./ca-bundle.crt"
  44. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  45. #define CLIENT_CA_CERT_DIR "."
  46. #define CLIENT_CERT_FILE "./client.cert.pem"
  47. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  48. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  49. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  50. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  51. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  52. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  53. #else
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  55. #endif
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  57. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  60. #ifdef CPPHTTPLIB_SSL_ENABLED
  61. namespace httplib {
  62. namespace tls {
  63. // Declared here for the split build, where the TLS abstraction declarations
  64. // live below the split border; the definition is linked from httplib.cc.
  65. ca_store_t create_ca_store(const char *pem, size_t len);
  66. } // namespace tls
  67. } // namespace httplib
  68. #endif
  69. using namespace std;
  70. using namespace httplib;
  71. const char *HOST = "localhost";
  72. static int get_base_port() {
  73. const char *shard = getenv("GTEST_SHARD_INDEX");
  74. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  75. }
  76. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  77. // New standalone tests MUST use svr.bind_to_any_port() instead.
  78. const int PORT = get_base_port();
  79. const string LONG_QUERY_VALUE = string(25000, '@');
  80. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  81. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  82. const string TOO_LONG_QUERY_URL =
  83. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  84. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  85. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  86. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  87. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  88. return file.name == key;
  89. });
  90. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  91. return *it;
  92. #else
  93. if (it != items.end()) { return *it; }
  94. throw std::runtime_error("invalid multipart form data name error");
  95. #endif
  96. }
  97. static void read_file(const std::string &path, std::string &out) {
  98. std::ifstream fs(path, std::ios_base::binary);
  99. if (!fs) {
  100. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  101. return;
  102. #else
  103. throw std::runtime_error("File not found: " + path);
  104. #endif
  105. }
  106. fs.seekg(0, std::ios_base::end);
  107. auto size = fs.tellg();
  108. fs.seekg(0);
  109. out.resize(static_cast<size_t>(size));
  110. fs.read(&out[0], static_cast<std::streamsize>(size));
  111. }
  112. class UnixSocketTest : public ::testing::Test {
  113. protected:
  114. void TearDown() override { std::remove(pathname_.c_str()); }
  115. void client_GET(const std::string &addr) {
  116. httplib::Client cli{addr};
  117. cli.set_address_family(AF_UNIX);
  118. ASSERT_TRUE(cli.is_valid());
  119. const auto &result = cli.Get(pattern_);
  120. ASSERT_TRUE(result) << "error: " << result.error();
  121. const auto &resp = result.value();
  122. EXPECT_EQ(resp.status, StatusCode::OK_200);
  123. EXPECT_EQ(resp.body, content_);
  124. }
  125. static std::string make_sock_path() {
  126. const char *shard = getenv("GTEST_SHARD_INDEX");
  127. return shard ? std::string("./httplib-server-") + shard + ".sock"
  128. : "./httplib-server.sock";
  129. }
  130. const std::string pathname_{make_sock_path()};
  131. const std::string pattern_{"/hi"};
  132. const std::string content_{"Hello World!"};
  133. };
  134. TEST_F(UnixSocketTest, pathname) {
  135. httplib::Server svr;
  136. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  137. res.set_content(content_, "text/plain");
  138. });
  139. std::thread t{[&] {
  140. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  141. }};
  142. auto se = detail::scope_exit([&] {
  143. svr.stop();
  144. t.join();
  145. ASSERT_FALSE(svr.is_running());
  146. });
  147. svr.wait_until_ready();
  148. ASSERT_TRUE(svr.is_running());
  149. client_GET(pathname_);
  150. }
  151. #if defined(__linux__) || \
  152. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  153. TEST_F(UnixSocketTest, PeerPid) {
  154. httplib::Server svr;
  155. std::string remote_port_val;
  156. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  157. res.set_content(content_, "text/plain");
  158. remote_port_val = std::to_string(req.remote_port);
  159. });
  160. std::thread t{[&] {
  161. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  162. }};
  163. auto se = detail::scope_exit([&] {
  164. svr.stop();
  165. t.join();
  166. ASSERT_FALSE(svr.is_running());
  167. });
  168. svr.wait_until_ready();
  169. ASSERT_TRUE(svr.is_running());
  170. client_GET(pathname_);
  171. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  172. }
  173. #endif
  174. #ifdef __linux__
  175. TEST_F(UnixSocketTest, abstract) {
  176. constexpr char svr_path[]{"\x00httplib-server.sock"};
  177. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  178. httplib::Server svr;
  179. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  180. res.set_content(content_, "text/plain");
  181. });
  182. std::thread t{[&] {
  183. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  184. }};
  185. auto se = detail::scope_exit([&] {
  186. svr.stop();
  187. t.join();
  188. ASSERT_FALSE(svr.is_running());
  189. });
  190. svr.wait_until_ready();
  191. ASSERT_TRUE(svr.is_running());
  192. client_GET(abstract_addr);
  193. }
  194. #endif
  195. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  196. httplib::Server svr;
  197. std::string received_host_header;
  198. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  199. // Capture the Host header sent by the client
  200. auto host_iter = req.headers.find("Host");
  201. if (host_iter != req.headers.end()) {
  202. received_host_header = host_iter->second;
  203. }
  204. res.set_content(content_, "text/plain");
  205. });
  206. std::thread t{[&] {
  207. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  208. }};
  209. auto se = detail::scope_exit([&] {
  210. svr.stop();
  211. t.join();
  212. ASSERT_FALSE(svr.is_running());
  213. });
  214. svr.wait_until_ready();
  215. ASSERT_TRUE(svr.is_running());
  216. // Test that Host header is automatically set to "localhost" for Unix socket
  217. // connections
  218. httplib::Client cli{pathname_};
  219. cli.set_address_family(AF_UNIX);
  220. ASSERT_TRUE(cli.is_valid());
  221. const auto &result = cli.Get(pattern_);
  222. ASSERT_TRUE(result) << "error: " << result.error();
  223. const auto &resp = result.value();
  224. EXPECT_EQ(resp.status, StatusCode::OK_200);
  225. EXPECT_EQ(resp.body, content_);
  226. // Verify that Host header was automatically set to "localhost"
  227. EXPECT_EQ(received_host_header, "localhost");
  228. }
  229. #ifndef _WIN32
  230. TEST(SocketStream, wait_writable_UNIX) {
  231. int fds[2];
  232. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  233. const auto asSocketStream = [&](socket_t fd,
  234. std::function<bool(Stream &)> func) {
  235. return detail::process_client_socket(
  236. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  237. };
  238. asSocketStream(fds[0], [&](Stream &s0) {
  239. EXPECT_EQ(s0.socket(), fds[0]);
  240. EXPECT_TRUE(s0.wait_writable());
  241. EXPECT_TRUE(s0.is_peer_alive());
  242. EXPECT_EQ(0, close(fds[1]));
  243. EXPECT_FALSE(s0.is_peer_alive());
  244. return true;
  245. });
  246. EXPECT_EQ(0, close(fds[0]));
  247. }
  248. TEST(SocketStream, wait_writable_INET) {
  249. sockaddr_in addr;
  250. memset(&addr, 0, sizeof(addr));
  251. addr.sin_family = AF_INET;
  252. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  253. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  254. int disconnected_svr_sock = -1;
  255. std::thread svr{[&] {
  256. const int s = socket(AF_INET, SOCK_STREAM, 0);
  257. ASSERT_LE(0, s);
  258. // PORT + 1 is shared with the SSL redirect tests and with
  259. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  260. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  261. // because that happens on a worker thread the ASSERT does not stop the
  262. // test: it runs on and fails at the disconnected_svr_sock check instead.
  263. default_socket_options(s);
  264. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  265. ASSERT_EQ(0, listen(s, 1));
  266. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  267. ASSERT_EQ(0, close(s));
  268. }};
  269. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  270. std::thread cli{[&] {
  271. const int s = socket(AF_INET, SOCK_STREAM, 0);
  272. ASSERT_LE(0, s);
  273. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  274. ASSERT_EQ(0, close(s));
  275. }};
  276. cli.join();
  277. svr.join();
  278. ASSERT_NE(disconnected_svr_sock, -1);
  279. const auto asSocketStream = [&](socket_t fd,
  280. std::function<bool(Stream &)> func) {
  281. return detail::process_client_socket(
  282. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  283. };
  284. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  285. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  286. // wait_writable() returns true because select_write() only checks if the
  287. // send buffer has space. Peer disconnection is detected later by send().
  288. EXPECT_TRUE(ss.wait_writable());
  289. return true;
  290. });
  291. ASSERT_EQ(0, close(disconnected_svr_sock));
  292. }
  293. #endif // #ifndef _WIN32
  294. TEST(SetSocketOptTest, TcpNoDelay) {
  295. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  296. ASSERT_NE(sock, INVALID_SOCKET);
  297. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  298. int val = 0;
  299. socklen_t len = sizeof(val);
  300. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  301. reinterpret_cast<char *>(&val), &len));
  302. EXPECT_NE(val, 0);
  303. detail::close_socket(sock);
  304. }
  305. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  306. // accept() reports failures through WSAGetLastError() on Windows and through
  307. // errno everywhere else. Asking the wrong one is what made the accept loop
  308. // treat every recoverable failure as fatal on Windows.
  309. struct Classification {
  310. bool resource;
  311. bool transient;
  312. };
  313. auto classify = [](int err) {
  314. #ifdef _WIN32
  315. WSASetLastError(err);
  316. #else
  317. errno = err;
  318. #endif
  319. // Read both before asserting: an assertion may clobber the error slot.
  320. Classification c;
  321. c.resource = detail::is_accept_resource_error();
  322. c.transient = detail::is_accept_transient_error();
  323. return c;
  324. };
  325. #ifdef _WIN32
  326. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  327. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  328. WSAECONNRESET, WSAECONNABORTED};
  329. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  330. #else
  331. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  332. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  333. ECONNABORTED};
  334. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  335. #endif
  336. for (auto err : resource_errors) {
  337. const auto c = classify(err);
  338. EXPECT_TRUE(c.resource) << "error " << err;
  339. EXPECT_FALSE(c.transient) << "error " << err;
  340. }
  341. for (auto err : transient_errors) {
  342. const auto c = classify(err);
  343. EXPECT_TRUE(c.transient) << "error " << err;
  344. EXPECT_FALSE(c.resource) << "error " << err;
  345. }
  346. for (auto err : fatal_errors) {
  347. const auto c = classify(err);
  348. EXPECT_FALSE(c.resource) << "error " << err;
  349. EXPECT_FALSE(c.transient) << "error " << err;
  350. }
  351. #ifdef _WIN32
  352. WSASetLastError(0);
  353. #else
  354. errno = 0;
  355. #endif
  356. }
  357. TEST(ClientTest, MoveConstructible) {
  358. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  359. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  360. }
  361. TEST(ClientTest, MoveAssignable) {
  362. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  363. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  364. }
  365. #ifdef _WIN32
  366. TEST(StartupTest, WSAStartup) {
  367. WSADATA wsaData;
  368. int ret = WSAStartup(0x0002, &wsaData);
  369. ASSERT_EQ(0, ret);
  370. }
  371. #endif
  372. TEST(DecodePathTest, PercentCharacter) {
  373. EXPECT_EQ(
  374. decode_path_component(
  375. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  376. U8("descrip=Gastos áéíóúñÑ 6"));
  377. }
  378. TEST(DecodePathTest, PercentCharacterNUL) {
  379. string expected;
  380. expected.push_back('x');
  381. expected.push_back('\0');
  382. expected.push_back('x');
  383. EXPECT_EQ(decode_path_component("x%00x"), expected);
  384. }
  385. TEST(DecodePathTest, UnicodeEncoding) {
  386. // %u0041 = 'A' (1-byte UTF-8)
  387. EXPECT_EQ("A", decode_path_component("%u0041"));
  388. // %u00E9 = 'é' (2-byte UTF-8)
  389. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  390. // %u3042 = 'あ' (3-byte UTF-8)
  391. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  392. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  393. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  394. // %uD800 = surrogate (invalid, silently dropped)
  395. EXPECT_EQ("", decode_path_component("%uD800"));
  396. }
  397. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  398. // A sign or whitespace inside the two-character escape window must not be
  399. // accepted as a valid percent-encoding; the sequence is passed through
  400. // literally, matching decode_uri_component / decode_path_component.
  401. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  402. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  403. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  404. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  405. // Well-formed escapes still decode.
  406. EXPECT_EQ("-", decode_query_component("%2D", false));
  407. EXPECT_EQ("A", decode_query_component("%41", false));
  408. }
  409. TEST(SanitizeFilenameTest, VariousPatterns) {
  410. // Path traversal
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  413. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  414. // Normal and edge cases
  415. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  416. EXPECT_EQ("filename.txt",
  417. httplib::sanitize_filename("/path/to/filename.txt"));
  418. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  419. EXPECT_EQ("", httplib::sanitize_filename(".."));
  420. EXPECT_EQ("", httplib::sanitize_filename(""));
  421. // Null bytes stripped
  422. EXPECT_EQ("safe.txt",
  423. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  424. // Whitespace-only rejected
  425. EXPECT_EQ("", httplib::sanitize_filename(" "));
  426. }
  427. // Forward declaration (see the base64_encode note below): split builds move the
  428. // definition into httplib.cc, so re-declaring it here lets the test link.
  429. namespace httplib {
  430. namespace detail {
  431. bool is_chunked_transfer_encoding(const Headers &headers);
  432. } // namespace detail
  433. } // namespace httplib
  434. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  435. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  436. auto make = [](std::initializer_list<const char *> lines) {
  437. Headers h;
  438. for (auto te : lines) {
  439. if (te) { h.emplace("Transfer-Encoding", te); }
  440. }
  441. return h;
  442. };
  443. // Sole coding, matched case-insensitively.
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  447. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  451. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  456. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  457. // were received, into one list. Headers preserves that order, so the answer
  458. // is decided by the last coding of the last line and the order the lines
  459. // arrived in is significant.
  460. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  463. // The split can fall anywhere in the list.
  464. EXPECT_TRUE(
  465. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  466. EXPECT_FALSE(
  467. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  468. // A trailing line naming no coding leaves the list ending in nothing, so it
  469. // must not inherit the chunked from the line before it.
  470. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  471. }
  472. // Forward declaration: in split builds split.py strips `inline` and moves the
  473. // definition into httplib.cc, so detail::base64_encode is not visible from the
  474. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  475. // in both header-only and split builds.
  476. namespace httplib {
  477. namespace detail {
  478. std::string base64_encode(const std::string &in);
  479. } // namespace detail
  480. } // namespace httplib
  481. TEST(Base64EncodeTest, KnownAnswers) {
  482. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  483. // where the accumulator's top bit is already set before the next shift.
  484. EXPECT_EQ("", detail::base64_encode(""));
  485. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  486. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  487. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  488. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  489. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  490. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  491. // High bytes keep the top bit set across several rounds.
  492. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  493. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  494. }
  495. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  496. string unescapedCharacters = "-_.!~*'()";
  497. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  498. }
  499. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  500. string reservedCharacters = ";,/?:@&=+$";
  501. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  502. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  503. }
  504. TEST(ClientQueryOrder, PreserveOrder) {
  505. // This test reproduces Issue #2259: client may reorder query parameters
  506. // when sending a GET request. The expected behavior is that the client
  507. // preserves the original query string order when the caller supplied it
  508. // as part of the path.
  509. Server svr;
  510. svr.Get("/", [&](const Request &req, Response &res) {
  511. // Echo back the raw target so the test can assert ordering
  512. res.set_content(req.target, "text/plain");
  513. });
  514. std::thread t{[&] { svr.listen(HOST, PORT); }};
  515. auto se = detail::scope_exit([&] {
  516. svr.stop();
  517. t.join();
  518. ASSERT_FALSE(svr.is_running());
  519. });
  520. svr.wait_until_ready();
  521. Client cli(HOST, PORT);
  522. ASSERT_TRUE(cli.is_valid());
  523. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  524. auto res = cli.Get(original);
  525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  526. // Expect the echoed target to exactly match the original path (order
  527. // preserved)
  528. EXPECT_EQ(res->body, original);
  529. }
  530. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  531. string chineseCharacters = U8("中国語");
  532. string russianCharacters = U8("дом");
  533. string brazilianCharacters = U8("óculos");
  534. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  535. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  536. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  537. "%D0%B4%D0%BE%D0%BC");
  538. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  539. }
  540. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  541. string unescapedCharacters = "-_.!~*'()";
  542. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  543. }
  544. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  545. string reservedCharacters = ";,/?:@&=+$";
  546. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  547. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  548. }
  549. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  550. string chineseCharacters = U8("中国語");
  551. string russianCharacters = U8("дом");
  552. string brazilianCharacters = U8("óculos");
  553. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  554. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  555. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  556. "%D0%B4%D0%BE%D0%BC");
  557. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  558. }
  559. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  560. // Issue #2082 use case: encoding path component with ampersand
  561. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  562. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  563. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  564. }
  565. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  566. string unescapedCharacters = "-_.!~*'()";
  567. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  568. }
  569. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  570. string reservedCharacters = ";,/?:@&=+$#";
  571. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  572. }
  573. TEST(EncodeUriTest, TestUTF8Characters) {
  574. string chineseCharacters = U8("中国語");
  575. string russianCharacters = U8("дом");
  576. string brazilianCharacters = U8("óculos");
  577. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  578. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  579. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  580. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  581. }
  582. TEST(EncodeUriTest, TestCompleteUri) {
  583. string uri =
  584. "https://example.com/path/to/resource?query=value&param=test#fragment";
  585. EXPECT_EQ(
  586. httplib::encode_uri(uri),
  587. "https://example.com/path/to/resource?query=value&param=test#fragment");
  588. }
  589. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  590. string uri =
  591. "https://example.com/path with spaces/file name.html?q=hello world";
  592. EXPECT_EQ(httplib::encode_uri(uri),
  593. "https://example.com/path%20with%20spaces/"
  594. "file%20name.html?q=hello%20world");
  595. }
  596. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  597. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  598. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  599. }
  600. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  601. string unescapedCharacters = "-_.!~*'()";
  602. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  603. }
  604. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  605. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  606. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  607. string encodedBrazilian = "%C3%B3culos";
  608. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  610. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  611. }
  612. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  613. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  614. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  615. "Piri Tommy Villiers - on & on");
  616. }
  617. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  618. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  619. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  620. }
  621. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  622. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  623. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  624. }
  625. TEST(DecodeUriTest, TestUTF8Characters) {
  626. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  627. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  628. string encodedBrazilian = "%C3%B3culos";
  629. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  630. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  631. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  632. }
  633. TEST(DecodeUriTest, TestCompleteUri) {
  634. string encodedUri = "https://example.com/path%20with%20spaces/"
  635. "file%20name.html?q=hello%20world";
  636. EXPECT_EQ(
  637. httplib::decode_uri(encodedUri),
  638. "https://example.com/path with spaces/file name.html?q=hello world");
  639. }
  640. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  641. string original =
  642. "https://example.com/path with spaces/file name.html?q=hello world";
  643. string encoded = httplib::encode_uri(original);
  644. string decoded = httplib::decode_uri(encoded);
  645. EXPECT_EQ(decoded, original);
  646. }
  647. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  648. // decode_uri is the inverse of encode_uri: an escaped reserved character
  649. // stays encoded so it is not promoted into a real delimiter, while
  650. // non-reserved escapes still decode (like JS decodeURI).
  651. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  652. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  653. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  654. "%3F%3A%40%26%3D%2B%24%2C%3B");
  655. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  656. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  657. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  658. "http://example.com/a%2Fb");
  659. // decode_uri_component still decodes the reserved character.
  660. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  661. }
  662. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  663. string original = "Piri Tommy Villiers - on & on";
  664. string encoded = httplib::encode_uri_component(original);
  665. string decoded = httplib::decode_uri_component(encoded);
  666. EXPECT_EQ(decoded, original);
  667. }
  668. TEST(TrimTests, TrimStringTests) {
  669. EXPECT_EQ("abc", detail::trim_copy("abc"));
  670. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  671. EXPECT_TRUE(detail::trim_copy("").empty());
  672. }
  673. TEST(AsciiTest, LocaleIndependentClassification) {
  674. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  675. // which consult the global C locale: std::isalnum(0xC5) can return true
  676. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  677. // helpers must classify every byte by the ASCII grammar alone.
  678. for (int i = 0; i < 256; i++) {
  679. auto c = static_cast<char>(i);
  680. auto is_digit = i >= '0' && i <= '9';
  681. auto is_upper = i >= 'A' && i <= 'Z';
  682. auto is_lower = i >= 'a' && i <= 'z';
  683. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  684. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  685. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  686. << "byte " << i;
  687. }
  688. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  689. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  690. // Non-ASCII bytes must be percent-encoded, never passed through as
  691. // alphanumeric.
  692. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  693. }
  694. TEST(FromCharsTest, Double) {
  695. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  696. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  697. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  698. auto parse = [](const std::string &s, double &v) {
  699. return detail::from_chars(s.data(), s.data() + s.size(), v);
  700. };
  701. double v = -1.0;
  702. // Representative quality values.
  703. EXPECT_EQ(parse("0", v).ec, std::errc{});
  704. EXPECT_DOUBLE_EQ(v, 0.0);
  705. EXPECT_EQ(parse("1", v).ec, std::errc{});
  706. EXPECT_DOUBLE_EQ(v, 1.0);
  707. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  708. EXPECT_DOUBLE_EQ(v, 0.8);
  709. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  710. EXPECT_DOUBLE_EQ(v, 0.001);
  711. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  712. EXPECT_DOUBLE_EQ(v, 1.0);
  713. // A missing integer or fractional part is tolerated.
  714. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  715. EXPECT_DOUBLE_EQ(v, 0.5);
  716. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  717. EXPECT_DOUBLE_EQ(v, 5.0);
  718. // Values outside [0, 1] still parse; the caller range-checks them.
  719. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  720. EXPECT_DOUBLE_EQ(v, 123.456);
  721. // Stops at the first byte that is not part of the number and reports where.
  722. std::string trailing = "0.9, text/html";
  723. auto r = parse(trailing, v);
  724. EXPECT_EQ(r.ec, std::errc{});
  725. EXPECT_DOUBLE_EQ(v, 0.9);
  726. EXPECT_EQ(*r.ptr, ',');
  727. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  728. // outright, and an 'e'/'E' simply ends the number.
  729. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  730. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  731. std::string exp_input = "1.5e3";
  732. r = parse(exp_input, v);
  733. EXPECT_EQ(r.ec, std::errc{});
  734. EXPECT_DOUBLE_EQ(v, 1.5);
  735. EXPECT_EQ(*r.ptr, 'e');
  736. // Invalid inputs.
  737. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  741. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  742. // Pathological but well-formed inputs must stay bounded (no overflow, no
  743. // out-of-bounds table access) and stay within [0, 1] for the caller.
  744. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  745. std::errc{});
  746. EXPECT_DOUBLE_EQ(v, 0.0);
  747. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  748. std::errc{});
  749. EXPECT_GE(v, 0.0);
  750. EXPECT_LE(v, 1.0);
  751. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  752. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  753. }
  754. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  755. // Simple case without quality values
  756. std::vector<std::string> result1;
  757. EXPECT_TRUE(detail::parse_accept_header(
  758. "text/html,application/json,text/plain", result1));
  759. EXPECT_EQ(result1.size(), 3U);
  760. EXPECT_EQ(result1[0], "text/html");
  761. EXPECT_EQ(result1[1], "application/json");
  762. EXPECT_EQ(result1[2], "text/plain");
  763. // With quality values
  764. std::vector<std::string> result2;
  765. EXPECT_TRUE(detail::parse_accept_header(
  766. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  767. EXPECT_EQ(result2.size(), 3U);
  768. EXPECT_EQ(result2[0], "application/json"); // highest q value
  769. EXPECT_EQ(result2[1], "text/html");
  770. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  771. }
  772. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  773. // Mixed with and without quality values
  774. std::vector<std::string> result;
  775. EXPECT_TRUE(detail::parse_accept_header(
  776. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  777. EXPECT_EQ(result.size(), 3U);
  778. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  779. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  780. EXPECT_EQ(result[2], "application/json"); // q=0.5
  781. }
  782. TEST(ParseAcceptHeaderTest, EdgeCases) {
  783. // Empty header
  784. std::vector<std::string> empty_result;
  785. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  786. EXPECT_TRUE(empty_result.empty());
  787. // Single type
  788. std::vector<std::string> single_result;
  789. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  790. EXPECT_EQ(single_result.size(), 1U);
  791. EXPECT_EQ(single_result[0], "application/json");
  792. // Wildcard types
  793. std::vector<std::string> wildcard_result;
  794. EXPECT_TRUE(detail::parse_accept_header(
  795. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  796. EXPECT_EQ(wildcard_result.size(), 3U);
  797. EXPECT_EQ(wildcard_result[0], "application/json");
  798. EXPECT_EQ(wildcard_result[1], "text/*");
  799. EXPECT_EQ(wildcard_result[2], "*/*");
  800. }
  801. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  802. // Common browser Accept header
  803. std::vector<std::string> browser_result;
  804. EXPECT_TRUE(
  805. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  806. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  807. browser_result));
  808. EXPECT_EQ(browser_result.size(), 6U);
  809. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  813. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  814. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  815. // API client header
  816. std::vector<std::string> api_result;
  817. EXPECT_TRUE(detail::parse_accept_header(
  818. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  819. api_result));
  820. EXPECT_EQ(api_result.size(), 3U);
  821. EXPECT_EQ(api_result[0], "application/json");
  822. EXPECT_EQ(api_result[1], "application/xml");
  823. EXPECT_EQ(api_result[2], "text/plain");
  824. }
  825. TEST(ParseAcceptHeaderTest, SpecialCases) {
  826. // Quality value with 3 decimal places
  827. std::vector<std::string> decimal_result;
  828. EXPECT_TRUE(detail::parse_accept_header(
  829. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  830. EXPECT_EQ(decimal_result.size(), 2U);
  831. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  832. EXPECT_EQ(decimal_result[1], "text/html");
  833. // Zero quality (should still be included but with lowest priority)
  834. std::vector<std::string> zero_q_result;
  835. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  836. zero_q_result));
  837. EXPECT_EQ(zero_q_result.size(), 2U);
  838. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  839. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  840. // No spaces around commas
  841. std::vector<std::string> no_space_result;
  842. EXPECT_TRUE(detail::parse_accept_header(
  843. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  844. no_space_result));
  845. EXPECT_EQ(no_space_result.size(), 3U);
  846. EXPECT_EQ(no_space_result[0], "text/html");
  847. EXPECT_EQ(no_space_result[1], "application/json");
  848. EXPECT_EQ(no_space_result[2], "text/plain");
  849. }
  850. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  851. // Quality values always use '.' as the decimal separator, so parsing must
  852. // not depend on the process locale. An embedding application may have
  853. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  854. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  855. std::string saved = cur ? cur : "C";
  856. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  857. "fr_FR.UTF-8"};
  858. bool switched = false;
  859. for (const auto loc : comma_locales) {
  860. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  861. std::localeconv()->decimal_point[0] == ',') {
  862. switched = true;
  863. break;
  864. }
  865. }
  866. if (!switched) {
  867. std::setlocale(LC_NUMERIC, saved.c_str());
  868. GTEST_SKIP() << "no comma-decimal locale available on this host";
  869. }
  870. // The higher-weighted type appears later in the list, so a correct parse
  871. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  872. // sensitive parse reads both weights as 0 and leaves the original order.
  873. std::vector<std::string> result;
  874. EXPECT_TRUE(detail::parse_accept_header(
  875. "application/json;q=0.1,text/html;q=0.9", result));
  876. ASSERT_EQ(result.size(), 2U);
  877. EXPECT_EQ(result[0], "text/html");
  878. EXPECT_EQ(result[1], "application/json");
  879. std::setlocale(LC_NUMERIC, saved.c_str());
  880. }
  881. TEST(ParseAcceptHeaderTest, InvalidCases) {
  882. std::vector<std::string> result;
  883. // Invalid quality value (> 1.0)
  884. EXPECT_FALSE(
  885. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  886. // Invalid quality value (< 0.0)
  887. EXPECT_FALSE(
  888. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  889. // Invalid quality value (not a number)
  890. EXPECT_FALSE(detail::parse_accept_header(
  891. "text/html;q=invalid,application/json", result));
  892. // A valid numeric prefix does not make the entire quality value valid.
  893. EXPECT_FALSE(detail::parse_accept_header(
  894. "text/html;q=0.5junk,application/json", result));
  895. // Empty quality value
  896. EXPECT_FALSE(
  897. detail::parse_accept_header("text/html;q=,application/json", result));
  898. // Invalid media type format (no slash and not wildcard)
  899. EXPECT_FALSE(
  900. detail::parse_accept_header("invalidtype,application/json", result));
  901. // Valid cases should still work
  902. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  903. EXPECT_EQ(result.size(), 1U);
  904. EXPECT_EQ(result[0], "*/*");
  905. EXPECT_TRUE(detail::parse_accept_header("*", result));
  906. EXPECT_EQ(result.size(), 1U);
  907. EXPECT_EQ(result[0], "*");
  908. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  909. EXPECT_EQ(result.size(), 1U);
  910. EXPECT_EQ(result[0], "text/*");
  911. }
  912. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  913. // elements, so a leading, trailing or doubled comma is a legal Accept value
  914. // and must not be answered with 400 Bad Request.
  915. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  916. struct {
  917. const char *value;
  918. std::vector<std::string> expected;
  919. } cases[] = {
  920. {",application/json", {"application/json"}},
  921. {"text/html,", {"text/html"}},
  922. {"text/html,,*/*", {"text/html", "*/*"}},
  923. // An empty element may be spelled with whitespace in it
  924. {"text/html, , application/json", {"text/html", "application/json"}},
  925. // Nothing but empty elements is an empty list, which means the same
  926. // thing as no Accept header at all
  927. {",,,", {}},
  928. // Quality values still apply across ignored empty elements
  929. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  930. };
  931. for (const auto &c : cases) {
  932. std::vector<std::string> result;
  933. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  934. << "value: " << c.value;
  935. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  936. }
  937. // An invalid entry is still rejected when empty elements surround it
  938. std::vector<std::string> result;
  939. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  940. }
  941. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  942. Server svr;
  943. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  944. EXPECT_EQ(req.accept_content_types.size(), 3U);
  945. EXPECT_EQ(req.accept_content_types[0], "application/json");
  946. EXPECT_EQ(req.accept_content_types[1], "text/html");
  947. EXPECT_EQ(req.accept_content_types[2], "*/*");
  948. res.set_content("ok", "text/plain");
  949. });
  950. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  951. EXPECT_TRUE(false);
  952. res.set_content("bad request", "text/plain");
  953. });
  954. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  955. auto se = detail::scope_exit([&] {
  956. svr.stop();
  957. listen_thread.join();
  958. ASSERT_FALSE(svr.is_running());
  959. });
  960. svr.wait_until_ready();
  961. Client cli("localhost", PORT);
  962. {
  963. auto res = cli.Get(
  964. "/accept_ok",
  965. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  967. EXPECT_EQ(StatusCode::OK_200, res->status);
  968. }
  969. {
  970. auto res = cli.Get("/accept_bad_request",
  971. Headers{{"Accept", "text/html;q=abc,application/json"}});
  972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  973. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  974. }
  975. }
  976. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  977. Server svr;
  978. svr.Get("/", [](const Request & /*req*/, Response &res) {
  979. res.set_content("ok", "text/plain");
  980. });
  981. std::atomic<int> start_count{0};
  982. std::atomic<bool> running_when_called{false};
  983. svr.set_start_handler([&]() {
  984. running_when_called = svr.is_running();
  985. start_count++;
  986. });
  987. auto port = svr.bind_to_any_port(HOST);
  988. std::thread t([&]() { svr.listen_after_bind(); });
  989. auto se = detail::scope_exit([&] {
  990. svr.stop();
  991. t.join();
  992. ASSERT_FALSE(svr.is_running());
  993. });
  994. svr.wait_until_ready();
  995. // A successful request proves the accept loop is running, which the start
  996. // handler precedes; so by now the handler must have run exactly once.
  997. Client cli(HOST, port);
  998. cli.set_connection_timeout(std::chrono::seconds(5));
  999. auto res = cli.Get("/");
  1000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1001. EXPECT_EQ(StatusCode::OK_200, res->status);
  1002. EXPECT_EQ(1, start_count.load());
  1003. EXPECT_TRUE(running_when_called.load());
  1004. }
  1005. TEST(DivideTest, DivideStringTests) {
  1006. auto divide = [](const std::string &str, char d) {
  1007. std::string lhs;
  1008. std::string rhs;
  1009. detail::divide(str, d,
  1010. [&](const char *lhs_data, std::size_t lhs_size,
  1011. const char *rhs_data, std::size_t rhs_size) {
  1012. lhs.assign(lhs_data, lhs_size);
  1013. rhs.assign(rhs_data, rhs_size);
  1014. });
  1015. return std::make_pair(std::move(lhs), std::move(rhs));
  1016. };
  1017. {
  1018. const auto res = divide("", '=');
  1019. EXPECT_EQ(res.first, "");
  1020. EXPECT_EQ(res.second, "");
  1021. }
  1022. {
  1023. const auto res = divide("=", '=');
  1024. EXPECT_EQ(res.first, "");
  1025. EXPECT_EQ(res.second, "");
  1026. }
  1027. {
  1028. const auto res = divide(" ", '=');
  1029. EXPECT_EQ(res.first, " ");
  1030. EXPECT_EQ(res.second, "");
  1031. }
  1032. {
  1033. const auto res = divide("a", '=');
  1034. EXPECT_EQ(res.first, "a");
  1035. EXPECT_EQ(res.second, "");
  1036. }
  1037. {
  1038. const auto res = divide("a=", '=');
  1039. EXPECT_EQ(res.first, "a");
  1040. EXPECT_EQ(res.second, "");
  1041. }
  1042. {
  1043. const auto res = divide("=b", '=');
  1044. EXPECT_EQ(res.first, "");
  1045. EXPECT_EQ(res.second, "b");
  1046. }
  1047. {
  1048. const auto res = divide("a=b", '=');
  1049. EXPECT_EQ(res.first, "a");
  1050. EXPECT_EQ(res.second, "b");
  1051. }
  1052. {
  1053. const auto res = divide("a=b=", '=');
  1054. EXPECT_EQ(res.first, "a");
  1055. EXPECT_EQ(res.second, "b=");
  1056. }
  1057. {
  1058. const auto res = divide("a=b=c", '=');
  1059. EXPECT_EQ(res.first, "a");
  1060. EXPECT_EQ(res.second, "b=c");
  1061. }
  1062. }
  1063. TEST(SplitTest, ParseQueryString) {
  1064. string s = "key1=val1&key2=val2&key3=val3";
  1065. Params dic;
  1066. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1067. [&](const char *b, const char *e) {
  1068. string key, val;
  1069. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1070. if (key.empty()) {
  1071. key.assign(b2, e2);
  1072. } else {
  1073. val.assign(b2, e2);
  1074. }
  1075. });
  1076. dic.emplace(key, val);
  1077. });
  1078. EXPECT_EQ("val1", dic.find("key1")->second);
  1079. EXPECT_EQ("val2", dic.find("key2")->second);
  1080. EXPECT_EQ("val3", dic.find("key3")->second);
  1081. }
  1082. TEST(SplitTest, ParseInvalidQueryTests) {
  1083. {
  1084. string s = " ";
  1085. Params dict;
  1086. detail::parse_query_text(s, dict);
  1087. EXPECT_TRUE(dict.empty());
  1088. }
  1089. {
  1090. string s = " = =";
  1091. Params dict;
  1092. detail::parse_query_text(s, dict);
  1093. EXPECT_TRUE(dict.empty());
  1094. }
  1095. }
  1096. TEST(ParseQueryTest, ParseQueryString) {
  1097. {
  1098. std::string s = "key1=val1&key2=val2&key3=val3";
  1099. Params dic;
  1100. detail::parse_query_text(s, dic);
  1101. EXPECT_EQ("val1", dic.find("key1")->second);
  1102. EXPECT_EQ("val2", dic.find("key2")->second);
  1103. EXPECT_EQ("val3", dic.find("key3")->second);
  1104. }
  1105. {
  1106. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1107. Params dic;
  1108. detail::parse_query_text(s, dic);
  1109. EXPECT_EQ("", dic.find("key1")->second);
  1110. EXPECT_EQ("val1", dic.find("key2")->second);
  1111. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1112. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1113. }
  1114. }
  1115. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1116. Params dic;
  1117. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1118. dic.emplace("key1", "val1");
  1119. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1120. dic.emplace("key2", "val2");
  1121. dic.emplace("key3", "val3");
  1122. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1123. }
  1124. // Joins every entry of a Headers or Params into "key=value " so a whole
  1125. // traversal can be compared in one assertion. Both are instantiations of the
  1126. // same insertion-ordered container, so one helper serves both.
  1127. template <typename Map> static std::string entries_to_string(const Map &m) {
  1128. std::string s;
  1129. for (const auto &entry : m) {
  1130. s += entry.first + "=" + entry.second + " ";
  1131. }
  1132. return s;
  1133. }
  1134. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1135. // Params used to be a std::multimap, which sorted by name and handed the
  1136. // caller's query back alphabetised. A client signing its query string could
  1137. // not reproduce the order it asked for.
  1138. Params dic;
  1139. dic.emplace("zulu", "1");
  1140. dic.emplace("alpha", "2");
  1141. dic.emplace("mike", "3");
  1142. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1143. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1144. }
  1145. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1146. Params dic;
  1147. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1148. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1149. }
  1150. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1151. Request req;
  1152. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1153. req.params);
  1154. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1155. EXPECT_EQ("first", req.get_param_value("tag"));
  1156. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1157. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1158. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1159. EXPECT_EQ("", req.get_param_value("tag", 3));
  1160. }
  1161. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1162. // Params shares its container with Headers, which matches field names
  1163. // case-insensitively. Parameter names must not pick that up.
  1164. Params dic;
  1165. dic.emplace("Key", "upper");
  1166. dic.emplace("key", "lower");
  1167. EXPECT_EQ(2U, dic.size());
  1168. EXPECT_EQ(1U, dic.count("Key"));
  1169. EXPECT_EQ(1U, dic.count("key"));
  1170. EXPECT_EQ("upper", dic.find("Key")->second);
  1171. EXPECT_EQ("lower", dic.find("key")->second);
  1172. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1173. }
  1174. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1175. Server svr;
  1176. std::string order;
  1177. svr.Get("/order", [&](const Request &req, Response &res) {
  1178. order = entries_to_string(req.params);
  1179. res.set_content("ok", "text/plain");
  1180. });
  1181. auto port = svr.bind_to_any_port(HOST);
  1182. thread t = thread([&] { svr.listen_after_bind(); });
  1183. auto se = detail::scope_exit([&] {
  1184. svr.stop();
  1185. t.join();
  1186. ASSERT_FALSE(svr.is_running());
  1187. });
  1188. svr.wait_until_ready();
  1189. Client cli(HOST, port);
  1190. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1191. ASSERT_TRUE(res);
  1192. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1193. }
  1194. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1195. Server svr;
  1196. std::string field_order, file_order;
  1197. svr.Post("/order", [&](const Request &req, Response &res) {
  1198. for (const auto &field : req.form.fields) {
  1199. field_order += field.first + "=" + field.second.content + " ";
  1200. }
  1201. for (const auto &file : req.form.files) {
  1202. file_order += file.first + "=" + file.second.filename + " ";
  1203. }
  1204. res.set_content("ok", "text/plain");
  1205. });
  1206. auto port = svr.bind_to_any_port(HOST);
  1207. thread t = thread([&] { svr.listen_after_bind(); });
  1208. auto se = detail::scope_exit([&] {
  1209. svr.stop();
  1210. t.join();
  1211. ASSERT_FALSE(svr.is_running());
  1212. });
  1213. svr.wait_until_ready();
  1214. UploadFormDataItems items = {
  1215. {"zulu", "1", "", ""},
  1216. {"alpha", "2", "", ""},
  1217. {"mike", "3", "", ""},
  1218. {"zebra", "z", "z.txt", "text/plain"},
  1219. {"apple", "a", "a.txt", "text/plain"},
  1220. };
  1221. Client cli(HOST, port);
  1222. auto res = cli.Post("/order", items);
  1223. ASSERT_TRUE(res);
  1224. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1225. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1226. }
  1227. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1228. Server svr;
  1229. std::vector<std::string> values;
  1230. std::string first, second, out_of_range, order;
  1231. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1232. values = req.form.get_fields("tag");
  1233. first = req.form.get_field("tag", 0);
  1234. second = req.form.get_field("tag", 1);
  1235. out_of_range = req.form.get_field("tag", 2);
  1236. for (const auto &field : req.form.fields) {
  1237. order += field.first + "=" + field.second.content + " ";
  1238. }
  1239. res.set_content("ok", "text/plain");
  1240. });
  1241. auto port = svr.bind_to_any_port(HOST);
  1242. thread t = thread([&] { svr.listen_after_bind(); });
  1243. auto se = detail::scope_exit([&] {
  1244. svr.stop();
  1245. t.join();
  1246. ASSERT_FALSE(svr.is_running());
  1247. });
  1248. svr.wait_until_ready();
  1249. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1250. // not adjacent in the container.
  1251. UploadFormDataItems items = {
  1252. {"tag", "first", "", ""},
  1253. {"other", "x", "", ""},
  1254. {"tag", "second", "", ""},
  1255. };
  1256. Client cli(HOST, port);
  1257. auto res = cli.Post("/repeated", items);
  1258. ASSERT_TRUE(res);
  1259. ASSERT_EQ(2U, values.size());
  1260. EXPECT_EQ("first", values[0]);
  1261. EXPECT_EQ("second", values[1]);
  1262. EXPECT_EQ("first", first);
  1263. EXPECT_EQ("second", second);
  1264. // std::multimap already kept entries sharing a name in insertion order, so
  1265. // everything above passes without this change too. The whole traversal is
  1266. // what tells the two apart: sorting by name would hoist "other" to the front
  1267. // and the two "tag" parts would end up adjacent.
  1268. EXPECT_EQ("tag=first other=x tag=second ", order);
  1269. // Advancing past the last entry of a name used to run off the container;
  1270. // the container's saturating increment makes it return the default instead.
  1271. EXPECT_EQ("", out_of_range);
  1272. }
  1273. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1274. // Server::read_content() keeps a FormFields::iterator alive across the
  1275. // content callbacks that fill the part it points at. The container is
  1276. // vector-backed, so a later emplace can reallocate and invalidate an older
  1277. // iterator; 64 parts grow the vector through seven reallocations, which
  1278. // checks that every part's content still lands in its own entry.
  1279. const size_t part_count = 64;
  1280. // One formula for both the parts sent and the values expected back, so the
  1281. // two cannot drift apart.
  1282. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1283. auto content_of = [](size_t i) {
  1284. return std::string(64, static_cast<char>('a' + (i % 26)));
  1285. };
  1286. Server svr;
  1287. std::vector<std::pair<std::string, std::string>> received;
  1288. svr.Post("/many", [&](const Request &req, Response &res) {
  1289. for (const auto &field : req.form.fields) {
  1290. received.emplace_back(field.first, field.second.content);
  1291. }
  1292. res.set_content("ok", "text/plain");
  1293. });
  1294. auto port = svr.bind_to_any_port(HOST);
  1295. thread t = thread([&] { svr.listen_after_bind(); });
  1296. auto se = detail::scope_exit([&] {
  1297. svr.stop();
  1298. t.join();
  1299. ASSERT_FALSE(svr.is_running());
  1300. });
  1301. svr.wait_until_ready();
  1302. UploadFormDataItems items;
  1303. for (size_t i = 0; i < part_count; i++) {
  1304. items.push_back({name_of(i), content_of(i), "", ""});
  1305. }
  1306. Client cli(HOST, port);
  1307. auto res = cli.Post("/many", items);
  1308. ASSERT_TRUE(res);
  1309. ASSERT_EQ(part_count, received.size());
  1310. for (size_t i = 0; i < part_count; i++) {
  1311. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1312. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1313. }
  1314. }
  1315. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1316. string content_type = "multipart/form-data; boundary=something";
  1317. string boundary;
  1318. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1319. EXPECT_TRUE(ret);
  1320. EXPECT_EQ(boundary, "something");
  1321. }
  1322. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1323. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1324. string boundary;
  1325. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1326. EXPECT_TRUE(ret);
  1327. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1328. }
  1329. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1330. string content_type =
  1331. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1332. string boundary;
  1333. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1334. EXPECT_TRUE(ret);
  1335. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1336. }
  1337. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1338. string content_type =
  1339. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1340. string boundary;
  1341. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1342. EXPECT_TRUE(ret);
  1343. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1344. }
  1345. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1346. const string boundary(70, 'a');
  1347. string content_type = "multipart/form-data; boundary=" + boundary;
  1348. string parsed;
  1349. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1350. EXPECT_TRUE(ret);
  1351. EXPECT_EQ(parsed, boundary);
  1352. }
  1353. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1354. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1355. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1356. string parsed;
  1357. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1358. EXPECT_FALSE(ret);
  1359. }
  1360. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1361. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1362. // is 72 characters on the wire and still valid.
  1363. const string boundary(70, 'a');
  1364. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1365. string parsed;
  1366. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1367. EXPECT_EQ(parsed, boundary);
  1368. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1369. parsed.clear();
  1370. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1371. }
  1372. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1373. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1374. // The parameter parser must not treat that '=' as the key/value separator.
  1375. string content_type =
  1376. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1377. "charset=UTF-8";
  1378. string parsed;
  1379. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1380. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1381. }
  1382. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1383. // A ';' inside the quoted-string is part of the value, not a parameter
  1384. // separator, so it must not truncate the boundary.
  1385. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1386. string parsed;
  1387. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1388. EXPECT_EQ(parsed, "a;b");
  1389. }
  1390. TEST(ParseDispositionParamsTest, QuotedValues) {
  1391. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1392. // ';' and '=' are ordinary characters inside one.
  1393. struct {
  1394. const char *value;
  1395. std::vector<std::pair<const char *, const char *>> expected;
  1396. } cases[] = {
  1397. {"name=\"file1\"; filename=\"a.txt\"",
  1398. {{"name", "file1"}, {"filename", "a.txt"}}},
  1399. // Whitespace around '=' and ';' is still trimmed
  1400. {"name=\"file2\" ;filename = \"a.html\"",
  1401. {{"name", "file2"}, {"filename", "a.html"}}},
  1402. // '=' inside the value used to leave only the text after the last one
  1403. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1404. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1405. {"name=\"x=y\"", {{"name", "x=y"}}},
  1406. // ';' inside the value used to truncate the pair and leave a bogus one
  1407. {"name=\"file3\"; filename=\"a;b.txt\"",
  1408. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1409. // An unquoted value keeps working, and so does filename*
  1410. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1411. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1412. // A parameter with no key is dropped rather than turned into one whose
  1413. // key is the value
  1414. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1415. };
  1416. for (const auto &c : cases) {
  1417. Params params;
  1418. detail::parse_disposition_params(c.value, params);
  1419. for (const auto &kv : c.expected) {
  1420. auto it = params.find(kv.first);
  1421. ASSERT_NE(it, params.end())
  1422. << "value: " << c.value << ", key: " << kv.first;
  1423. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1424. }
  1425. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1426. }
  1427. }
  1428. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1429. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1430. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1431. Server svr;
  1432. std::string field_value, file_name, file_filename;
  1433. bool has_field = false, has_file = false;
  1434. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1435. has_field = req.form.has_field("x=y");
  1436. field_value = req.form.get_field("x=y");
  1437. has_file = req.form.has_file("file1");
  1438. const auto &file = req.form.get_file("file1");
  1439. file_name = file.name;
  1440. file_filename = file.filename;
  1441. res.set_content("ok", "text/plain");
  1442. });
  1443. auto port = svr.bind_to_any_port(HOST);
  1444. thread t = thread([&] { svr.listen_after_bind(); });
  1445. auto se = detail::scope_exit([&] {
  1446. svr.stop();
  1447. t.join();
  1448. ASSERT_FALSE(svr.is_running());
  1449. });
  1450. svr.wait_until_ready();
  1451. UploadFormDataItems items = {
  1452. {"x=y", "field-value", "", ""},
  1453. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1454. };
  1455. Client cli(HOST, port);
  1456. auto res = cli.Post("/quoted", items);
  1457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1458. ASSERT_EQ(StatusCode::OK_200, res->status);
  1459. EXPECT_TRUE(has_field);
  1460. EXPECT_EQ("field-value", field_value);
  1461. EXPECT_TRUE(has_file);
  1462. EXPECT_EQ("file1", file_name);
  1463. EXPECT_EQ("a;b=report.pdf", file_filename);
  1464. }
  1465. TEST(GetHeaderValueTest, DefaultValue) {
  1466. Headers headers = {{"Dummy", "Dummy"}};
  1467. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1468. EXPECT_STREQ("text/plain", val);
  1469. }
  1470. TEST(GetHeaderValueTest, DefaultValueInt) {
  1471. Headers headers = {{"Dummy", "Dummy"}};
  1472. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1473. EXPECT_EQ(100ull, val);
  1474. }
  1475. TEST(GetHeaderValueTest, RegularValue) {
  1476. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1477. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1478. EXPECT_STREQ("text/html", val);
  1479. }
  1480. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1481. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1482. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1483. EXPECT_STREQ("text/html", val);
  1484. }
  1485. TEST(GetHeaderValueTest, SetContent) {
  1486. Response res;
  1487. res.set_content("html", "text/html");
  1488. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1489. res.set_content("text", "text/plain");
  1490. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1491. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1492. }
  1493. TEST(GetHeaderValueTest, RegularValueInt) {
  1494. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1495. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1496. EXPECT_EQ(100ull, val);
  1497. }
  1498. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1499. Headers headers = {{"Content-Length", "x"}};
  1500. auto is_invalid_value = false;
  1501. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1502. is_invalid_value);
  1503. EXPECT_EQ(0ull, val);
  1504. EXPECT_TRUE(is_invalid_value);
  1505. }
  1506. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1507. // An all-digit value that overflows size_t must be reported as invalid, not
  1508. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1509. // a large length to a small one on 32-bit builds, leaving the framing length
  1510. // wrong while is_invalid_value stayed false.
  1511. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1512. auto is_invalid_value = false;
  1513. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1514. is_invalid_value);
  1515. EXPECT_TRUE(is_invalid_value);
  1516. // A well-formed length is unaffected.
  1517. Headers ok = {{"Content-Length", "1234"}};
  1518. is_invalid_value = false;
  1519. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1520. is_invalid_value);
  1521. EXPECT_EQ(1234ull, val);
  1522. EXPECT_FALSE(is_invalid_value);
  1523. }
  1524. TEST(GetHeaderValueTest, Range) {
  1525. {
  1526. Headers headers = {make_range_header({{1, -1}})};
  1527. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1528. EXPECT_STREQ("bytes=1-", val);
  1529. }
  1530. {
  1531. Headers headers = {make_range_header({{-1, 1}})};
  1532. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1533. EXPECT_STREQ("bytes=-1", val);
  1534. }
  1535. {
  1536. Headers headers = {make_range_header({{1, 10}})};
  1537. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1538. EXPECT_STREQ("bytes=1-10", val);
  1539. }
  1540. {
  1541. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1542. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1543. EXPECT_STREQ("bytes=1-10, 100-", val);
  1544. }
  1545. {
  1546. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1547. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1548. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1549. }
  1550. {
  1551. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1552. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1553. EXPECT_STREQ("bytes=0-0, -1", val);
  1554. }
  1555. }
  1556. TEST(BearerTokenAuthTest, SchemeValidation) {
  1557. // A value shorter than "Bearer " must not throw from the fixed-length
  1558. // substr, and a non-Bearer scheme must not be reported as a token.
  1559. struct {
  1560. const char *value;
  1561. const char *expected;
  1562. } cases[] = {
  1563. {"x", ""},
  1564. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1565. {"Bearer abc123", "abc123"},
  1566. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1567. };
  1568. for (const auto &c : cases) {
  1569. Request req;
  1570. req.set_header("Authorization", c.value);
  1571. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1572. }
  1573. }
  1574. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1575. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1576. // to depend on the standard library (libstdc++ handed back duplicates in
  1577. // reverse insertion order, libc++ in insertion order).
  1578. Request req;
  1579. req.set_header("Accept-Encoding", "gzip");
  1580. req.set_header("Accept-Encoding", "deflate");
  1581. req.set_header("Accept-Encoding", "br");
  1582. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1583. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1584. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1585. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1586. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1587. }
  1588. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1589. Request req;
  1590. req.set_header("X-Test", "only");
  1591. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1592. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1593. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1594. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1595. }
  1596. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1597. Headers headers;
  1598. headers.emplace("Host", "example.com");
  1599. headers.emplace("Accept-Encoding", "gzip");
  1600. headers.emplace("User-Agent", "test");
  1601. headers.emplace("Accept-Encoding", "deflate");
  1602. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1603. "Accept-Encoding=deflate ",
  1604. entries_to_string(headers));
  1605. }
  1606. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1607. Headers headers = {{"Content-Type", "text/html"},
  1608. {"CONTENT-TYPE", "text/xml"}};
  1609. EXPECT_EQ(2U, headers.count("content-type"));
  1610. auto it = headers.find("content-type");
  1611. ASSERT_TRUE(it != headers.end());
  1612. EXPECT_EQ("text/html", it->second);
  1613. }
  1614. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1615. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1616. // drop only those fields and leave everything positioned between them.
  1617. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1618. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1619. auto rng = headers.equal_range("a");
  1620. headers.erase(rng.first, rng.second);
  1621. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1622. }
  1623. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1624. Headers headers = {
  1625. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1626. EXPECT_EQ(3U, headers.erase("A"));
  1627. EXPECT_EQ(0U, headers.count("A"));
  1628. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1629. }
  1630. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1631. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1632. headers.emplace_front("Host", "example.com");
  1633. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1634. entries_to_string(headers));
  1635. }
  1636. TEST(ParseHeaderValueTest, Range) {
  1637. {
  1638. Ranges ranges;
  1639. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1640. EXPECT_TRUE(ret);
  1641. EXPECT_EQ(1u, ranges.size());
  1642. EXPECT_EQ(1u, ranges[0].first);
  1643. EXPECT_EQ(-1, ranges[0].second);
  1644. }
  1645. {
  1646. Ranges ranges;
  1647. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1648. EXPECT_TRUE(ret);
  1649. EXPECT_EQ(1u, ranges.size());
  1650. EXPECT_EQ(-1, ranges[0].first);
  1651. EXPECT_EQ(1u, ranges[0].second);
  1652. }
  1653. {
  1654. Ranges ranges;
  1655. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1656. EXPECT_TRUE(ret);
  1657. EXPECT_EQ(1u, ranges.size());
  1658. EXPECT_EQ(1u, ranges[0].first);
  1659. EXPECT_EQ(10u, ranges[0].second);
  1660. }
  1661. {
  1662. Ranges ranges;
  1663. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1664. EXPECT_FALSE(ret);
  1665. }
  1666. {
  1667. Ranges ranges;
  1668. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1669. EXPECT_TRUE(ret);
  1670. EXPECT_EQ(2u, ranges.size());
  1671. EXPECT_EQ(1u, ranges[0].first);
  1672. EXPECT_EQ(10u, ranges[0].second);
  1673. EXPECT_EQ(100u, ranges[1].first);
  1674. EXPECT_EQ(-1, ranges[1].second);
  1675. }
  1676. {
  1677. Ranges ranges;
  1678. auto ret =
  1679. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1680. EXPECT_TRUE(ret);
  1681. EXPECT_EQ(3u, ranges.size());
  1682. EXPECT_EQ(1u, ranges[0].first);
  1683. EXPECT_EQ(10u, ranges[0].second);
  1684. EXPECT_EQ(100u, ranges[1].first);
  1685. EXPECT_EQ(200u, ranges[1].second);
  1686. EXPECT_EQ(300u, ranges[2].first);
  1687. EXPECT_EQ(400u, ranges[2].second);
  1688. }
  1689. {
  1690. Ranges ranges;
  1691. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1700. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1701. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1702. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1703. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1704. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1705. EXPECT_FALSE(
  1706. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1707. EXPECT_TRUE(ranges.empty());
  1708. }
  1709. {
  1710. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1711. // remainder of the representation, so it stays accepted.
  1712. Ranges ranges;
  1713. auto ret =
  1714. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1715. EXPECT_TRUE(ret);
  1716. ASSERT_EQ(1u, ranges.size());
  1717. EXPECT_EQ(0, ranges[0].first);
  1718. EXPECT_EQ(-1, ranges[0].second);
  1719. }
  1720. }
  1721. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1722. Request req;
  1723. req.set_header("Accept-Encoding", "gzip");
  1724. Response res;
  1725. res.set_header("Content-Type", "text/plain");
  1726. auto ret = detail::encoding_type(req, res);
  1727. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1728. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1729. #else
  1730. EXPECT_TRUE(ret == detail::EncodingType::None);
  1731. #endif
  1732. }
  1733. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1734. Request req;
  1735. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1736. Response res;
  1737. res.set_header("Content-Type", "text/plain");
  1738. auto ret = detail::encoding_type(req, res);
  1739. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1740. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1741. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1742. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1743. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1744. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1745. #else
  1746. EXPECT_TRUE(ret == detail::EncodingType::None);
  1747. #endif
  1748. }
  1749. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1750. Request req;
  1751. req.set_header("Accept-Encoding",
  1752. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1753. Response res;
  1754. res.set_header("Content-Type", "text/plain");
  1755. auto ret = detail::encoding_type(req, res);
  1756. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1757. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1758. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1759. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1760. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1761. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1762. #else
  1763. EXPECT_TRUE(ret == detail::EncodingType::None);
  1764. #endif
  1765. }
  1766. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1767. // All supported encodings rejected with q=0 should return None
  1768. Request req;
  1769. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1770. Response res;
  1771. res.set_header("Content-Type", "text/plain");
  1772. auto ret = detail::encoding_type(req, res);
  1773. EXPECT_TRUE(ret == detail::EncodingType::None);
  1774. }
  1775. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1776. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1777. Request req;
  1778. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1779. Response res;
  1780. res.set_header("Content-Type", "text/plain");
  1781. auto ret = detail::encoding_type(req, res);
  1782. EXPECT_TRUE(ret == detail::EncodingType::None);
  1783. }
  1784. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1785. Request req;
  1786. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1787. Response res;
  1788. res.set_header("Content-Type", "text/plain");
  1789. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1790. }
  1791. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1792. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1793. Request req;
  1794. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1795. Response res;
  1796. res.set_header("Content-Type", "text/plain");
  1797. auto ret = detail::encoding_type(req, res);
  1798. EXPECT_TRUE(ret == detail::EncodingType::None);
  1799. }
  1800. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1801. // RFC 7231: Accept-Encoding values are case-insensitive
  1802. Request req;
  1803. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1804. Response res;
  1805. res.set_header("Content-Type", "text/plain");
  1806. auto ret = detail::encoding_type(req, res);
  1807. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1808. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1809. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1810. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1811. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1812. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1813. #else
  1814. EXPECT_TRUE(ret == detail::EncodingType::None);
  1815. #endif
  1816. }
  1817. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1818. // q value should determine priority, not hardcoded order
  1819. Request req;
  1820. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1821. Response res;
  1822. res.set_header("Content-Type", "text/plain");
  1823. auto ret = detail::encoding_type(req, res);
  1824. // gzip has highest q=1.0, so it should be selected even though
  1825. // br and zstd are also supported
  1826. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1827. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1828. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1829. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1830. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1831. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1832. #else
  1833. EXPECT_TRUE(ret == detail::EncodingType::None);
  1834. #endif
  1835. }
  1836. TEST(BufferStreamTest, read) {
  1837. detail::BufferStream strm1;
  1838. Stream &strm = strm1;
  1839. EXPECT_EQ(5, strm.write("hello"));
  1840. char buf[512];
  1841. EXPECT_EQ(2, strm.read(buf, 2));
  1842. EXPECT_EQ('h', buf[0]);
  1843. EXPECT_EQ('e', buf[1]);
  1844. EXPECT_EQ(2, strm.read(buf, 2));
  1845. EXPECT_EQ('l', buf[0]);
  1846. EXPECT_EQ('l', buf[1]);
  1847. EXPECT_EQ(1, strm.read(buf, 1));
  1848. EXPECT_EQ('o', buf[0]);
  1849. EXPECT_EQ(0, strm.read(buf, 1));
  1850. }
  1851. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1852. auto host = "www.httpwatch.com";
  1853. auto ip = hosted_at(host);
  1854. EXPECT_EQ("23.96.13.243", ip);
  1855. std::vector<std::string> addrs;
  1856. hosted_at(host, addrs);
  1857. EXPECT_EQ(1u, addrs.size());
  1858. }
  1859. #if 0 // It depends on each test environment...
  1860. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1861. auto host = "www.youtube.com";
  1862. std::vector<std::string> addrs;
  1863. hosted_at(host, addrs);
  1864. EXPECT_EQ(20u, addrs.size());
  1865. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1866. EXPECT_TRUE(it != addrs.end());
  1867. }
  1868. #endif
  1869. class ChunkedEncodingTest : public ::testing::Test {
  1870. protected:
  1871. ChunkedEncodingTest()
  1872. : cli_(HOST, PORT)
  1873. #ifdef CPPHTTPLIB_SSL_ENABLED
  1874. ,
  1875. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1876. #endif
  1877. {
  1878. cli_.set_connection_timeout(2);
  1879. #ifdef CPPHTTPLIB_SSL_ENABLED
  1880. cli_.enable_server_certificate_verification(false);
  1881. #endif
  1882. }
  1883. virtual void SetUp() {
  1884. read_file("./image.jpg", image_data_);
  1885. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1886. res.set_content("Hello World!", "text/plain");
  1887. });
  1888. svr_.Get(
  1889. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1890. res.set_chunked_content_provider(
  1891. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1892. size_t remaining = image_data_.size() - offset;
  1893. if (remaining == 0) {
  1894. sink.done();
  1895. } else {
  1896. constexpr size_t CHUNK_SIZE = 1024;
  1897. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1898. sink.write(&image_data_[offset], send_size);
  1899. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1900. }
  1901. return true;
  1902. });
  1903. });
  1904. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1905. svr_.wait_until_ready();
  1906. }
  1907. virtual void TearDown() {
  1908. svr_.stop();
  1909. if (!request_threads_.empty()) {
  1910. std::this_thread::sleep_for(std::chrono::seconds(1));
  1911. for (auto &t : request_threads_) {
  1912. t.join();
  1913. }
  1914. }
  1915. t_.join();
  1916. }
  1917. #ifdef CPPHTTPLIB_SSL_ENABLED
  1918. SSLClient cli_;
  1919. SSLServer svr_;
  1920. #else
  1921. Client cli_;
  1922. Server svr_;
  1923. #endif
  1924. thread t_;
  1925. std::vector<thread> request_threads_;
  1926. std::string image_data_;
  1927. };
  1928. TEST_F(ChunkedEncodingTest, NormalGet) {
  1929. auto res = cli_.Get("/chunked");
  1930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1931. std::string out;
  1932. read_file("./image.jpg", out);
  1933. EXPECT_EQ(StatusCode::OK_200, res->status);
  1934. EXPECT_EQ(out, res->body);
  1935. }
  1936. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1937. std::string body;
  1938. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1939. body.append(data, data_length);
  1940. return true;
  1941. });
  1942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1943. std::string out;
  1944. read_file("./image.jpg", out);
  1945. EXPECT_EQ(StatusCode::OK_200, res->status);
  1946. EXPECT_EQ(out, body);
  1947. }
  1948. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1949. std::string body;
  1950. auto res = cli_.Get(
  1951. "/chunked",
  1952. [&](const Response &response) {
  1953. EXPECT_EQ(StatusCode::OK_200, response.status);
  1954. return true;
  1955. },
  1956. [&](const char *data, size_t data_length) {
  1957. body.append(data, data_length);
  1958. return true;
  1959. });
  1960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1961. std::string out;
  1962. read_file("./image.jpg", out);
  1963. EXPECT_EQ(StatusCode::OK_200, res->status);
  1964. EXPECT_EQ(out, body);
  1965. }
  1966. TEST(RangeTest, FromHTTPBin_Online) {
  1967. auto host = "httpbingo.org";
  1968. auto path = std::string{"/range/32"};
  1969. #ifdef CPPHTTPLIB_SSL_ENABLED
  1970. auto port = 443;
  1971. SSLClient cli(host, port);
  1972. #else
  1973. auto port = 80;
  1974. Client cli(host, port);
  1975. #endif
  1976. cli.set_connection_timeout(5);
  1977. {
  1978. auto res = cli.Get(path);
  1979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1980. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1981. EXPECT_EQ(StatusCode::OK_200, res->status);
  1982. }
  1983. {
  1984. Headers headers = {make_range_header({{1, -1}})};
  1985. auto res = cli.Get(path, headers);
  1986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1987. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1988. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1989. }
  1990. {
  1991. Headers headers = {make_range_header({{1, 10}})};
  1992. auto res = cli.Get(path, headers);
  1993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1994. EXPECT_EQ("bcdefghijk", res->body);
  1995. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1996. }
  1997. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1998. // entire resource, while the original httpbin returned 200. Both are
  1999. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2000. {
  2001. Headers headers = {make_range_header({{0, 31}})};
  2002. auto res = cli.Get(path, headers);
  2003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2004. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2005. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2006. res->status == StatusCode::PartialContent_206);
  2007. }
  2008. {
  2009. Headers headers = {make_range_header({{0, -1}})};
  2010. auto res = cli.Get(path, headers);
  2011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2012. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2013. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2014. res->status == StatusCode::PartialContent_206);
  2015. }
  2016. // go-httpbin returns 206 with clamped range for over-range requests,
  2017. // while the original httpbin returned 416. Both behaviors are observed
  2018. // in real servers, so we only verify the request succeeds.
  2019. {
  2020. Headers headers = {make_range_header({{0, 32}})};
  2021. auto res = cli.Get(path, headers);
  2022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2023. }
  2024. }
  2025. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2026. auto host = "unresolvableaddress.local";
  2027. auto path = std::string{"/"};
  2028. #ifdef CPPHTTPLIB_SSL_ENABLED
  2029. auto port = 443;
  2030. SSLClient cli(host, port);
  2031. #else
  2032. auto port = 80;
  2033. Client cli(host, port);
  2034. #endif
  2035. cli.set_connection_timeout(1);
  2036. {
  2037. auto res = cli.Get(path);
  2038. ASSERT_FALSE(res);
  2039. }
  2040. std::this_thread::sleep_for(std::chrono::seconds(8));
  2041. }
  2042. #if defined(__linux__) && defined(__GLIBC__) && \
  2043. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2044. // Forward declaration: in split builds split.py strips `inline` and moves the
  2045. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2046. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2047. // against the symbol in both header-only and split builds.
  2048. namespace httplib {
  2049. namespace detail {
  2050. int getaddrinfo_with_timeout(const char *node, const char *service,
  2051. const struct addrinfo *hints,
  2052. struct addrinfo **res, time_t timeout_sec);
  2053. } // namespace detail
  2054. } // namespace httplib
  2055. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2056. //
  2057. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2058. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2059. // gai_suspend() call hits the connection timeout the function calls
  2060. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2061. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2062. // still alive and still references the now-destroyed stack frame.
  2063. //
  2064. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2065. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2066. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2067. // and runs them in a container.
  2068. namespace {
  2069. bool should_run_issue_2431_tests() {
  2070. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2071. return v && *v && std::string(v) != "0";
  2072. }
  2073. std::string unique_unresolvable_host(int n) {
  2074. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2075. // glibc still asks the configured nameserver — which is exactly the path
  2076. // we want to exercise. A unique label per call avoids the resolver cache.
  2077. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2078. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2079. std::to_string(n) + ".invalid";
  2080. }
  2081. } // namespace
  2082. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2083. if (!should_run_issue_2431_tests()) {
  2084. GTEST_SKIP()
  2085. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2086. }
  2087. for (int i = 0; i < 8; ++i) {
  2088. struct addrinfo hints;
  2089. memset(&hints, 0, sizeof(hints));
  2090. hints.ai_family = AF_UNSPEC;
  2091. hints.ai_socktype = SOCK_STREAM;
  2092. auto host = unique_unresolvable_host(i);
  2093. struct addrinfo *result = nullptr;
  2094. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2095. &result, /*timeout_sec=*/1);
  2096. if (rc == 0 && result) { freeaddrinfo(result); }
  2097. }
  2098. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2099. // stack region they still believe holds their gaicb.
  2100. std::this_thread::sleep_for(std::chrono::seconds(3));
  2101. }
  2102. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2103. if (!should_run_issue_2431_tests()) {
  2104. GTEST_SKIP()
  2105. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2106. }
  2107. std::atomic<bool> stop{false};
  2108. std::vector<std::thread> threads;
  2109. for (int t = 0; t < 8; ++t) {
  2110. threads.emplace_back([t, &stop] {
  2111. int i = 0;
  2112. while (!stop.load(std::memory_order_relaxed)) {
  2113. struct addrinfo hints;
  2114. memset(&hints, 0, sizeof(hints));
  2115. hints.ai_family = AF_UNSPEC;
  2116. hints.ai_socktype = SOCK_STREAM;
  2117. auto host = unique_unresolvable_host(t * 100000 + i++);
  2118. struct addrinfo *result = nullptr;
  2119. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2120. &result, /*timeout_sec=*/1);
  2121. if (rc == 0 && result) { freeaddrinfo(result); }
  2122. }
  2123. });
  2124. }
  2125. std::this_thread::sleep_for(std::chrono::seconds(8));
  2126. stop.store(true, std::memory_order_relaxed);
  2127. for (auto &th : threads) {
  2128. th.join();
  2129. }
  2130. std::this_thread::sleep_for(std::chrono::seconds(3));
  2131. }
  2132. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2133. if (!should_run_issue_2431_tests()) {
  2134. GTEST_SKIP()
  2135. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2136. }
  2137. std::atomic<bool> stop{false};
  2138. std::vector<std::thread> threads;
  2139. for (int t = 0; t < 8; ++t) {
  2140. threads.emplace_back([t, &stop] {
  2141. int i = 0;
  2142. while (!stop.load(std::memory_order_relaxed)) {
  2143. auto host = unique_unresolvable_host(t * 100000 + i++);
  2144. Client cli(host, 80);
  2145. cli.set_connection_timeout(1, 0);
  2146. cli.set_read_timeout(1, 0);
  2147. cli.set_write_timeout(1, 0);
  2148. (void)cli.Get("/");
  2149. }
  2150. });
  2151. }
  2152. std::this_thread::sleep_for(std::chrono::seconds(8));
  2153. stop.store(true, std::memory_order_relaxed);
  2154. for (auto &th : threads) {
  2155. th.join();
  2156. }
  2157. std::this_thread::sleep_for(std::chrono::seconds(3));
  2158. }
  2159. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2160. TEST(ConnectionErrorTest, InvalidHost) {
  2161. auto host = "-abcde.com";
  2162. #ifdef CPPHTTPLIB_SSL_ENABLED
  2163. auto port = 443;
  2164. SSLClient cli(host, port);
  2165. #else
  2166. auto port = 80;
  2167. Client cli(host, port);
  2168. #endif
  2169. cli.set_connection_timeout(std::chrono::seconds(2));
  2170. auto res = cli.Get("/");
  2171. ASSERT_TRUE(!res);
  2172. EXPECT_EQ(Error::Connection, res.error());
  2173. }
  2174. TEST(ConnectionErrorTest, InvalidHost2) {
  2175. auto host = "httpcan.org/";
  2176. #ifdef CPPHTTPLIB_SSL_ENABLED
  2177. SSLClient cli(host);
  2178. #else
  2179. Client cli(host);
  2180. #endif
  2181. cli.set_connection_timeout(std::chrono::seconds(2));
  2182. auto res = cli.Get("/");
  2183. ASSERT_TRUE(!res);
  2184. EXPECT_EQ(Error::Connection, res.error());
  2185. }
  2186. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2187. auto host = "httpcan.org/";
  2188. #ifdef CPPHTTPLIB_SSL_ENABLED
  2189. SSLClient cli(host);
  2190. #else
  2191. Client cli(host);
  2192. #endif
  2193. cli.set_connection_timeout(std::chrono::seconds(2));
  2194. auto res = cli.Get("/");
  2195. ASSERT_TRUE(!res);
  2196. stringstream s;
  2197. s << "error code: " << res.error();
  2198. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2199. }
  2200. TEST(ConnectionErrorTest, InvalidPort) {
  2201. auto host = "localhost";
  2202. auto port = 44380;
  2203. #ifdef CPPHTTPLIB_SSL_ENABLED
  2204. SSLClient cli(host, port);
  2205. #else
  2206. Client cli(host, port);
  2207. #endif
  2208. cli.set_connection_timeout(std::chrono::seconds(2));
  2209. auto res = cli.Get("/");
  2210. ASSERT_TRUE(!res);
  2211. EXPECT_TRUE(Error::Connection == res.error() ||
  2212. Error::ConnectionTimeout == res.error());
  2213. }
  2214. TEST(ConnectionErrorTest, Timeout_Online) {
  2215. auto host = "google.com";
  2216. #ifdef CPPHTTPLIB_SSL_ENABLED
  2217. auto port = 44380;
  2218. SSLClient cli(host, port);
  2219. #else
  2220. auto port = 8080;
  2221. Client cli(host, port);
  2222. #endif
  2223. cli.set_connection_timeout(std::chrono::seconds(2));
  2224. // only probe one address type so that the error reason
  2225. // correlates to the timed-out IPv4, not the unsupported
  2226. // IPv6 connection attempt
  2227. cli.set_address_family(AF_INET);
  2228. auto res = cli.Get("/");
  2229. ASSERT_TRUE(!res);
  2230. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2231. }
  2232. TEST(CancelTest, NoCancel_Online) {
  2233. auto host = "httpbingo.org";
  2234. auto path = std::string{"/range/32"};
  2235. #ifdef CPPHTTPLIB_SSL_ENABLED
  2236. auto port = 443;
  2237. SSLClient cli(host, port);
  2238. #else
  2239. auto port = 80;
  2240. Client cli(host, port);
  2241. #endif
  2242. cli.set_connection_timeout(std::chrono::seconds(5));
  2243. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2245. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2246. EXPECT_EQ(StatusCode::OK_200, res->status);
  2247. }
  2248. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2249. // Use /bytes with a large payload so that the DownloadProgress callback
  2250. // (which only fires for Content-Length responses) is invoked before the
  2251. // entire body is received, giving cancellation a chance to fire.
  2252. auto host = "httpbingo.org";
  2253. auto path = std::string{"/bytes/524288"};
  2254. #ifdef CPPHTTPLIB_SSL_ENABLED
  2255. auto port = 443;
  2256. SSLClient cli(host, port);
  2257. #else
  2258. auto port = 80;
  2259. Client cli(host, port);
  2260. #endif
  2261. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2262. cli.set_connection_timeout(std::chrono::seconds(5));
  2263. ASSERT_TRUE(!res);
  2264. EXPECT_EQ(Error::Canceled, res.error());
  2265. }
  2266. TEST(CancelTest, WithCancelLargePayload_Online) {
  2267. auto host = "httpbingo.org";
  2268. auto path = std::string{"/bytes/524288"};
  2269. #ifdef CPPHTTPLIB_SSL_ENABLED
  2270. auto port = 443;
  2271. SSLClient cli(host, port);
  2272. #else
  2273. auto port = 80;
  2274. Client cli(host, port);
  2275. #endif
  2276. cli.set_connection_timeout(std::chrono::seconds(5));
  2277. uint32_t count = 0;
  2278. auto res =
  2279. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2280. ASSERT_TRUE(!res);
  2281. EXPECT_EQ(Error::Canceled, res.error());
  2282. }
  2283. TEST(CancelTest, NoCancelPost) {
  2284. Server svr;
  2285. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2286. res.set_content("Hello World!", "text/plain");
  2287. });
  2288. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2289. auto se = detail::scope_exit([&] {
  2290. svr.stop();
  2291. thread.join();
  2292. ASSERT_FALSE(svr.is_running());
  2293. });
  2294. svr.wait_until_ready();
  2295. Client cli(HOST, PORT);
  2296. cli.set_connection_timeout(std::chrono::seconds(5));
  2297. auto res =
  2298. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2299. "application/json", [](uint64_t, uint64_t) { return true; });
  2300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2301. EXPECT_EQ("Hello World!", res->body);
  2302. EXPECT_EQ(StatusCode::OK_200, res->status);
  2303. }
  2304. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2305. Server svr;
  2306. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2307. res.set_content("Hello World!", "text/plain");
  2308. });
  2309. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2310. auto se = detail::scope_exit([&] {
  2311. svr.stop();
  2312. thread.join();
  2313. ASSERT_FALSE(svr.is_running());
  2314. });
  2315. svr.wait_until_ready();
  2316. Client cli(HOST, PORT);
  2317. cli.set_connection_timeout(std::chrono::seconds(5));
  2318. auto res =
  2319. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2320. "application/json", [](uint64_t, uint64_t) { return false; });
  2321. ASSERT_TRUE(!res);
  2322. EXPECT_EQ(Error::Canceled, res.error());
  2323. }
  2324. TEST(CancelTest, WithCancelLargePayloadPost) {
  2325. Server svr;
  2326. svr.set_payload_max_length(200 * 1024 * 1024);
  2327. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2328. res.set_content(LARGE_DATA, "text/plain");
  2329. });
  2330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2331. auto se = detail::scope_exit([&] {
  2332. svr.stop();
  2333. thread.join();
  2334. ASSERT_FALSE(svr.is_running());
  2335. });
  2336. svr.wait_until_ready();
  2337. Client cli(HOST, PORT);
  2338. cli.set_payload_max_length(200 * 1024 * 1024);
  2339. cli.set_connection_timeout(std::chrono::seconds(5));
  2340. auto res =
  2341. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2342. "application/json", [](uint64_t, uint64_t) { return false; });
  2343. ASSERT_TRUE(!res);
  2344. EXPECT_EQ(Error::Canceled, res.error());
  2345. }
  2346. TEST(CancelTest, NoCancelPut) {
  2347. Server svr;
  2348. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2349. res.set_content("Hello World!", "text/plain");
  2350. });
  2351. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2352. auto se = detail::scope_exit([&] {
  2353. svr.stop();
  2354. thread.join();
  2355. ASSERT_FALSE(svr.is_running());
  2356. });
  2357. svr.wait_until_ready();
  2358. Client cli(HOST, PORT);
  2359. cli.set_connection_timeout(std::chrono::seconds(5));
  2360. auto res =
  2361. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2362. "application/json", [](uint64_t, uint64_t) { return true; });
  2363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2364. EXPECT_EQ("Hello World!", res->body);
  2365. EXPECT_EQ(StatusCode::OK_200, res->status);
  2366. }
  2367. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2368. Server svr;
  2369. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2370. res.set_content("Hello World!", "text/plain");
  2371. });
  2372. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2373. auto se = detail::scope_exit([&] {
  2374. svr.stop();
  2375. thread.join();
  2376. ASSERT_FALSE(svr.is_running());
  2377. });
  2378. svr.wait_until_ready();
  2379. Client cli(HOST, PORT);
  2380. cli.set_connection_timeout(std::chrono::seconds(5));
  2381. auto res =
  2382. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2383. "application/json", [](uint64_t, uint64_t) { return false; });
  2384. ASSERT_TRUE(!res);
  2385. EXPECT_EQ(Error::Canceled, res.error());
  2386. }
  2387. TEST(CancelTest, WithCancelLargePayloadPut) {
  2388. Server svr;
  2389. svr.set_payload_max_length(200 * 1024 * 1024);
  2390. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2391. res.set_content(LARGE_DATA, "text/plain");
  2392. });
  2393. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2394. auto se = detail::scope_exit([&] {
  2395. svr.stop();
  2396. thread.join();
  2397. ASSERT_FALSE(svr.is_running());
  2398. });
  2399. svr.wait_until_ready();
  2400. Client cli(HOST, PORT);
  2401. cli.set_payload_max_length(200 * 1024 * 1024);
  2402. cli.set_connection_timeout(std::chrono::seconds(5));
  2403. auto res =
  2404. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2405. "application/json", [](uint64_t, uint64_t) { return false; });
  2406. ASSERT_TRUE(!res);
  2407. EXPECT_EQ(Error::Canceled, res.error());
  2408. }
  2409. TEST(CancelTest, NoCancelPatch) {
  2410. Server svr;
  2411. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2412. res.set_content("Hello World!", "text/plain");
  2413. });
  2414. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2415. auto se = detail::scope_exit([&] {
  2416. svr.stop();
  2417. thread.join();
  2418. ASSERT_FALSE(svr.is_running());
  2419. });
  2420. svr.wait_until_ready();
  2421. Client cli(HOST, PORT);
  2422. cli.set_connection_timeout(std::chrono::seconds(5));
  2423. auto res =
  2424. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2425. "application/json", [](uint64_t, uint64_t) { return true; });
  2426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2427. EXPECT_EQ("Hello World!", res->body);
  2428. EXPECT_EQ(StatusCode::OK_200, res->status);
  2429. }
  2430. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2431. Server svr;
  2432. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2433. res.set_content("Hello World!", "text/plain");
  2434. });
  2435. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2436. auto se = detail::scope_exit([&] {
  2437. svr.stop();
  2438. thread.join();
  2439. ASSERT_FALSE(svr.is_running());
  2440. });
  2441. svr.wait_until_ready();
  2442. Client cli(HOST, PORT);
  2443. cli.set_connection_timeout(std::chrono::seconds(5));
  2444. auto res =
  2445. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2446. "application/json", [](uint64_t, uint64_t) { return false; });
  2447. ASSERT_TRUE(!res);
  2448. EXPECT_EQ(Error::Canceled, res.error());
  2449. }
  2450. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2451. Server svr;
  2452. svr.set_payload_max_length(200 * 1024 * 1024);
  2453. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2454. res.set_content(LARGE_DATA, "text/plain");
  2455. });
  2456. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2457. auto se = detail::scope_exit([&] {
  2458. svr.stop();
  2459. thread.join();
  2460. ASSERT_FALSE(svr.is_running());
  2461. });
  2462. svr.wait_until_ready();
  2463. Client cli(HOST, PORT);
  2464. cli.set_payload_max_length(200 * 1024 * 1024);
  2465. cli.set_connection_timeout(std::chrono::seconds(5));
  2466. auto res =
  2467. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2468. "application/json", [](uint64_t, uint64_t) { return false; });
  2469. ASSERT_TRUE(!res);
  2470. EXPECT_EQ(Error::Canceled, res.error());
  2471. }
  2472. TEST(CancelTest, NoCancelDelete) {
  2473. Server svr;
  2474. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2475. res.set_content("Hello World!", "text/plain");
  2476. });
  2477. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2478. auto se = detail::scope_exit([&] {
  2479. svr.stop();
  2480. thread.join();
  2481. ASSERT_FALSE(svr.is_running());
  2482. });
  2483. svr.wait_until_ready();
  2484. Client cli(HOST, PORT);
  2485. cli.set_connection_timeout(std::chrono::seconds(5));
  2486. auto res =
  2487. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2488. "application/json", [](uint64_t, uint64_t) { return true; });
  2489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2490. EXPECT_EQ("Hello World!", res->body);
  2491. EXPECT_EQ(StatusCode::OK_200, res->status);
  2492. }
  2493. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2494. Server svr;
  2495. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2496. res.set_content("Hello World!", "text/plain");
  2497. });
  2498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2499. auto se = detail::scope_exit([&] {
  2500. svr.stop();
  2501. thread.join();
  2502. ASSERT_FALSE(svr.is_running());
  2503. });
  2504. svr.wait_until_ready();
  2505. Client cli(HOST, PORT);
  2506. cli.set_connection_timeout(std::chrono::seconds(5));
  2507. auto res =
  2508. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2509. "application/json", [](uint64_t, uint64_t) { return false; });
  2510. ASSERT_TRUE(!res);
  2511. EXPECT_EQ(Error::Canceled, res.error());
  2512. }
  2513. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2514. Server svr;
  2515. svr.set_payload_max_length(200 * 1024 * 1024);
  2516. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2517. res.set_content(LARGE_DATA, "text/plain");
  2518. });
  2519. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2520. auto se = detail::scope_exit([&] {
  2521. svr.stop();
  2522. thread.join();
  2523. ASSERT_FALSE(svr.is_running());
  2524. });
  2525. svr.wait_until_ready();
  2526. Client cli(HOST, PORT);
  2527. cli.set_payload_max_length(200 * 1024 * 1024);
  2528. cli.set_connection_timeout(std::chrono::seconds(5));
  2529. auto res =
  2530. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2531. "application/json", [](uint64_t, uint64_t) { return false; });
  2532. ASSERT_TRUE(!res);
  2533. EXPECT_EQ(Error::Canceled, res.error());
  2534. }
  2535. static std::string remove_whitespace(const std::string &input) {
  2536. std::string output;
  2537. output.reserve(input.size());
  2538. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2539. [](unsigned char c) { return !std::isspace(c); });
  2540. return output;
  2541. }
  2542. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2543. auto host = "httpbingo.org";
  2544. auto path = std::string{"/basic-auth/hello/world"};
  2545. #ifdef CPPHTTPLIB_SSL_ENABLED
  2546. auto port = 443;
  2547. SSLClient cli(host, port);
  2548. #else
  2549. auto port = 80;
  2550. Client cli(host, port);
  2551. #endif
  2552. {
  2553. auto res = cli.Get(path);
  2554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2555. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2556. }
  2557. {
  2558. auto res = cli.Get(
  2559. path, Headers{make_basic_authentication_header("hello", "world")});
  2560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2561. auto body = remove_whitespace(res->body);
  2562. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2563. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2564. EXPECT_EQ(StatusCode::OK_200, res->status);
  2565. }
  2566. {
  2567. cli.set_basic_auth("hello", "world");
  2568. auto res = cli.Get(path);
  2569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2570. auto body = remove_whitespace(res->body);
  2571. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2572. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2573. EXPECT_EQ(StatusCode::OK_200, res->status);
  2574. }
  2575. {
  2576. cli.set_basic_auth("hello", "bad");
  2577. auto res = cli.Get(path);
  2578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2579. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2580. }
  2581. {
  2582. cli.set_basic_auth("bad", "world");
  2583. auto res = cli.Get(path);
  2584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2585. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2586. }
  2587. }
  2588. #ifdef CPPHTTPLIB_SSL_ENABLED
  2589. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2590. auto host = "httpbingo.org";
  2591. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2592. auto paths = std::vector<std::string>{
  2593. "/digest-auth/auth/hello/world/MD5",
  2594. "/digest-auth/auth/hello/world/SHA-256",
  2595. };
  2596. auto port = 443;
  2597. SSLClient cli(host, port);
  2598. {
  2599. auto res = cli.Get(unauth_path);
  2600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2601. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2602. }
  2603. {
  2604. cli.set_digest_auth("hello", "world");
  2605. for (const auto &path : paths) {
  2606. auto res = cli.Get(path.c_str());
  2607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2608. auto body = remove_whitespace(res->body);
  2609. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2610. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2611. EXPECT_EQ(StatusCode::OK_200, res->status);
  2612. }
  2613. cli.set_digest_auth("hello", "bad");
  2614. for (const auto &path : paths) {
  2615. auto res = cli.Get(path.c_str());
  2616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2617. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2618. }
  2619. }
  2620. }
  2621. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2622. // comma-separated list of challenges, and each challenge may itself carry a
  2623. // comma-separated auth-param list, so a server can legally offer Basic
  2624. // before Digest, either as two field lines or packed into one. Runs one 401
  2625. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2626. // value() joins them in receipt order) and checks that the retry carries a
  2627. // well-formed Digest Authorization header naming expected_realm.
  2628. static void
  2629. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2630. const std::string &expected_realm) {
  2631. std::atomic<int> hits{0};
  2632. Server svr;
  2633. svr.Get("/x", [&](const Request &req, Response &res) {
  2634. if (++hits == 1) {
  2635. res.status = StatusCode::Unauthorized_401;
  2636. for (const auto &challenge : challenges) {
  2637. res.set_header("WWW-Authenticate", challenge);
  2638. }
  2639. } else {
  2640. auto authorization = req.get_header_value("Authorization");
  2641. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2642. EXPECT_NE(std::string::npos,
  2643. authorization.find("realm=\"" + expected_realm + "\""));
  2644. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2645. res.set_content("ok", "text/plain");
  2646. }
  2647. });
  2648. auto port = svr.bind_to_any_port(HOST);
  2649. std::thread t([&]() { svr.listen_after_bind(); });
  2650. auto se = detail::scope_exit([&] {
  2651. svr.stop();
  2652. t.join();
  2653. });
  2654. svr.wait_until_ready();
  2655. Client cli(HOST, port);
  2656. cli.set_digest_auth("hello", "world");
  2657. auto res = cli.Get("/x");
  2658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2659. EXPECT_EQ(2, hits.load());
  2660. }
  2661. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2662. static const char *kDigestChallenge =
  2663. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2664. "algorithm=MD5";
  2665. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2666. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2667. "testrealm");
  2668. }
  2669. // Same challenge list with the schemes in the opposite order, to make sure
  2670. // the fix above didn't just special-case "Basic first".
  2671. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2672. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2673. "testrealm");
  2674. }
  2675. // A comma inside a quoted auth-param value must not be mistaken for the
  2676. // separator between two challenges (or two auth-params).
  2677. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2678. run_digest_challenge_list_test(
  2679. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2680. "algorithm=MD5"},
  2681. "test,realm");
  2682. }
  2683. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2684. // make_digest_authentication_header() dereferences both unconditionally, so
  2685. // a server sending a challenge missing either one must not be treated as
  2686. // usable -- doing so used to crash the client with std::out_of_range.
  2687. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2688. Server svr;
  2689. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2690. res.status = StatusCode::Unauthorized_401;
  2691. res.set_header("WWW-Authenticate", challenge);
  2692. });
  2693. auto port = svr.bind_to_any_port(HOST);
  2694. std::thread t([&]() { svr.listen_after_bind(); });
  2695. auto se = detail::scope_exit([&] {
  2696. svr.stop();
  2697. t.join();
  2698. });
  2699. svr.wait_until_ready();
  2700. Client cli(HOST, port);
  2701. cli.set_digest_auth("hello", "world");
  2702. auto res = cli.Get("/x");
  2703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2704. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2705. }
  2706. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2707. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2708. }
  2709. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2710. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2711. }
  2712. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2713. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2714. }
  2715. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2716. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2717. // when storing the values, so the header builder has to re-escape them (and
  2718. // keep algorithm a bare token); otherwise the value breaks out of its
  2719. // quoted-string and injects extra auth-params into the client's Authorization.
  2720. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2721. std::atomic<int> hits{0};
  2722. std::string authorization;
  2723. Server svr;
  2724. svr.Get("/x", [&](const Request &req, Response &res) {
  2725. if (++hits == 1) {
  2726. res.status = StatusCode::Unauthorized_401;
  2727. // On the wire the quotes embedded in the values are backslash-escaped.
  2728. res.set_header("WWW-Authenticate",
  2729. "Digest realm=\"testrealm\", "
  2730. "nonce=\"n\\\"; injected=\\\"x\", "
  2731. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2732. } else {
  2733. authorization = req.get_header_value("Authorization");
  2734. res.set_content("ok", "text/plain");
  2735. }
  2736. });
  2737. auto port = svr.bind_to_any_port(HOST);
  2738. std::thread t([&]() { svr.listen_after_bind(); });
  2739. auto se = detail::scope_exit([&] {
  2740. svr.stop();
  2741. t.join();
  2742. });
  2743. svr.wait_until_ready();
  2744. Client cli(HOST, port);
  2745. cli.set_digest_auth("hello", "world");
  2746. auto res = cli.Get("/x");
  2747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2748. EXPECT_EQ(2, hits.load());
  2749. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2750. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2751. // inside its quoted-string rather than starting an "injected" auth-param.
  2752. EXPECT_NE(std::string::npos,
  2753. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2754. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2755. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2756. }
  2757. #endif
  2758. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2759. auto host = "google.com";
  2760. auto another_host = "example.com";
  2761. auto wrong_ip = "0.0.0.0";
  2762. #ifdef CPPHTTPLIB_SSL_ENABLED
  2763. SSLClient cli(host);
  2764. #else
  2765. Client cli(host);
  2766. #endif
  2767. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2768. auto res = cli.Get("/");
  2769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2770. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2771. }
  2772. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2773. auto host = "google.com";
  2774. auto wrong_ip = "0.0.0.0";
  2775. #ifdef CPPHTTPLIB_SSL_ENABLED
  2776. SSLClient cli(host);
  2777. #else
  2778. Client cli(host);
  2779. #endif
  2780. cli.set_hostname_addr_map({{host, wrong_ip}});
  2781. auto res = cli.Get("/");
  2782. ASSERT_TRUE(!res);
  2783. EXPECT_EQ(Error::Connection, res.error());
  2784. }
  2785. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2786. // A mapped value that is not an IP literal must be resolved. "localhost"
  2787. // resolves from the hosts file, so this test needs no external DNS.
  2788. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2789. auto host = "target.invalid";
  2790. Server svr;
  2791. std::string received_host;
  2792. svr.Get("/hi", [&](const Request &req, Response &res) {
  2793. received_host = req.get_header_value("Host");
  2794. res.set_content("Hello World!", "text/plain");
  2795. });
  2796. auto port = svr.bind_to_any_port(HOST);
  2797. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2798. auto se = detail::scope_exit([&] {
  2799. svr.stop();
  2800. thread.join();
  2801. ASSERT_FALSE(svr.is_running());
  2802. });
  2803. svr.wait_until_ready();
  2804. Client cli(host, port);
  2805. cli.set_hostname_addr_map({{host, HOST}});
  2806. auto res = cli.Get("/hi");
  2807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2808. EXPECT_EQ(StatusCode::OK_200, res->status);
  2809. // The mapping only redirects the connection; the identity stays host_.
  2810. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2811. }
  2812. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2813. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2814. auto host = "target.invalid";
  2815. Server svr;
  2816. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2817. res.set_content("Hello World!", "text/plain");
  2818. });
  2819. auto port = svr.bind_to_any_port("127.0.0.1");
  2820. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2821. auto se = detail::scope_exit([&] {
  2822. svr.stop();
  2823. thread.join();
  2824. ASSERT_FALSE(svr.is_running());
  2825. });
  2826. svr.wait_until_ready();
  2827. Client cli(host, port);
  2828. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2829. auto res = cli.Get("/hi");
  2830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2831. EXPECT_EQ(StatusCode::OK_200, res->status);
  2832. }
  2833. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2834. // An empty mapped value must leave host_ as the connection target. Without
  2835. // that guard the empty value would become the host argument, getaddrinfo
  2836. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2837. // loopback - silently connecting somewhere the caller never asked for.
  2838. // The server listens on loopback, so such a fallback would succeed and is
  2839. // therefore observable as a failure of this test.
  2840. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2841. Server svr;
  2842. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2843. res.set_content("Hello World!", "text/plain");
  2844. });
  2845. auto port = svr.bind_to_any_port(HOST);
  2846. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2847. auto se = detail::scope_exit([&] {
  2848. svr.stop();
  2849. thread.join();
  2850. ASSERT_FALSE(svr.is_running());
  2851. });
  2852. svr.wait_until_ready();
  2853. Client cli(blackhole, port);
  2854. cli.set_hostname_addr_map({{blackhole, ""}});
  2855. cli.set_connection_timeout(1);
  2856. auto res = cli.Get("/hi");
  2857. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2858. }
  2859. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2860. auto host = "httpbingo.org";
  2861. auto path = std::string{"/absolute-redirect/3"};
  2862. #ifdef CPPHTTPLIB_SSL_ENABLED
  2863. SSLClient cli(host);
  2864. #else
  2865. Client cli(host);
  2866. #endif
  2867. cli.set_follow_location(true);
  2868. auto res = cli.Get(path);
  2869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2870. EXPECT_EQ(StatusCode::OK_200, res->status);
  2871. }
  2872. TEST(RedirectTest, Redirect_Online) {
  2873. auto host = "httpbingo.org";
  2874. auto path = std::string{"/redirect/3"};
  2875. #ifdef CPPHTTPLIB_SSL_ENABLED
  2876. SSLClient cli(host);
  2877. #else
  2878. Client cli(host);
  2879. #endif
  2880. cli.set_follow_location(true);
  2881. auto res = cli.Get(path);
  2882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2883. EXPECT_EQ(StatusCode::OK_200, res->status);
  2884. }
  2885. TEST(RelativeRedirectTest, Redirect_Online) {
  2886. auto host = "httpbingo.org";
  2887. auto path = std::string{"/relative-redirect/3"};
  2888. #ifdef CPPHTTPLIB_SSL_ENABLED
  2889. SSLClient cli(host);
  2890. #else
  2891. Client cli(host);
  2892. #endif
  2893. cli.set_follow_location(true);
  2894. auto res = cli.Get(path);
  2895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2896. EXPECT_EQ(StatusCode::OK_200, res->status);
  2897. }
  2898. TEST(TooManyRedirectTest, Redirect_Online) {
  2899. auto host = "httpbingo.org";
  2900. auto path = std::string{"/redirect/21"};
  2901. #ifdef CPPHTTPLIB_SSL_ENABLED
  2902. SSLClient cli(host);
  2903. #else
  2904. Client cli(host);
  2905. #endif
  2906. cli.set_follow_location(true);
  2907. auto res = cli.Get(path);
  2908. ASSERT_TRUE(!res);
  2909. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2910. }
  2911. #ifdef CPPHTTPLIB_SSL_ENABLED
  2912. TEST(YahooRedirectTest, Redirect_Online) {
  2913. Client cli("yahoo.com");
  2914. auto res = cli.Get("/");
  2915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2916. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2917. cli.set_follow_location(true);
  2918. res = cli.Get("/");
  2919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2920. EXPECT_EQ(StatusCode::OK_200, res->status);
  2921. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2922. }
  2923. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2924. #define REDIR_HOST "httpbingo.org"
  2925. #define REDIR_PATH "/redirect-to"
  2926. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2927. SSLClient cli(REDIR_HOST);
  2928. cli.set_follow_location(true);
  2929. auto res =
  2930. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2932. EXPECT_EQ(StatusCode::OK_200, res->status);
  2933. }
  2934. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2935. SSLClient cli(REDIR_HOST);
  2936. cli.set_follow_location(true);
  2937. Params params;
  2938. params.emplace("url", "http://example.com");
  2939. params.emplace("status_code", "302");
  2940. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2942. EXPECT_EQ(StatusCode::OK_200, res->status);
  2943. }
  2944. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2945. SSLClient cli(REDIR_HOST);
  2946. cli.set_follow_location(true);
  2947. Params params;
  2948. params.emplace("url", "http://example.com");
  2949. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2951. EXPECT_EQ(StatusCode::OK_200, res->status);
  2952. }
  2953. TEST(UrlWithSpace, Redirect_Online) {
  2954. SSLClient cli("edge.forgecdn.net");
  2955. cli.set_follow_location(true);
  2956. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2958. EXPECT_EQ(StatusCode::OK_200, res->status);
  2959. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2960. }
  2961. #endif
  2962. #if !defined(_WIN32) && !defined(_WIN64)
  2963. TEST(ReceiveSignals, Signal) {
  2964. auto setupSignalHandlers = []() {
  2965. struct sigaction act;
  2966. sigemptyset(&act.sa_mask);
  2967. act.sa_flags = SA_SIGINFO;
  2968. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2969. switch (sig) {
  2970. case SIGINT:
  2971. default: break;
  2972. }
  2973. };
  2974. ::sigaction(SIGINT, &act, nullptr);
  2975. };
  2976. Server svr;
  2977. int port = 0;
  2978. auto thread = std::thread([&]() {
  2979. setupSignalHandlers();
  2980. port = svr.bind_to_any_port(HOST);
  2981. svr.listen_after_bind();
  2982. });
  2983. auto se = detail::scope_exit([&] {
  2984. svr.stop();
  2985. thread.join();
  2986. ASSERT_FALSE(svr.is_running());
  2987. });
  2988. svr.wait_until_ready();
  2989. ASSERT_TRUE(svr.is_running());
  2990. pthread_kill(thread.native_handle(), SIGINT);
  2991. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2992. ASSERT_TRUE(svr.is_running());
  2993. }
  2994. #endif
  2995. TEST(RedirectToDifferentPort, Redirect) {
  2996. Server svr1;
  2997. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2998. res.set_content("Hello World!", "text/plain");
  2999. });
  3000. int svr1_port = 0;
  3001. auto thread1 = std::thread([&]() {
  3002. svr1_port = svr1.bind_to_any_port(HOST);
  3003. svr1.listen_after_bind();
  3004. });
  3005. Server svr2;
  3006. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3007. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3008. });
  3009. int svr2_port = 0;
  3010. auto thread2 = std::thread([&]() {
  3011. svr2_port = svr2.bind_to_any_port(HOST);
  3012. svr2.listen_after_bind();
  3013. });
  3014. auto se = detail::scope_exit([&] {
  3015. svr2.stop();
  3016. thread2.join();
  3017. svr1.stop();
  3018. thread1.join();
  3019. ASSERT_FALSE(svr2.is_running());
  3020. ASSERT_FALSE(svr1.is_running());
  3021. });
  3022. svr1.wait_until_ready();
  3023. svr2.wait_until_ready();
  3024. Client cli("localhost", svr2_port);
  3025. cli.set_follow_location(true);
  3026. auto res = cli.Get("/2");
  3027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3028. EXPECT_EQ(StatusCode::OK_200, res->status);
  3029. EXPECT_EQ("Hello World!", res->body);
  3030. }
  3031. static void
  3032. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3033. Server svr1;
  3034. std::string captured_authorization;
  3035. svr1.Get("/target", [&](const Request &req, Response &res) {
  3036. captured_authorization = req.get_header_value("Authorization");
  3037. res.set_content("OK", "text/plain");
  3038. });
  3039. int svr1_port = 0;
  3040. auto thread1 = std::thread([&]() {
  3041. svr1_port = svr1.bind_to_any_port(HOST);
  3042. svr1.listen_after_bind();
  3043. });
  3044. Server svr2;
  3045. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3046. res.set_redirect(
  3047. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3048. });
  3049. int svr2_port = 0;
  3050. auto thread2 = std::thread([&]() {
  3051. svr2_port = svr2.bind_to_any_port(HOST);
  3052. svr2.listen_after_bind();
  3053. });
  3054. auto se = detail::scope_exit([&] {
  3055. svr2.stop();
  3056. thread2.join();
  3057. svr1.stop();
  3058. thread1.join();
  3059. ASSERT_FALSE(svr2.is_running());
  3060. ASSERT_FALSE(svr1.is_running());
  3061. });
  3062. svr1.wait_until_ready();
  3063. svr2.wait_until_ready();
  3064. Client cli("localhost", svr2_port);
  3065. cli.set_follow_location(true);
  3066. set_auth(cli);
  3067. auto res = cli.Get("/redir");
  3068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3069. EXPECT_EQ(StatusCode::OK_200, res->status);
  3070. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3071. EXPECT_TRUE(captured_authorization.empty());
  3072. }
  3073. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3074. TestDoNotForwardCredentialsOnRedirect(
  3075. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3076. }
  3077. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3078. TestDoNotForwardCredentialsOnRedirect(
  3079. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3080. }
  3081. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3082. Server svr1;
  3083. std::string captured_cookie;
  3084. bool target_hit = false;
  3085. svr1.Get("/target", [&](const Request &req, Response &res) {
  3086. captured_cookie = req.get_header_value("Cookie");
  3087. target_hit = true;
  3088. res.set_content("OK", "text/plain");
  3089. });
  3090. int svr1_port = 0;
  3091. auto thread1 = std::thread([&]() {
  3092. svr1_port = svr1.bind_to_any_port(HOST);
  3093. svr1.listen_after_bind();
  3094. });
  3095. Server svr2;
  3096. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3097. res.set_redirect(
  3098. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3099. });
  3100. int svr2_port = 0;
  3101. auto thread2 = std::thread([&]() {
  3102. svr2_port = svr2.bind_to_any_port(HOST);
  3103. svr2.listen_after_bind();
  3104. });
  3105. auto se = detail::scope_exit([&] {
  3106. svr2.stop();
  3107. thread2.join();
  3108. svr1.stop();
  3109. thread1.join();
  3110. ASSERT_FALSE(svr2.is_running());
  3111. ASSERT_FALSE(svr1.is_running());
  3112. });
  3113. svr1.wait_until_ready();
  3114. svr2.wait_until_ready();
  3115. Client cli("localhost", svr2_port);
  3116. cli.set_follow_location(true);
  3117. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3118. auto res = cli.Get("/redir", headers);
  3119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3120. EXPECT_EQ(StatusCode::OK_200, res->status);
  3121. EXPECT_TRUE(target_hit);
  3122. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3123. EXPECT_TRUE(captured_cookie.empty());
  3124. }
  3125. TEST(RedirectToSamePort, ForwardCookie) {
  3126. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3127. // header so that ordinary session flows keep working.
  3128. Server svr;
  3129. std::string captured_cookie;
  3130. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3131. res.set_redirect("/target", 302);
  3132. });
  3133. svr.Get("/target", [&](const Request &req, Response &res) {
  3134. captured_cookie = req.get_header_value("Cookie");
  3135. res.set_content("OK", "text/plain");
  3136. });
  3137. auto port = svr.bind_to_any_port(HOST);
  3138. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3139. auto se = detail::scope_exit([&] {
  3140. svr.stop();
  3141. thread.join();
  3142. ASSERT_FALSE(svr.is_running());
  3143. });
  3144. svr.wait_until_ready();
  3145. Client cli(HOST, port);
  3146. cli.set_follow_location(true);
  3147. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3148. auto res = cli.Get("/redir", headers);
  3149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3150. EXPECT_EQ(StatusCode::OK_200, res->status);
  3151. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3152. }
  3153. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3154. Server svr;
  3155. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3156. // Port number that overflows int — should not crash
  3157. res.set_redirect("http://localhost:99999999999999999999/target");
  3158. });
  3159. auto port = svr.bind_to_any_port(HOST);
  3160. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3161. auto se = detail::scope_exit([&] {
  3162. svr.stop();
  3163. thread.join();
  3164. ASSERT_FALSE(svr.is_running());
  3165. });
  3166. svr.wait_until_ready();
  3167. Client cli(HOST, port);
  3168. cli.set_follow_location(true);
  3169. auto res = cli.Get("/redir");
  3170. // Should fail gracefully, not crash (no valid response due to bad port)
  3171. EXPECT_FALSE(res);
  3172. }
  3173. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3174. Server svr;
  3175. auto port = svr.bind_to_any_port(HOST);
  3176. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3177. // The server's own port followed by junk must not be followed
  3178. res.set_redirect("http://" + std::string(HOST) + ":" +
  3179. std::to_string(port) + "junk/target");
  3180. });
  3181. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3182. res.set_content("target", "text/plain");
  3183. });
  3184. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3185. auto se = detail::scope_exit([&] {
  3186. svr.stop();
  3187. thread.join();
  3188. ASSERT_FALSE(svr.is_running());
  3189. });
  3190. svr.wait_until_ready();
  3191. Client cli(HOST, port);
  3192. cli.set_follow_location(true);
  3193. auto res = cli.Get("/redir");
  3194. EXPECT_FALSE(res);
  3195. }
  3196. TEST(RedirectFromPageWithContent, Redirect) {
  3197. Server svr;
  3198. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3199. res.set_content("___", "text/plain");
  3200. res.set_redirect("/2");
  3201. });
  3202. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3203. res.set_content("Hello World!", "text/plain");
  3204. });
  3205. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3206. auto se = detail::scope_exit([&] {
  3207. svr.stop();
  3208. th.join();
  3209. ASSERT_FALSE(svr.is_running());
  3210. });
  3211. svr.wait_until_ready();
  3212. {
  3213. Client cli("localhost", PORT);
  3214. cli.set_follow_location(true);
  3215. std::string body;
  3216. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3217. body.append(data, data_length);
  3218. return true;
  3219. });
  3220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3221. EXPECT_EQ(StatusCode::OK_200, res->status);
  3222. EXPECT_EQ("Hello World!", body);
  3223. }
  3224. {
  3225. Client cli("localhost", PORT);
  3226. std::string body;
  3227. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3228. body.append(data, data_length);
  3229. return true;
  3230. });
  3231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3232. EXPECT_EQ(StatusCode::Found_302, res->status);
  3233. EXPECT_EQ("___", body);
  3234. }
  3235. }
  3236. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3237. Server svr;
  3238. auto port_str = std::to_string(PORT);
  3239. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3240. auto expected_host = "[::1]:" + port_str;
  3241. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3242. res.set_content("___", "text/plain");
  3243. // res.set_redirect("/2");
  3244. res.set_redirect(redirect_url);
  3245. });
  3246. svr.Get("/2", [&](const Request &req, Response &res) {
  3247. auto host_header = req.headers.find("Host");
  3248. ASSERT_TRUE(host_header != req.headers.end());
  3249. EXPECT_EQ(expected_host, host_header->second);
  3250. res.set_content("Hello World!", "text/plain");
  3251. });
  3252. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3253. auto se = detail::scope_exit([&] {
  3254. svr.stop();
  3255. th.join();
  3256. ASSERT_FALSE(svr.is_running());
  3257. });
  3258. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3259. // actually starts anything, so the condition !svr.is_running() will
  3260. // always remain true, and the loop never stops.
  3261. // This basically counts how many milliseconds have passed since the
  3262. // call to svr.listen(), and if after 5 seconds nothing started yet
  3263. // aborts the test.
  3264. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3265. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3266. ASSERT_LT(milliseconds, 5000U);
  3267. }
  3268. {
  3269. Client cli("::1", PORT);
  3270. cli.set_follow_location(true);
  3271. std::string body;
  3272. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3273. body.append(data, data_length);
  3274. return true;
  3275. });
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. EXPECT_EQ(StatusCode::OK_200, res->status);
  3278. EXPECT_EQ("Hello World!", body);
  3279. }
  3280. {
  3281. Client cli("::1", PORT);
  3282. std::string body;
  3283. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3284. body.append(data, data_length);
  3285. return true;
  3286. });
  3287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3288. EXPECT_EQ(StatusCode::Found_302, res->status);
  3289. EXPECT_EQ("___", body);
  3290. }
  3291. }
  3292. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3293. Server svr;
  3294. svr.Get("/foo", [](const Request &req, Response &res) {
  3295. auto a = req.params.find("a");
  3296. if (a != req.params.end()) {
  3297. res.set_content((*a).second, "text/plain");
  3298. res.status = StatusCode::OK_200;
  3299. } else {
  3300. res.status = StatusCode::BadRequest_400;
  3301. }
  3302. });
  3303. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3304. auto se = detail::scope_exit([&] {
  3305. svr.stop();
  3306. thread.join();
  3307. ASSERT_FALSE(svr.is_running());
  3308. });
  3309. svr.wait_until_ready();
  3310. {
  3311. Client cli(HOST, PORT);
  3312. cli.set_path_encode(false);
  3313. auto res = cli.Get("/foo?a=explicitly+encoded");
  3314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3315. EXPECT_EQ(StatusCode::OK_200, res->status);
  3316. // This expects it back with a space, as the `+` won't have been
  3317. // url-encoded, and server-side the params get decoded turning `+`
  3318. // into spaces.
  3319. EXPECT_EQ("explicitly encoded", res->body);
  3320. }
  3321. }
  3322. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3323. // When path encoding is disabled the client must transmit the supplied
  3324. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3325. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3326. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3327. // than a space (0x20). Assert on the raw wire target to catch this.
  3328. Server svr;
  3329. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3330. svr.Get("/foo", [&](const Request &req, Response &res) {
  3331. EXPECT_EQ(expected_target, req.target);
  3332. res.status = StatusCode::OK_200;
  3333. });
  3334. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3335. auto se = detail::scope_exit([&] {
  3336. svr.stop();
  3337. thread.join();
  3338. ASSERT_FALSE(svr.is_running());
  3339. });
  3340. svr.wait_until_ready();
  3341. {
  3342. Client cli(HOST, PORT);
  3343. cli.set_path_encode(false);
  3344. auto res = cli.Get(expected_target.c_str());
  3345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3346. EXPECT_EQ(StatusCode::OK_200, res->status);
  3347. }
  3348. }
  3349. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3350. // `open_stream()` used to skip the path encoding that the buffered send
  3351. // path applies, so the same `path` produced different bytes in the request
  3352. // line depending on which API was used. Assert the two agree.
  3353. Server svr;
  3354. std::string target;
  3355. svr.Get(".*", [&](const Request &req, Response &res) {
  3356. target = req.target;
  3357. res.status = StatusCode::OK_200;
  3358. });
  3359. auto port = svr.bind_to_any_port(HOST);
  3360. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3361. auto se = detail::scope_exit([&] {
  3362. svr.stop();
  3363. thread.join();
  3364. ASSERT_FALSE(svr.is_running());
  3365. });
  3366. svr.wait_until_ready();
  3367. struct {
  3368. const char *path;
  3369. const char *expected;
  3370. } cases[] = {
  3371. {"/a b?x=1", "/a%20b?x=1"},
  3372. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3373. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3374. };
  3375. for (const auto &c : cases) {
  3376. Client cli(HOST, port);
  3377. target.clear();
  3378. auto res = cli.Get(c.path);
  3379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3380. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3381. auto buffered_target = target;
  3382. target.clear();
  3383. auto handle = cli.open_stream("GET", c.path);
  3384. EXPECT_TRUE(handle.is_valid())
  3385. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3386. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3387. }
  3388. }
  3389. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3390. // The `set_path_encode(false)` contract — transmit the supplied target
  3391. // verbatim — must hold for the streaming API too.
  3392. Server svr;
  3393. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3394. std::string target;
  3395. svr.Get("/foo", [&](const Request &req, Response &res) {
  3396. target = req.target;
  3397. res.status = StatusCode::OK_200;
  3398. });
  3399. auto port = svr.bind_to_any_port(HOST);
  3400. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3401. auto se = detail::scope_exit([&] {
  3402. svr.stop();
  3403. thread.join();
  3404. ASSERT_FALSE(svr.is_running());
  3405. });
  3406. svr.wait_until_ready();
  3407. {
  3408. Client cli(HOST, port);
  3409. cli.set_path_encode(false);
  3410. auto handle = cli.open_stream("GET", expected_target);
  3411. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3412. EXPECT_EQ(expected_target, target);
  3413. }
  3414. }
  3415. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3416. // With path encoding enabled a CR/LF in the target is percent-encoded
  3417. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3418. // write_request_line still backstops `set_path_encode(false)`, which is
  3419. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3420. Server svr;
  3421. // Captured before routing: the decoded path contains a newline, which a
  3422. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3423. std::string target;
  3424. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3425. target = req.target;
  3426. res.status = StatusCode::OK_200;
  3427. return Server::HandlerResponse::Handled;
  3428. });
  3429. auto port = svr.bind_to_any_port(HOST);
  3430. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3431. auto se = detail::scope_exit([&] {
  3432. svr.stop();
  3433. thread.join();
  3434. ASSERT_FALSE(svr.is_running());
  3435. });
  3436. svr.wait_until_ready();
  3437. {
  3438. Client cli(HOST, port);
  3439. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3440. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3441. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3442. }
  3443. }
  3444. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3445. // Every control character is percent-encoded, not just CR/LF, so the target
  3446. // passes the request-target check in write_request_line.
  3447. Server svr;
  3448. std::string target;
  3449. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3450. target = req.target;
  3451. res.status = StatusCode::OK_200;
  3452. return Server::HandlerResponse::Handled;
  3453. });
  3454. auto port = svr.bind_to_any_port(HOST);
  3455. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3456. auto se = detail::scope_exit([&] {
  3457. svr.stop();
  3458. thread.join();
  3459. ASSERT_FALSE(svr.is_running());
  3460. });
  3461. svr.wait_until_ready();
  3462. {
  3463. Client cli(HOST, port);
  3464. auto res = cli.Get("/a\tb\x1b\x7f");
  3465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3466. EXPECT_EQ("/a%09b%1B%7F", target);
  3467. }
  3468. }
  3469. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3470. // Nothing may reach the wire: a raw CR/LF target would split the request
  3471. // line and inject headers.
  3472. Server svr;
  3473. // Pre-routing so that "not called" means nothing reached the server at all,
  3474. // rather than merely failing to match a handler pattern.
  3475. auto handler_called = false;
  3476. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3477. handler_called = true;
  3478. res.status = StatusCode::OK_200;
  3479. return Server::HandlerResponse::Handled;
  3480. });
  3481. auto port = svr.bind_to_any_port(HOST);
  3482. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3483. auto se = detail::scope_exit([&] {
  3484. svr.stop();
  3485. thread.join();
  3486. ASSERT_FALSE(svr.is_running());
  3487. });
  3488. svr.wait_until_ready();
  3489. {
  3490. Client cli(HOST, port);
  3491. cli.set_path_encode(false);
  3492. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3493. EXPECT_FALSE(handle.is_valid());
  3494. EXPECT_EQ(Error::Write, handle.error);
  3495. EXPECT_FALSE(handler_called);
  3496. }
  3497. }
  3498. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3499. // Which of the two branches runs is decided by whether the query component
  3500. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3501. // an empty query and must still fall back to building one from
  3502. // `req.params`, while a non-empty query must win over `req.params`.
  3503. Server svr;
  3504. std::string target;
  3505. svr.Get("/foo", [&](const Request &req, Response &res) {
  3506. target = req.target;
  3507. res.status = StatusCode::OK_200;
  3508. });
  3509. auto port = svr.bind_to_any_port(HOST);
  3510. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3511. auto se = detail::scope_exit([&] {
  3512. svr.stop();
  3513. thread.join();
  3514. ASSERT_FALSE(svr.is_running());
  3515. });
  3516. svr.wait_until_ready();
  3517. {
  3518. // Trailing `?` -> empty query component -> `req.params` is used.
  3519. Client cli(HOST, port);
  3520. Request req;
  3521. req.method = "GET";
  3522. req.path = "/foo?";
  3523. req.params.emplace("a", "1");
  3524. target.clear();
  3525. auto res = cli.send(req);
  3526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3527. EXPECT_EQ("/foo?a=1", target);
  3528. }
  3529. {
  3530. // Non-empty query in `req.path` -> `req.params` is not appended.
  3531. Client cli(HOST, port);
  3532. Request req;
  3533. req.method = "GET";
  3534. req.path = "/foo?b=2";
  3535. req.params.emplace("a", "1");
  3536. target.clear();
  3537. auto res = cli.send(req);
  3538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3539. EXPECT_EQ("/foo?b=2", target);
  3540. }
  3541. }
  3542. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3543. Server svr;
  3544. svr.Get("/", [](const Request &req, Response &) {
  3545. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3546. });
  3547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3548. auto se = detail::scope_exit([&] {
  3549. svr.stop();
  3550. thread.join();
  3551. ASSERT_FALSE(svr.is_running());
  3552. });
  3553. svr.wait_until_ready();
  3554. {
  3555. Client cli(HOST, PORT);
  3556. cli.set_path_encode(false);
  3557. auto res = cli.Get("/?something=%0A");
  3558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3559. EXPECT_EQ(StatusCode::OK_200, res->status);
  3560. }
  3561. }
  3562. TEST(BindServerTest, BindDualStack) {
  3563. Server svr;
  3564. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3565. res.set_content("Hello World!", "text/plain");
  3566. });
  3567. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3568. auto se = detail::scope_exit([&] {
  3569. svr.stop();
  3570. thread.join();
  3571. ASSERT_FALSE(svr.is_running());
  3572. });
  3573. svr.wait_until_ready();
  3574. {
  3575. Client cli("127.0.0.1", PORT);
  3576. auto res = cli.Get("/1");
  3577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3578. EXPECT_EQ(StatusCode::OK_200, res->status);
  3579. EXPECT_EQ("Hello World!", res->body);
  3580. }
  3581. {
  3582. Client cli("::1", PORT);
  3583. auto res = cli.Get("/1");
  3584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3585. EXPECT_EQ(StatusCode::OK_200, res->status);
  3586. EXPECT_EQ("Hello World!", res->body);
  3587. }
  3588. }
  3589. TEST(BindServerTest, BindAndListenSeparately) {
  3590. Server svr;
  3591. int port = svr.bind_to_any_port("0.0.0.0");
  3592. ASSERT_TRUE(svr.is_valid());
  3593. ASSERT_TRUE(port > 0);
  3594. svr.stop();
  3595. }
  3596. // Reports whether anything is still listening on a loopback port. A plain
  3597. // connect() is used instead of a Client request because a socket left bound by
  3598. // mistake accepts the connection into its backlog and never answers, which
  3599. // would hang the test instead of failing it.
  3600. static bool is_loopback_port_accepting(int port) {
  3601. sockaddr_in addr{};
  3602. addr.sin_family = AF_INET;
  3603. addr.sin_port = htons(static_cast<uint16_t>(port));
  3604. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3605. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3606. EXPECT_NE(sock, INVALID_SOCKET);
  3607. if (sock == INVALID_SOCKET) { return false; }
  3608. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3609. static_cast<socklen_t>(sizeof(addr)));
  3610. detail::close_socket(sock);
  3611. return ret == 0;
  3612. }
  3613. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3614. Server svr;
  3615. auto port = svr.bind_to_any_port("127.0.0.1");
  3616. ASSERT_TRUE(port > 0);
  3617. svr.stop();
  3618. // bind_to_any_port() already called listen(2), so until stop() closed the
  3619. // descriptor the port kept accepting connections into the backlog. ASSERT
  3620. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3621. // below blocks forever in the accept loop.
  3622. ASSERT_FALSE(is_loopback_port_accepting(port));
  3623. // Nothing is left to accept on, so listen_after_bind() must report failure
  3624. // instead of returning success without ever serving.
  3625. EXPECT_FALSE(svr.listen_after_bind());
  3626. // The failed listen marks the server decommissioned, so a waiter returns
  3627. // instead of spinning forever.
  3628. svr.wait_until_ready();
  3629. }
  3630. #ifdef CPPHTTPLIB_SSL_ENABLED
  3631. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3632. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3633. CLIENT_CA_CERT_DIR);
  3634. int port = svr.bind_to_any_port("0.0.0.0");
  3635. ASSERT_TRUE(svr.is_valid());
  3636. ASSERT_TRUE(port > 0);
  3637. svr.stop();
  3638. }
  3639. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3640. // or a rejected CustomRoute() registration would not stop the server binding.
  3641. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3642. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3643. CLIENT_CA_CERT_DIR);
  3644. ASSERT_TRUE(svr.is_valid());
  3645. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3646. EXPECT_FALSE(svr.is_valid());
  3647. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3648. }
  3649. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3650. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3651. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3652. int port = svr.bind_to_any_port("0.0.0.0");
  3653. ASSERT_TRUE(svr.is_valid());
  3654. ASSERT_TRUE(port > 0);
  3655. svr.stop();
  3656. }
  3657. TEST(BindServerTest, UpdateCertsPem) {
  3658. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3659. int port = svr.bind_to_any_port("0.0.0.0");
  3660. ASSERT_TRUE(svr.is_valid());
  3661. ASSERT_TRUE(port > 0);
  3662. // Read PEM files
  3663. std::string cert_pem, key_pem, ca_pem;
  3664. read_file(SERVER_CERT_FILE, cert_pem);
  3665. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3666. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3667. // Update server certificates using PEM API
  3668. ASSERT_TRUE(
  3669. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3670. ASSERT_TRUE(svr.is_valid());
  3671. svr.stop();
  3672. }
  3673. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3674. // Start server with client CA (enables client auth)
  3675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3676. ASSERT_TRUE(svr.is_valid());
  3677. bool handler_called = false;
  3678. svr.Get("/test", [&](const Request &req, Response &res) {
  3679. handler_called = true;
  3680. // Verify client certificate is present
  3681. auto cert = req.peer_cert();
  3682. EXPECT_TRUE(static_cast<bool>(cert));
  3683. res.set_content("ok", "text/plain");
  3684. });
  3685. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3686. auto se = detail::scope_exit([&] {
  3687. svr.stop();
  3688. t.join();
  3689. ASSERT_FALSE(svr.is_running());
  3690. });
  3691. svr.wait_until_ready();
  3692. // Read PEM files
  3693. std::string cert_pem, key_pem, ca_pem;
  3694. read_file(SERVER_CERT_FILE, cert_pem);
  3695. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3696. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3697. // Update server certificates and client CA using PEM API while server running
  3698. ASSERT_TRUE(
  3699. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3700. // Connect with client certificate
  3701. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3702. cli.enable_server_certificate_verification(false);
  3703. cli.set_connection_timeout(30);
  3704. auto res = cli.Get("/test");
  3705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3706. ASSERT_EQ(StatusCode::OK_200, res->status);
  3707. ASSERT_TRUE(handler_called);
  3708. EXPECT_EQ("ok", res->body);
  3709. }
  3710. #endif
  3711. TEST(ErrorHandlerTest, ContentLength) {
  3712. Server svr;
  3713. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3714. res.status = StatusCode::OK_200;
  3715. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3716. "text/html"); // <= Content-Length still 13
  3717. });
  3718. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3719. res.set_content("Hello World!\n", "text/plain");
  3720. res.status = 524;
  3721. });
  3722. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3723. auto se = detail::scope_exit([&] {
  3724. svr.stop();
  3725. thread.join();
  3726. ASSERT_FALSE(svr.is_running());
  3727. });
  3728. svr.wait_until_ready();
  3729. {
  3730. Client cli(HOST, PORT);
  3731. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3733. EXPECT_EQ(StatusCode::OK_200, res->status);
  3734. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3735. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3736. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3737. }
  3738. }
  3739. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3740. TEST(ExceptionTest, WithoutExceptionHandler) {
  3741. Server svr;
  3742. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3743. throw std::runtime_error("exception...");
  3744. });
  3745. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3746. throw std::runtime_error("exception\r\n...");
  3747. });
  3748. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3749. auto se = detail::scope_exit([&] {
  3750. svr.stop();
  3751. listen_thread.join();
  3752. ASSERT_FALSE(svr.is_running());
  3753. });
  3754. svr.wait_until_ready();
  3755. Client cli("localhost", PORT);
  3756. {
  3757. auto res = cli.Get("/exception");
  3758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3759. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3760. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3761. }
  3762. {
  3763. auto res = cli.Get("/unknown");
  3764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3765. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3766. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3767. }
  3768. }
  3769. TEST(ExceptionTest, WithExceptionHandler) {
  3770. Server svr;
  3771. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3772. std::exception_ptr ep) {
  3773. EXPECT_FALSE(ep == nullptr);
  3774. try {
  3775. std::rethrow_exception(ep);
  3776. } catch (std::exception &e) {
  3777. EXPECT_EQ("abc", std::string(e.what()));
  3778. } catch (...) {}
  3779. res.status = StatusCode::InternalServerError_500;
  3780. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3781. "text/html"); // <= Content-Length still 13 at this point
  3782. });
  3783. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3784. res.set_content("Hello World!\n", "text/plain");
  3785. throw std::runtime_error("abc");
  3786. });
  3787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3788. auto se = detail::scope_exit([&] {
  3789. svr.stop();
  3790. thread.join();
  3791. ASSERT_FALSE(svr.is_running());
  3792. });
  3793. svr.wait_until_ready();
  3794. for (size_t i = 0; i < 10; i++) {
  3795. Client cli(HOST, PORT);
  3796. for (size_t j = 0; j < 100; j++) {
  3797. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3799. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3800. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3801. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3802. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3803. }
  3804. cli.set_keep_alive(true);
  3805. for (size_t j = 0; j < 100; j++) {
  3806. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3808. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3809. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3810. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3811. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3812. }
  3813. }
  3814. }
  3815. TEST(ExceptionTest, AndErrorHandler) {
  3816. Server svr;
  3817. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3818. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3819. });
  3820. svr.set_exception_handler(
  3821. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3822. EXPECT_FALSE(ep == nullptr);
  3823. try {
  3824. std::rethrow_exception(ep);
  3825. } catch (std::exception &e) {
  3826. res.set_content(e.what(), "text/html");
  3827. } catch (...) {}
  3828. res.status = StatusCode::InternalServerError_500;
  3829. });
  3830. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3831. throw std::runtime_error("EXCEPTION");
  3832. });
  3833. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3834. res.set_content("ERROR", "text/html");
  3835. res.status = StatusCode::InternalServerError_500;
  3836. });
  3837. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3838. auto se = detail::scope_exit([&] {
  3839. svr.stop();
  3840. thread.join();
  3841. ASSERT_FALSE(svr.is_running());
  3842. });
  3843. svr.wait_until_ready();
  3844. Client cli(HOST, PORT);
  3845. {
  3846. auto res = cli.Get("/exception");
  3847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3848. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3849. EXPECT_EQ("EXCEPTION", res->body);
  3850. }
  3851. {
  3852. auto res = cli.Get("/error");
  3853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3854. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3855. EXPECT_EQ("ERROR", res->body);
  3856. }
  3857. {
  3858. auto res = cli.Get("/invalid");
  3859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3860. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3861. EXPECT_EQ("NOT_FOUND", res->body);
  3862. }
  3863. }
  3864. #endif
  3865. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3866. // process_request() wraps only routing() in a try/catch, so an exception from
  3867. // any other user callback used to unwind into the task queue - which does not
  3868. // catch - and terminate the process. Each test below runs the server on a
  3869. // single worker thread: a guard that catches the exception but still loses the
  3870. // thread would otherwise be hidden by a spare worker serving the follow-up
  3871. // request. Note that a regression here aborts the whole test binary rather
  3872. // than failing one test.
  3873. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3874. Server svr;
  3875. svr.new_task_queue = [] { return new ThreadPool(1); };
  3876. std::atomic<int> reported{0};
  3877. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3878. if (err == Error::UserCallbackException) { reported++; }
  3879. });
  3880. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3881. res.set_content_provider(
  3882. 1024, "text/plain",
  3883. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3884. sink.write("hello", 5);
  3885. throw std::runtime_error("from the content provider");
  3886. });
  3887. });
  3888. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3889. res.set_content("ok", "text/plain");
  3890. });
  3891. auto port = svr.bind_to_any_port(HOST);
  3892. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3893. auto se = detail::scope_exit([&] {
  3894. svr.stop();
  3895. listen_thread.join();
  3896. ASSERT_FALSE(svr.is_running());
  3897. });
  3898. svr.wait_until_ready();
  3899. {
  3900. Client cli(HOST, port);
  3901. cli.set_read_timeout(5, 0);
  3902. EXPECT_FALSE(cli.Get("/throw"));
  3903. }
  3904. EXPECT_TRUE(svr.is_running());
  3905. EXPECT_EQ(1, reported.load());
  3906. // A request on a fresh connection is still served.
  3907. {
  3908. Client cli(HOST, port);
  3909. auto res = cli.Get("/ok");
  3910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3911. EXPECT_EQ(StatusCode::OK_200, res->status);
  3912. EXPECT_EQ("ok", res->body);
  3913. }
  3914. }
  3915. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3916. Server svr;
  3917. svr.new_task_queue = [] { return new ThreadPool(1); };
  3918. std::atomic<bool> should_throw{true};
  3919. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3920. res.set_content("hi", "text/plain");
  3921. });
  3922. svr.set_post_routing_handler(
  3923. [&](const Request & /*req*/, Response & /*res*/) {
  3924. if (should_throw) {
  3925. throw std::runtime_error("from the post-routing handler");
  3926. }
  3927. });
  3928. auto port = svr.bind_to_any_port(HOST);
  3929. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3930. auto se = detail::scope_exit([&] {
  3931. svr.stop();
  3932. listen_thread.join();
  3933. ASSERT_FALSE(svr.is_running());
  3934. });
  3935. svr.wait_until_ready();
  3936. {
  3937. Client cli(HOST, port);
  3938. cli.set_read_timeout(5, 0);
  3939. EXPECT_FALSE(cli.Get("/hi"));
  3940. }
  3941. EXPECT_TRUE(svr.is_running());
  3942. should_throw = false;
  3943. {
  3944. Client cli(HOST, port);
  3945. auto res = cli.Get("/hi");
  3946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3947. EXPECT_EQ(StatusCode::OK_200, res->status);
  3948. EXPECT_EQ("hi", res->body);
  3949. }
  3950. }
  3951. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3952. // The guard reports the caught exception through the error logger, which is
  3953. // a user callback too. A logger that throws has to be contained as well, or
  3954. // the process would terminate from inside the catch.
  3955. Server svr;
  3956. svr.new_task_queue = [] { return new ThreadPool(1); };
  3957. std::atomic<int> reported{0};
  3958. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3959. if (err == Error::UserCallbackException) {
  3960. reported++;
  3961. throw std::runtime_error("from the error logger");
  3962. }
  3963. });
  3964. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3965. res.set_content_provider(
  3966. 1024, "text/plain",
  3967. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3968. sink.write("hello", 5);
  3969. throw std::runtime_error("from the content provider");
  3970. });
  3971. });
  3972. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3973. res.set_content("ok", "text/plain");
  3974. });
  3975. auto port = svr.bind_to_any_port(HOST);
  3976. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3977. auto se = detail::scope_exit([&] {
  3978. svr.stop();
  3979. listen_thread.join();
  3980. ASSERT_FALSE(svr.is_running());
  3981. });
  3982. svr.wait_until_ready();
  3983. {
  3984. Client cli(HOST, port);
  3985. cli.set_read_timeout(5, 0);
  3986. EXPECT_FALSE(cli.Get("/throw"));
  3987. }
  3988. EXPECT_TRUE(svr.is_running());
  3989. EXPECT_EQ(1, reported.load());
  3990. {
  3991. Client cli(HOST, port);
  3992. auto res = cli.Get("/ok");
  3993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3994. EXPECT_EQ(StatusCode::OK_200, res->status);
  3995. EXPECT_EQ("ok", res->body);
  3996. }
  3997. }
  3998. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3999. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4000. // so the exception unwinds through the ws::WebSocket object on its way to
  4001. // the guard. None of the HTTP cases above cross that.
  4002. Server svr;
  4003. svr.new_task_queue = [] { return new ThreadPool(1); };
  4004. std::atomic<int> reported{0};
  4005. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4006. if (err == Error::UserCallbackException) { reported++; }
  4007. });
  4008. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4009. throw std::runtime_error("from the WebSocket handler");
  4010. });
  4011. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4012. res.set_content("ok", "text/plain");
  4013. });
  4014. auto port = svr.bind_to_any_port(HOST);
  4015. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4016. auto se = detail::scope_exit([&] {
  4017. svr.stop();
  4018. listen_thread.join();
  4019. ASSERT_FALSE(svr.is_running());
  4020. });
  4021. svr.wait_until_ready();
  4022. {
  4023. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4024. "/ws");
  4025. auto res = client.connect();
  4026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4027. // The server dropped the connection instead of dying.
  4028. std::string msg;
  4029. EXPECT_FALSE(client.read(msg));
  4030. client.close();
  4031. }
  4032. EXPECT_TRUE(svr.is_running());
  4033. EXPECT_EQ(1, reported.load());
  4034. {
  4035. Client cli(HOST, port);
  4036. auto res = cli.Get("/ok");
  4037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4038. EXPECT_EQ(StatusCode::OK_200, res->status);
  4039. EXPECT_EQ("ok", res->body);
  4040. }
  4041. }
  4042. #ifdef CPPHTTPLIB_SSL_ENABLED
  4043. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4044. // SSLServer::process_and_close_socket() is a separate overload with its own
  4045. // guard, so it is exercised on its own.
  4046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4047. ASSERT_TRUE(svr.is_valid());
  4048. svr.new_task_queue = [] { return new ThreadPool(1); };
  4049. std::atomic<int> reported{0};
  4050. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4051. if (err == Error::UserCallbackException) { reported++; }
  4052. });
  4053. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4054. res.set_content_provider(
  4055. 1024, "text/plain",
  4056. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4057. sink.write("hello", 5);
  4058. throw std::runtime_error("from the content provider");
  4059. });
  4060. });
  4061. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4062. res.set_content("ok", "text/plain");
  4063. });
  4064. auto port = svr.bind_to_any_port(HOST);
  4065. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4066. auto se = detail::scope_exit([&] {
  4067. svr.stop();
  4068. listen_thread.join();
  4069. ASSERT_FALSE(svr.is_running());
  4070. });
  4071. svr.wait_until_ready();
  4072. {
  4073. SSLClient cli(HOST, port);
  4074. cli.enable_server_certificate_verification(false);
  4075. cli.set_read_timeout(5, 0);
  4076. EXPECT_FALSE(cli.Get("/throw"));
  4077. }
  4078. EXPECT_TRUE(svr.is_running());
  4079. EXPECT_EQ(1, reported.load());
  4080. {
  4081. SSLClient cli(HOST, port);
  4082. cli.enable_server_certificate_verification(false);
  4083. auto res = cli.Get("/ok");
  4084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4085. EXPECT_EQ(StatusCode::OK_200, res->status);
  4086. EXPECT_EQ("ok", res->body);
  4087. }
  4088. }
  4089. #endif
  4090. #endif
  4091. TEST(NoContentTest, ContentLength) {
  4092. Server svr;
  4093. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4094. res.status = StatusCode::NoContent_204;
  4095. });
  4096. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4097. auto se = detail::scope_exit([&] {
  4098. svr.stop();
  4099. thread.join();
  4100. ASSERT_FALSE(svr.is_running());
  4101. });
  4102. svr.wait_until_ready();
  4103. {
  4104. Client cli(HOST, PORT);
  4105. auto res = cli.Get("/hi");
  4106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4107. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4108. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4109. }
  4110. }
  4111. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4112. #ifdef CPPHTTPLIB_SSL_ENABLED
  4113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4114. ASSERT_TRUE(svr.is_valid());
  4115. #else
  4116. Server svr;
  4117. #endif
  4118. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4119. if (req.path == "/routing_handler") {
  4120. res.set_header("PRE_ROUTING", "on");
  4121. res.set_content("Routing Handler", "text/plain");
  4122. return httplib::Server::HandlerResponse::Handled;
  4123. }
  4124. return httplib::Server::HandlerResponse::Unhandled;
  4125. });
  4126. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4127. res.set_content("Error", "text/html");
  4128. });
  4129. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4130. if (req.path == "/routing_handler") {
  4131. res.set_header("POST_ROUTING", "on");
  4132. }
  4133. });
  4134. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4135. res.set_content("Hello World!\n", "text/plain");
  4136. });
  4137. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4138. auto se = detail::scope_exit([&] {
  4139. svr.stop();
  4140. thread.join();
  4141. ASSERT_FALSE(svr.is_running());
  4142. });
  4143. svr.wait_until_ready();
  4144. {
  4145. #ifdef CPPHTTPLIB_SSL_ENABLED
  4146. SSLClient cli(HOST, PORT);
  4147. cli.enable_server_certificate_verification(false);
  4148. #else
  4149. Client cli(HOST, PORT);
  4150. #endif
  4151. auto res = cli.Get("/routing_handler");
  4152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4153. EXPECT_EQ(StatusCode::OK_200, res->status);
  4154. EXPECT_EQ("Routing Handler", res->body);
  4155. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4156. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4157. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4158. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4159. }
  4160. {
  4161. #ifdef CPPHTTPLIB_SSL_ENABLED
  4162. SSLClient cli(HOST, PORT);
  4163. cli.enable_server_certificate_verification(false);
  4164. #else
  4165. Client cli(HOST, PORT);
  4166. #endif
  4167. auto res = cli.Get("/hi");
  4168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4169. EXPECT_EQ(StatusCode::OK_200, res->status);
  4170. EXPECT_EQ("Hello World!\n", res->body);
  4171. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4172. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4173. }
  4174. {
  4175. #ifdef CPPHTTPLIB_SSL_ENABLED
  4176. SSLClient cli(HOST, PORT);
  4177. cli.enable_server_certificate_verification(false);
  4178. #else
  4179. Client cli(HOST, PORT);
  4180. #endif
  4181. auto res = cli.Get("/aaa");
  4182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4183. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4184. EXPECT_EQ("Error", res->body);
  4185. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4186. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4187. }
  4188. }
  4189. TEST(RequestHandlerTest, PreRequestHandler) {
  4190. auto route_path = "/user/:user";
  4191. Server svr;
  4192. svr.Get("/hi", [](const Request &, Response &res) {
  4193. res.set_content("hi", "text/plain");
  4194. });
  4195. svr.Get(route_path, [](const Request &req, Response &res) {
  4196. res.set_content(req.path_params.at("user"), "text/plain");
  4197. });
  4198. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4199. if (req.matched_route == route_path) {
  4200. auto user = req.path_params.at("user");
  4201. if (user != "john") {
  4202. res.status = StatusCode::Forbidden_403;
  4203. res.set_content("error", "text/html");
  4204. return Server::HandlerResponse::Handled;
  4205. }
  4206. }
  4207. return Server::HandlerResponse::Unhandled;
  4208. });
  4209. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4210. auto se = detail::scope_exit([&] {
  4211. svr.stop();
  4212. thread.join();
  4213. ASSERT_FALSE(svr.is_running());
  4214. });
  4215. svr.wait_until_ready();
  4216. Client cli(HOST, PORT);
  4217. {
  4218. auto res = cli.Get("/hi");
  4219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4220. EXPECT_EQ(StatusCode::OK_200, res->status);
  4221. EXPECT_EQ("hi", res->body);
  4222. }
  4223. {
  4224. auto res = cli.Get("/user/john");
  4225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4226. EXPECT_EQ(StatusCode::OK_200, res->status);
  4227. EXPECT_EQ("john", res->body);
  4228. }
  4229. {
  4230. auto res = cli.Get("/user/invalid-user");
  4231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4232. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4233. EXPECT_EQ("error", res->body);
  4234. }
  4235. }
  4236. // The pre-request handler must run before the request body is read, so a
  4237. // rejected request never forces the server to buffer a (potentially large)
  4238. // body. Here the posted body is larger than the payload limit: if the body
  4239. // were read first the server would answer 413, but because the pre-request
  4240. // handler runs first it answers 403 and the body is never read.
  4241. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4242. Server svr;
  4243. svr.set_payload_max_length(8);
  4244. auto handler_ran = false;
  4245. svr.Post("/reject", [&](const Request &req, Response &res) {
  4246. handler_ran = true;
  4247. res.set_content(req.body, "text/plain");
  4248. });
  4249. svr.Post("/accept", [](const Request &req, Response &res) {
  4250. res.set_content(req.body, "text/plain");
  4251. });
  4252. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4253. if (req.matched_route == "/reject") {
  4254. res.status = StatusCode::Forbidden_403;
  4255. res.set_content("denied", "text/plain");
  4256. return Server::HandlerResponse::Handled;
  4257. }
  4258. return Server::HandlerResponse::Unhandled;
  4259. });
  4260. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4261. auto se = detail::scope_exit([&] {
  4262. svr.stop();
  4263. thread.join();
  4264. ASSERT_FALSE(svr.is_running());
  4265. });
  4266. svr.wait_until_ready();
  4267. Client cli(HOST, PORT);
  4268. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4269. // rejects with 403 before the body is read, so 413 is never reached.
  4270. {
  4271. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4273. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4274. EXPECT_EQ("denied", res->body);
  4275. EXPECT_FALSE(handler_ran);
  4276. }
  4277. // An approved route still reads the body and enforces the payload limit.
  4278. {
  4279. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4281. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4282. }
  4283. }
  4284. TEST(UserDataTest, BasicOperations) {
  4285. httplib::UserData ud;
  4286. // Initially empty
  4287. EXPECT_FALSE(ud.has("key"));
  4288. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4289. // set and get
  4290. ud.set("key", 42);
  4291. EXPECT_TRUE(ud.has("key"));
  4292. auto *p = ud.get<int>("key");
  4293. ASSERT_NE(nullptr, p);
  4294. EXPECT_EQ(42, *p);
  4295. // Type mismatch → nullptr
  4296. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4297. // Overwrite with different type
  4298. ud.set("key", std::string("hello"));
  4299. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4300. auto *s = ud.get<std::string>("key");
  4301. ASSERT_NE(nullptr, s);
  4302. EXPECT_EQ("hello", *s);
  4303. // erase
  4304. ud.erase("key");
  4305. EXPECT_FALSE(ud.has("key"));
  4306. // clear
  4307. ud.set("a", 1);
  4308. ud.set("b", 2);
  4309. ud.clear();
  4310. EXPECT_FALSE(ud.has("a"));
  4311. EXPECT_FALSE(ud.has("b"));
  4312. }
  4313. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4314. struct AuthCtx {
  4315. std::string user_id;
  4316. };
  4317. Server svr;
  4318. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4319. res.user_data.set("auth", AuthCtx{"alice"});
  4320. return Server::HandlerResponse::Unhandled;
  4321. });
  4322. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4323. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4324. ASSERT_NE(nullptr, ctx);
  4325. res.set_content("Hello " + ctx->user_id, "text/plain");
  4326. });
  4327. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4328. auto se = detail::scope_exit([&] {
  4329. svr.stop();
  4330. thread.join();
  4331. ASSERT_FALSE(svr.is_running());
  4332. });
  4333. svr.wait_until_ready();
  4334. Client cli(HOST, PORT);
  4335. auto res = cli.Get("/me");
  4336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4337. EXPECT_EQ(StatusCode::OK_200, res->status);
  4338. EXPECT_EQ("Hello alice", res->body);
  4339. }
  4340. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4341. struct RoleCtx {
  4342. std::string role;
  4343. };
  4344. Server svr;
  4345. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4346. res.user_data.set("role", RoleCtx{"admin"});
  4347. return Server::HandlerResponse::Unhandled;
  4348. });
  4349. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4350. auto *ctx = res.user_data.get<RoleCtx>("role");
  4351. ASSERT_NE(nullptr, ctx);
  4352. res.set_content(ctx->role, "text/plain");
  4353. });
  4354. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4355. auto se = detail::scope_exit([&] {
  4356. svr.stop();
  4357. thread.join();
  4358. ASSERT_FALSE(svr.is_running());
  4359. });
  4360. svr.wait_until_ready();
  4361. Client cli(HOST, PORT);
  4362. auto res = cli.Get("/role");
  4363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4364. EXPECT_EQ(StatusCode::OK_200, res->status);
  4365. EXPECT_EQ("admin", res->body);
  4366. }
  4367. TEST(InvalidFormatTest, StatusCode) {
  4368. Server svr;
  4369. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4370. res.set_content("Hello World!\n", "text/plain");
  4371. res.status = 9999; // Status should be a three-digit code...
  4372. });
  4373. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4374. auto se = detail::scope_exit([&] {
  4375. svr.stop();
  4376. thread.join();
  4377. ASSERT_FALSE(svr.is_running());
  4378. });
  4379. svr.wait_until_ready();
  4380. {
  4381. Client cli(HOST, PORT);
  4382. auto res = cli.Get("/hi");
  4383. ASSERT_FALSE(res);
  4384. }
  4385. }
  4386. TEST(URLFragmentTest, WithFragment) {
  4387. Server svr;
  4388. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4389. EXPECT_TRUE(req.target == "/hi");
  4390. });
  4391. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4392. auto se = detail::scope_exit([&] {
  4393. svr.stop();
  4394. thread.join();
  4395. ASSERT_FALSE(svr.is_running());
  4396. });
  4397. svr.wait_until_ready();
  4398. {
  4399. Client cli(HOST, PORT);
  4400. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4401. EXPECT_TRUE(res);
  4402. EXPECT_EQ(StatusCode::OK_200, res->status);
  4403. res = cli.Get("/hi%23key1=val1=key2=val2");
  4404. EXPECT_TRUE(res);
  4405. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4406. }
  4407. }
  4408. TEST(HeaderWriter, SetHeaderWriter) {
  4409. Server svr;
  4410. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4411. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4412. return detail::write_headers(strm, hdrs);
  4413. });
  4414. svr.Get("/hi", [](const Request &req, Response &res) {
  4415. auto it = req.headers.find("CustomClientHeader");
  4416. EXPECT_TRUE(it != req.headers.end());
  4417. EXPECT_EQ(it->second, "CustomClientValue");
  4418. res.set_content("Hello World!\n", "text/plain");
  4419. });
  4420. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4421. auto se = detail::scope_exit([&] {
  4422. svr.stop();
  4423. thread.join();
  4424. ASSERT_FALSE(svr.is_running());
  4425. });
  4426. svr.wait_until_ready();
  4427. {
  4428. Client cli(HOST, PORT);
  4429. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4430. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4431. return detail::write_headers(strm, hdrs);
  4432. });
  4433. auto res = cli.Get("/hi");
  4434. EXPECT_TRUE(res);
  4435. EXPECT_EQ(StatusCode::OK_200, res->status);
  4436. auto it = res->headers.find("CustomServerHeader");
  4437. EXPECT_TRUE(it != res->headers.end());
  4438. EXPECT_EQ(it->second, "CustomServerValue");
  4439. }
  4440. }
  4441. class ServerTest : public ::testing::Test {
  4442. protected:
  4443. ServerTest()
  4444. : cli_(HOST, PORT)
  4445. #ifdef CPPHTTPLIB_SSL_ENABLED
  4446. ,
  4447. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4448. #endif
  4449. {
  4450. #ifdef CPPHTTPLIB_SSL_ENABLED
  4451. cli_.enable_server_certificate_verification(false);
  4452. #endif
  4453. // Allow LARGE_DATA (100MB) responses
  4454. cli_.set_payload_max_length(200 * 1024 * 1024);
  4455. }
  4456. virtual void SetUp() {
  4457. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4458. svr_.set_payload_max_length(200 * 1024 * 1024);
  4459. svr_.set_mount_point("/", "./www");
  4460. svr_.set_mount_point("/mount", "./www2");
  4461. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4462. svr_.Get("/hi",
  4463. [&](const Request & /*req*/, Response &res) {
  4464. res.set_content("Hello World!", "text/plain");
  4465. })
  4466. .Get("/file_content",
  4467. [&](const Request & /*req*/, Response &res) {
  4468. res.set_file_content("./www/dir/test.html");
  4469. })
  4470. .Get("/file_content_with_content_type",
  4471. [&](const Request & /*req*/, Response &res) {
  4472. res.set_file_content("./www/file", "text/plain");
  4473. })
  4474. .Get("/invalid_file_content",
  4475. [&](const Request & /*req*/, Response &res) {
  4476. res.set_file_content("./www/dir/invalid_file_path");
  4477. })
  4478. .Get("/http_response_splitting",
  4479. [&](const Request & /*req*/, Response &res) {
  4480. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4481. EXPECT_EQ(0U, res.headers.size());
  4482. EXPECT_FALSE(res.has_header("a"));
  4483. res.set_header("a", "1\nSet-Cookie: a=1");
  4484. EXPECT_EQ(0U, res.headers.size());
  4485. EXPECT_FALSE(res.has_header("a"));
  4486. res.set_header("a", "1\rSet-Cookie: a=1");
  4487. EXPECT_EQ(0U, res.headers.size());
  4488. EXPECT_FALSE(res.has_header("a"));
  4489. res.set_header("a\r\nb", "0");
  4490. EXPECT_EQ(0U, res.headers.size());
  4491. EXPECT_FALSE(res.has_header("a"));
  4492. res.set_header("a\rb", "0");
  4493. EXPECT_EQ(0U, res.headers.size());
  4494. EXPECT_FALSE(res.has_header("a"));
  4495. res.set_header("a\nb", "0");
  4496. EXPECT_EQ(0U, res.headers.size());
  4497. EXPECT_FALSE(res.has_header("a"));
  4498. res.set_redirect("1\r\nSet-Cookie: a=1");
  4499. EXPECT_EQ(0U, res.headers.size());
  4500. EXPECT_FALSE(res.has_header("Location"));
  4501. })
  4502. .Get("/slow",
  4503. [&](const Request & /*req*/, Response &res) {
  4504. std::this_thread::sleep_for(std::chrono::seconds(4));
  4505. res.set_content("slow", "text/plain");
  4506. })
  4507. #if 0
  4508. .Post("/slowpost",
  4509. [&](const Request & /*req*/, Response &res) {
  4510. std::this_thread::sleep_for(std::chrono::seconds(2));
  4511. res.set_content("slow", "text/plain");
  4512. })
  4513. #endif
  4514. .Get("/remote_addr",
  4515. [&](const Request &req, Response &res) {
  4516. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4517. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4518. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4519. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4520. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4521. #endif
  4522. res.set_content(req.remote_addr, "text/plain");
  4523. })
  4524. .Get("/local_addr",
  4525. [&](const Request &req, Response &res) {
  4526. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4527. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4528. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4529. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4530. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4531. #endif
  4532. auto local_addr = req.local_addr;
  4533. auto local_port = std::to_string(req.local_port);
  4534. res.set_content(local_addr.append(":").append(local_port),
  4535. "text/plain");
  4536. })
  4537. .Get("/endwith%",
  4538. [&](const Request & /*req*/, Response &res) {
  4539. res.set_content("Hello World!", "text/plain");
  4540. })
  4541. .Get("/a\\+\\+b",
  4542. [&](const Request &req, Response &res) {
  4543. ASSERT_TRUE(req.has_param("a +b"));
  4544. auto val = req.get_param_value("a +b");
  4545. res.set_content(val, "text/plain");
  4546. })
  4547. .Get("/", [&](const Request & /*req*/,
  4548. Response &res) { res.set_redirect("/hi"); })
  4549. .Post("/1",
  4550. [](const Request & /*req*/, Response &res) {
  4551. res.set_redirect("/2", StatusCode::SeeOther_303);
  4552. })
  4553. .Get("/2",
  4554. [](const Request & /*req*/, Response &res) {
  4555. res.set_content("redirected.", "text/plain");
  4556. res.status = StatusCode::OK_200;
  4557. })
  4558. .Post("/person",
  4559. [&](const Request &req, Response &res) {
  4560. if (req.has_param("name") && req.has_param("note")) {
  4561. persons_[req.get_param_value("name")] =
  4562. req.get_param_value("note");
  4563. } else {
  4564. res.status = StatusCode::BadRequest_400;
  4565. }
  4566. })
  4567. .Put("/person",
  4568. [&](const Request &req, Response &res) {
  4569. if (req.has_param("name") && req.has_param("note")) {
  4570. persons_[req.get_param_value("name")] =
  4571. req.get_param_value("note");
  4572. } else {
  4573. res.status = StatusCode::BadRequest_400;
  4574. }
  4575. })
  4576. .Get("/person/(.*)",
  4577. [&](const Request &req, Response &res) {
  4578. string name = req.matches[1];
  4579. if (persons_.find(name) != persons_.end()) {
  4580. auto note = persons_[name];
  4581. res.set_content(note, "text/plain");
  4582. } else {
  4583. res.status = StatusCode::NotFound_404;
  4584. }
  4585. })
  4586. .Delete("/person",
  4587. [&](const Request &req, Response &res) {
  4588. if (req.has_param("name")) {
  4589. string name = req.get_param_value("name");
  4590. if (persons_.find(name) != persons_.end()) {
  4591. persons_.erase(name);
  4592. res.set_content("DELETED", "text/plain");
  4593. } else {
  4594. res.status = StatusCode::NotFound_404;
  4595. }
  4596. } else {
  4597. res.status = StatusCode::BadRequest_400;
  4598. }
  4599. })
  4600. .Post("/x-www-form-urlencoded-json",
  4601. [&](const Request &req, Response &res) {
  4602. auto json = req.get_param_value("json");
  4603. ASSERT_EQ(JSON_DATA, json);
  4604. res.set_content(json, "appliation/json");
  4605. res.status = StatusCode::OK_200;
  4606. })
  4607. .Get("/streamed-chunked",
  4608. [&](const Request & /*req*/, Response &res) {
  4609. res.set_chunked_content_provider(
  4610. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4611. sink.os << "123";
  4612. sink.os << "456";
  4613. sink.os << "789";
  4614. sink.done();
  4615. return true;
  4616. });
  4617. })
  4618. .Get("/streamed-chunked-with-prohibited-trailer",
  4619. [&](const Request & /*req*/, Response &res) {
  4620. auto i = new int(0);
  4621. // Declare both a prohibited trailer (Content-Length) and an
  4622. // allowed one
  4623. res.set_header("Trailer", "Content-Length, X-Allowed");
  4624. res.set_chunked_content_provider(
  4625. "text/plain",
  4626. [i](size_t /*offset*/, DataSink &sink) {
  4627. switch (*i) {
  4628. case 0: sink.os << "123"; break;
  4629. case 1: sink.os << "456"; break;
  4630. case 2: sink.os << "789"; break;
  4631. case 3: {
  4632. sink.done_with_trailer(
  4633. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4634. } break;
  4635. }
  4636. (*i)++;
  4637. return true;
  4638. },
  4639. [i](bool success) {
  4640. EXPECT_TRUE(success);
  4641. delete i;
  4642. });
  4643. })
  4644. .Get("/streamed-chunked2",
  4645. [&](const Request & /*req*/, Response &res) {
  4646. auto i = new int(0);
  4647. res.set_chunked_content_provider(
  4648. "text/plain",
  4649. [i](size_t /*offset*/, DataSink &sink) {
  4650. switch (*i) {
  4651. case 0: sink.os << "123"; break;
  4652. case 1: sink.os << "456"; break;
  4653. case 2: sink.os << "789"; break;
  4654. case 3: sink.done(); break;
  4655. }
  4656. (*i)++;
  4657. return true;
  4658. },
  4659. [i](bool success) {
  4660. EXPECT_TRUE(success);
  4661. delete i;
  4662. });
  4663. })
  4664. .Get("/streamed-chunked-with-trailer",
  4665. [&](const Request & /*req*/, Response &res) {
  4666. auto i = new int(0);
  4667. res.set_header("Trailer", "Dummy1, Dummy2");
  4668. res.set_chunked_content_provider(
  4669. "text/plain",
  4670. [i](size_t /*offset*/, DataSink &sink) {
  4671. switch (*i) {
  4672. case 0: sink.os << "123"; break;
  4673. case 1: sink.os << "456"; break;
  4674. case 2: sink.os << "789"; break;
  4675. case 3: {
  4676. sink.done_with_trailer(
  4677. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4678. } break;
  4679. }
  4680. (*i)++;
  4681. return true;
  4682. },
  4683. [i](bool success) {
  4684. EXPECT_TRUE(success);
  4685. delete i;
  4686. });
  4687. })
  4688. .Get("/streamed",
  4689. [&](const Request & /*req*/, Response &res) {
  4690. res.set_content_provider(
  4691. 6, "text/plain",
  4692. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4693. sink.os << (offset < 3 ? "a" : "b");
  4694. return true;
  4695. });
  4696. })
  4697. .Get("/streamed-without-length",
  4698. [&](const Request & /*req*/, Response &res) {
  4699. auto data = new std::string("abcdefg");
  4700. res.set_content_provider(
  4701. "text/plain",
  4702. [data](size_t offset, DataSink &sink) {
  4703. if (offset < data->size()) {
  4704. sink.os << data->substr(offset);
  4705. }
  4706. sink.done();
  4707. return true;
  4708. },
  4709. [data](bool success) {
  4710. EXPECT_TRUE(success);
  4711. delete data;
  4712. });
  4713. })
  4714. .Get("/streamed-with-range",
  4715. [&](const Request &req, Response &res) {
  4716. auto data = new std::string("abcdefg");
  4717. // An explicit status keeps the server from picking the 206 it
  4718. // would otherwise choose for a ranged request, so the response
  4719. // is not a partial representation.
  4720. auto status = req.get_param_value("status");
  4721. if (status == "200") {
  4722. res.status = StatusCode::OK_200;
  4723. } else if (status == "403") {
  4724. res.status = StatusCode::Forbidden_403;
  4725. }
  4726. res.set_content_provider(
  4727. data->size(), "text/plain",
  4728. [data](size_t offset, size_t length, DataSink &sink) {
  4729. size_t DATA_CHUNK_SIZE = 4;
  4730. const auto &d = *data;
  4731. auto out_len =
  4732. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4733. auto ret =
  4734. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4735. EXPECT_TRUE(ret);
  4736. return true;
  4737. },
  4738. [data, &req](bool success) {
  4739. EXPECT_EQ(success, !req.has_param("error"));
  4740. delete data;
  4741. });
  4742. })
  4743. .Get("/streamed-cancel",
  4744. [&](const Request & /*req*/, Response &res) {
  4745. res.set_content_provider(
  4746. size_t(-1), "text/plain",
  4747. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4748. sink.os << "data_chunk";
  4749. return true;
  4750. });
  4751. })
  4752. .Get("/regex-with-delimiter",
  4753. [&](const Request &req, Response & /*res*/) {
  4754. ASSERT_TRUE(req.has_param("key"));
  4755. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4756. })
  4757. .Get("/with-range",
  4758. [&](const Request & /*req*/, Response &res) {
  4759. res.set_content("abcdefg", "text/plain");
  4760. })
  4761. .Get("/test-start-time",
  4762. [&](const Request &req, Response & /*res*/) {
  4763. EXPECT_NE(req.start_time_,
  4764. std::chrono::steady_clock::time_point::min());
  4765. })
  4766. .Get("/with-range-customized-response",
  4767. [&](const Request & /*req*/, Response &res) {
  4768. res.status = StatusCode::BadRequest_400;
  4769. res.set_content(JSON_DATA, "application/json");
  4770. })
  4771. .Post("/chunked",
  4772. [&](const Request &req, Response & /*res*/) {
  4773. EXPECT_EQ(req.body, "dechunked post body");
  4774. })
  4775. .Post("/large-chunked",
  4776. [&](const Request &req, Response & /*res*/) {
  4777. std::string expected(6 * 30 * 1024u, 'a');
  4778. EXPECT_EQ(req.body, expected);
  4779. })
  4780. .Post("/multipart",
  4781. [&](const Request &req, Response & /*res*/) {
  4782. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4783. req.form.get_field_count("text2") +
  4784. req.form.get_field_count("file3") +
  4785. req.form.get_field_count("file4"));
  4786. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4787. req.form.get_file_count("file2"));
  4788. ASSERT_TRUE(!req.form.has_file("???"));
  4789. ASSERT_TRUE(!req.form.has_field("???"));
  4790. ASSERT_TRUE(req.body.empty());
  4791. {
  4792. const auto &text = req.form.get_field("text1");
  4793. EXPECT_EQ("text default", text);
  4794. }
  4795. {
  4796. const auto &text = req.form.get_field("text2");
  4797. EXPECT_EQ("aωb", text);
  4798. }
  4799. {
  4800. const auto &file = req.form.get_file("file1");
  4801. EXPECT_EQ("hello.txt", file.filename);
  4802. EXPECT_EQ("text/plain", file.content_type);
  4803. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4804. }
  4805. {
  4806. const auto &file = req.form.get_file("file2");
  4807. EXPECT_EQ("world.json", file.filename);
  4808. EXPECT_EQ("application/json", file.content_type);
  4809. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4810. }
  4811. {
  4812. const auto &text = req.form.get_field("file3");
  4813. EXPECT_EQ(0u, text.size());
  4814. }
  4815. {
  4816. const auto &text = req.form.get_field("file4");
  4817. EXPECT_EQ(0u, text.size());
  4818. }
  4819. })
  4820. .Post("/multipart/multi_file_values",
  4821. [&](const Request &req, Response & /*res*/) {
  4822. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4823. req.form.get_field_count("multi_text1"));
  4824. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4825. ASSERT_TRUE(!req.form.has_file("???"));
  4826. ASSERT_TRUE(!req.form.has_field("???"));
  4827. ASSERT_TRUE(req.body.empty());
  4828. {
  4829. const auto &text = req.form.get_field("text");
  4830. EXPECT_EQ("default text", text);
  4831. }
  4832. {
  4833. const auto &text1_values = req.form.get_fields("multi_text1");
  4834. EXPECT_EQ(2u, text1_values.size());
  4835. EXPECT_EQ("aaaaa", text1_values[0]);
  4836. EXPECT_EQ("bbbbb", text1_values[1]);
  4837. }
  4838. {
  4839. const auto &file1_values = req.form.get_files("multi_file1");
  4840. EXPECT_EQ(2u, file1_values.size());
  4841. auto file1 = file1_values[0];
  4842. EXPECT_EQ(file1.filename, "hello.txt");
  4843. EXPECT_EQ(file1.content_type, "text/plain");
  4844. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4845. auto file2 = file1_values[1];
  4846. EXPECT_EQ(file2.filename, "world.json");
  4847. EXPECT_EQ(file2.content_type, "application/json");
  4848. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4849. }
  4850. })
  4851. .Post("/empty",
  4852. [&](const Request &req, Response &res) {
  4853. EXPECT_EQ(req.body, "");
  4854. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4855. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4856. res.set_content("empty", "text/plain");
  4857. })
  4858. .Post("/empty-no-content-type",
  4859. [&](const Request &req, Response &res) {
  4860. EXPECT_EQ(req.body, "");
  4861. EXPECT_FALSE(req.has_header("Content-Type"));
  4862. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4863. res.set_content("empty-no-content-type", "text/plain");
  4864. })
  4865. .Post("/path-only",
  4866. [&](const Request &req, Response &res) {
  4867. EXPECT_EQ(req.body, "");
  4868. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4869. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4870. res.set_content("path-only", "text/plain");
  4871. })
  4872. .Post("/path-headers-only",
  4873. [&](const Request &req, Response &res) {
  4874. EXPECT_EQ(req.body, "");
  4875. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4876. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4877. EXPECT_EQ("world", req.get_header_value("hello"));
  4878. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4879. res.set_content("path-headers-only", "text/plain");
  4880. })
  4881. .Post("/post-large",
  4882. [&](const Request &req, Response &res) {
  4883. EXPECT_EQ(req.body, LARGE_DATA);
  4884. res.set_content(req.body, "text/plain");
  4885. })
  4886. .Post("/post-loopback",
  4887. [&](const Request &, Response &res,
  4888. ContentReader const &content_reader) {
  4889. std::string body;
  4890. content_reader([&](const char *data, size_t data_length) {
  4891. body.append(data, data_length);
  4892. return true;
  4893. });
  4894. res.set_content(body, "text/plain");
  4895. })
  4896. .Put("/put-loopback",
  4897. [&](const Request &, Response &res,
  4898. ContentReader const &content_reader) {
  4899. std::string body;
  4900. content_reader([&](const char *data, size_t data_length) {
  4901. body.append(data, data_length);
  4902. return true;
  4903. });
  4904. res.set_content(body, "text/plain");
  4905. })
  4906. .Patch("/patch-loopback",
  4907. [&](const Request &, Response &res,
  4908. ContentReader const &content_reader) {
  4909. std::string body;
  4910. content_reader([&](const char *data, size_t data_length) {
  4911. body.append(data, data_length);
  4912. return true;
  4913. });
  4914. res.set_content(body, "text/plain");
  4915. })
  4916. .Put("/empty-no-content-type",
  4917. [&](const Request &req, Response &res) {
  4918. EXPECT_EQ(req.body, "");
  4919. EXPECT_FALSE(req.has_header("Content-Type"));
  4920. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4921. res.set_content("empty-no-content-type", "text/plain");
  4922. })
  4923. .Put("/put",
  4924. [&](const Request &req, Response &res) {
  4925. EXPECT_EQ(req.body, "PUT");
  4926. res.set_content(req.body, "text/plain");
  4927. })
  4928. .Put("/put-large",
  4929. [&](const Request &req, Response &res) {
  4930. EXPECT_EQ(req.body, LARGE_DATA);
  4931. res.set_content(req.body, "text/plain");
  4932. })
  4933. .Patch("/patch",
  4934. [&](const Request &req, Response &res) {
  4935. EXPECT_EQ(req.body, "PATCH");
  4936. res.set_content(req.body, "text/plain");
  4937. })
  4938. .Delete("/delete",
  4939. [&](const Request & /*req*/, Response &res) {
  4940. res.set_content("DELETE", "text/plain");
  4941. })
  4942. .Delete("/delete-body",
  4943. [&](const Request &req, Response &res) {
  4944. EXPECT_EQ(req.body, "content");
  4945. res.set_content(req.body, "text/plain");
  4946. })
  4947. .Options(R"(\*)",
  4948. [&](const Request & /*req*/, Response &res) {
  4949. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4950. })
  4951. .CustomRoute("PROPFIND", "/dav/:id",
  4952. [&](const Request &req, Response &res) {
  4953. res.set_header("x-body-size",
  4954. std::to_string(req.body.size()));
  4955. res.set_header("x-matched-route", req.matched_route);
  4956. res.set_header("x-dav-id", req.path_params.at("id"));
  4957. res.status = StatusCode::MultiStatus_207;
  4958. res.set_content(req.body, "application/xml");
  4959. })
  4960. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4961. [&](const Request &req, Response &res) {
  4962. res.set_header("x-dav-match", req.matches[1]);
  4963. res.status = StatusCode::MultiStatus_207;
  4964. })
  4965. .CustomRoute("MKCOL", "/dav-mkcol",
  4966. [&](const Request &req, Response &res) {
  4967. EXPECT_TRUE(req.body.empty());
  4968. res.status = StatusCode::Created_201;
  4969. })
  4970. .CustomRoute(
  4971. "REPORT", "/dav-report",
  4972. [&](const Request & /*req*/, Response &res,
  4973. const ContentReader &content_reader) {
  4974. std::string body;
  4975. content_reader([&](const char *data, size_t data_length) {
  4976. body.append(data, data_length);
  4977. return true;
  4978. });
  4979. res.set_header("x-body-size", std::to_string(body.size()));
  4980. res.status = StatusCode::MultiStatus_207;
  4981. res.set_content(body, "application/xml");
  4982. })
  4983. .Get("/request-target",
  4984. [&](const Request &req, Response & /*res*/) {
  4985. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4986. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4987. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4988. })
  4989. .Get("/long-query-value",
  4990. [&](const Request &req, Response & /*res*/) {
  4991. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4992. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4993. })
  4994. .Get("/too-long-query-value",
  4995. [&](const Request &req, Response & /*res*/) {
  4996. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4997. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4998. })
  4999. .Get("/array-param",
  5000. [&](const Request &req, Response & /*res*/) {
  5001. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5002. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5003. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5004. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5005. })
  5006. .Get("/array-param-values",
  5007. [&](const Request &req, Response & /*res*/) {
  5008. auto values = req.get_param_values("array");
  5009. EXPECT_EQ(3u, values.size());
  5010. EXPECT_EQ("value1", values[0]);
  5011. EXPECT_EQ("value2", values[1]);
  5012. EXPECT_EQ("value3", values[2]);
  5013. auto empty = req.get_param_values("nonexistent");
  5014. EXPECT_TRUE(empty.empty());
  5015. })
  5016. .Post("/validate-no-multiple-headers",
  5017. [&](const Request &req, Response & /*res*/) {
  5018. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5019. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5020. })
  5021. .Post("/content_receiver",
  5022. [&](const Request &req, Response &res,
  5023. const ContentReader &content_reader) {
  5024. if (req.is_multipart_form_data()) {
  5025. std::vector<FormData> items;
  5026. content_reader(
  5027. [&](const FormData &file) {
  5028. items.push_back(file);
  5029. return true;
  5030. },
  5031. [&](const char *data, size_t data_length) {
  5032. items.back().content.append(data, data_length);
  5033. return true;
  5034. });
  5035. EXPECT_EQ(5u, items.size());
  5036. {
  5037. const auto &file = get_file_value(items, "text1");
  5038. EXPECT_TRUE(file.filename.empty());
  5039. EXPECT_EQ("text default", file.content);
  5040. }
  5041. {
  5042. const auto &file = get_file_value(items, "text2");
  5043. EXPECT_TRUE(file.filename.empty());
  5044. EXPECT_EQ("aωb", file.content);
  5045. }
  5046. {
  5047. const auto &file = get_file_value(items, "file1");
  5048. EXPECT_EQ("hello.txt", file.filename);
  5049. EXPECT_EQ("text/plain", file.content_type);
  5050. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5051. }
  5052. {
  5053. const auto &file = get_file_value(items, "file2");
  5054. EXPECT_EQ("world.json", file.filename);
  5055. EXPECT_EQ("application/json", file.content_type);
  5056. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5057. }
  5058. {
  5059. const auto &file = get_file_value(items, "file3");
  5060. EXPECT_TRUE(file.filename.empty());
  5061. EXPECT_EQ("application/octet-stream", file.content_type);
  5062. EXPECT_EQ(0u, file.content.size());
  5063. }
  5064. } else {
  5065. std::string body;
  5066. content_reader([&](const char *data, size_t data_length) {
  5067. EXPECT_EQ(7U, data_length);
  5068. body.append(data, data_length);
  5069. return true;
  5070. });
  5071. EXPECT_EQ(body, "content");
  5072. res.set_content(body, "text/plain");
  5073. }
  5074. })
  5075. .Put("/content_receiver",
  5076. [&](const Request & /*req*/, Response &res,
  5077. const ContentReader &content_reader) {
  5078. std::string body;
  5079. content_reader([&](const char *data, size_t data_length) {
  5080. body.append(data, data_length);
  5081. return true;
  5082. });
  5083. EXPECT_EQ(body, "content");
  5084. res.set_content(body, "text/plain");
  5085. })
  5086. .Patch("/content_receiver",
  5087. [&](const Request & /*req*/, Response &res,
  5088. const ContentReader &content_reader) {
  5089. std::string body;
  5090. content_reader([&](const char *data, size_t data_length) {
  5091. body.append(data, data_length);
  5092. return true;
  5093. });
  5094. EXPECT_EQ(body, "content");
  5095. res.set_content(body, "text/plain");
  5096. })
  5097. .Post("/query-string-and-body",
  5098. [&](const Request &req, Response & /*res*/) {
  5099. ASSERT_TRUE(req.has_param("key"));
  5100. EXPECT_EQ(req.get_param_value("key"), "value");
  5101. EXPECT_EQ(req.body, "content");
  5102. })
  5103. .Get("/last-request",
  5104. [&](const Request &req, Response & /*res*/) {
  5105. EXPECT_EQ("close", req.get_header_value("Connection"));
  5106. })
  5107. .Get(R"(/redirect/(\d+))",
  5108. [&](const Request &req, Response &res) {
  5109. auto num = std::stoi(req.matches[1]) + 1;
  5110. std::string url = "/redirect/" + std::to_string(num);
  5111. res.set_redirect(url);
  5112. })
  5113. .Post("/binary",
  5114. [&](const Request &req, Response &res) {
  5115. EXPECT_EQ(4U, req.body.size());
  5116. EXPECT_EQ("application/octet-stream",
  5117. req.get_header_value("Content-Type"));
  5118. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5119. res.set_content(req.body, "application/octet-stream");
  5120. })
  5121. .Put("/binary",
  5122. [&](const Request &req, Response &res) {
  5123. EXPECT_EQ(4U, req.body.size());
  5124. EXPECT_EQ("application/octet-stream",
  5125. req.get_header_value("Content-Type"));
  5126. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5127. res.set_content(req.body, "application/octet-stream");
  5128. })
  5129. .Patch("/binary",
  5130. [&](const Request &req, Response &res) {
  5131. EXPECT_EQ(4U, req.body.size());
  5132. EXPECT_EQ("application/octet-stream",
  5133. req.get_header_value("Content-Type"));
  5134. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5135. res.set_content(req.body, "application/octet-stream");
  5136. })
  5137. .Delete("/binary",
  5138. [&](const Request &req, Response &res) {
  5139. EXPECT_EQ(4U, req.body.size());
  5140. EXPECT_EQ("application/octet-stream",
  5141. req.get_header_value("Content-Type"));
  5142. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5143. res.set_content(req.body, "application/octet-stream");
  5144. })
  5145. .Get("/issue1772",
  5146. [&](const Request & /*req*/, Response &res) {
  5147. res.status = 401;
  5148. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5149. })
  5150. .Delete("/issue609",
  5151. [](const httplib::Request &, httplib::Response &res,
  5152. const httplib::ContentReader &) {
  5153. res.set_content("ok", "text/plain");
  5154. })
  5155. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5156. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5157. .Get("/compress",
  5158. [&](const Request & /*req*/, Response &res) {
  5159. res.set_content(
  5160. "12345678901234567890123456789012345678901234567890123456789"
  5161. "01234567890123456789012345678901234567890",
  5162. "text/plain");
  5163. })
  5164. .Get("/compress-with-charset",
  5165. [&](const Request & /*req*/, Response &res) {
  5166. res.set_content(
  5167. "12345678901234567890123456789012345678901234567890123456789"
  5168. "01234567890123456789012345678901234567890",
  5169. "application/json; charset=utf-8");
  5170. })
  5171. .Get("/nocompress",
  5172. [&](const Request & /*req*/, Response &res) {
  5173. res.set_content(
  5174. "12345678901234567890123456789012345678901234567890123456789"
  5175. "01234567890123456789012345678901234567890",
  5176. "application/octet-stream");
  5177. })
  5178. .Post("/compress-multipart",
  5179. [&](const Request &req, Response & /*res*/) {
  5180. EXPECT_EQ(2u, req.form.fields.size());
  5181. ASSERT_TRUE(!req.form.has_field("???"));
  5182. {
  5183. const auto &text = req.form.get_field("key1");
  5184. EXPECT_EQ("test", text);
  5185. }
  5186. {
  5187. const auto &text = req.form.get_field("key2");
  5188. EXPECT_EQ("--abcdefg123", text);
  5189. }
  5190. })
  5191. #endif
  5192. ;
  5193. persons_["john"] = "programmer";
  5194. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5195. svr_.wait_until_ready();
  5196. }
  5197. virtual void TearDown() {
  5198. svr_.stop();
  5199. if (!request_threads_.empty()) {
  5200. std::this_thread::sleep_for(std::chrono::seconds(1));
  5201. for (auto &t : request_threads_) {
  5202. t.join();
  5203. }
  5204. }
  5205. t_.join();
  5206. }
  5207. map<string, string> persons_;
  5208. #ifdef CPPHTTPLIB_SSL_ENABLED
  5209. SSLClient cli_;
  5210. SSLServer svr_;
  5211. #else
  5212. Client cli_;
  5213. Server svr_;
  5214. #endif
  5215. thread t_;
  5216. std::vector<thread> request_threads_;
  5217. };
  5218. TEST_F(ServerTest, GetMethod200) {
  5219. auto res = cli_.Get("/hi");
  5220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5221. EXPECT_EQ("HTTP/1.1", res->version);
  5222. EXPECT_EQ(StatusCode::OK_200, res->status);
  5223. EXPECT_EQ("OK", res->reason);
  5224. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5225. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5226. EXPECT_EQ("Hello World!", res->body);
  5227. }
  5228. TEST_F(ServerTest, GetEmptyFile) {
  5229. auto res = cli_.Get("/empty_file");
  5230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5231. EXPECT_EQ(StatusCode::OK_200, res->status);
  5232. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5233. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5234. EXPECT_EQ("", res->body);
  5235. }
  5236. TEST_F(ServerTest, GetFileContent) {
  5237. auto res = cli_.Get("/file_content");
  5238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5239. EXPECT_EQ(StatusCode::OK_200, res->status);
  5240. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5241. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5242. EXPECT_EQ("test.html", res->body);
  5243. }
  5244. TEST_F(ServerTest, GetFileContentWithRange) {
  5245. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5247. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5248. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5249. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5250. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5251. EXPECT_EQ("est", res->body);
  5252. }
  5253. TEST_F(ServerTest, GetFileContentWithContentType) {
  5254. auto res = cli_.Get("/file_content_with_content_type");
  5255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5256. EXPECT_EQ(StatusCode::OK_200, res->status);
  5257. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5258. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5259. EXPECT_EQ("file\n", res->body);
  5260. }
  5261. TEST_F(ServerTest, GetInvalidFileContent) {
  5262. auto res = cli_.Get("/invalid_file_content");
  5263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5265. }
  5266. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5267. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5269. EXPECT_EQ("HTTP/1.1", res->version);
  5270. EXPECT_EQ(StatusCode::OK_200, res->status);
  5271. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5272. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5273. EXPECT_EQ("Hello World!", res->body);
  5274. }
  5275. TEST_F(ServerTest, GetMethod302) {
  5276. auto res = cli_.Get("/");
  5277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5278. EXPECT_EQ(StatusCode::Found_302, res->status);
  5279. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5280. }
  5281. TEST_F(ServerTest, GetMethod302Redirect) {
  5282. cli_.set_follow_location(true);
  5283. auto res = cli_.Get("/");
  5284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5285. EXPECT_EQ(StatusCode::OK_200, res->status);
  5286. EXPECT_EQ("Hello World!", res->body);
  5287. EXPECT_EQ("/hi", res->location);
  5288. }
  5289. TEST_F(ServerTest, GetMethod404) {
  5290. auto res = cli_.Get("/invalid");
  5291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5292. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5293. }
  5294. TEST_F(ServerTest, HeadMethod200) {
  5295. auto res = cli_.Head("/hi");
  5296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5297. EXPECT_EQ(StatusCode::OK_200, res->status);
  5298. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5299. EXPECT_TRUE(res->body.empty());
  5300. }
  5301. TEST_F(ServerTest, HeadMethod200Static) {
  5302. auto res = cli_.Head("/mount/dir/index.html");
  5303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5304. EXPECT_EQ(StatusCode::OK_200, res->status);
  5305. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5306. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5307. EXPECT_TRUE(res->body.empty());
  5308. }
  5309. TEST_F(ServerTest, HeadMethod404) {
  5310. auto res = cli_.Head("/invalid");
  5311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5312. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5313. EXPECT_TRUE(res->body.empty());
  5314. }
  5315. TEST_F(ServerTest, GetMethodPersonJohn) {
  5316. auto res = cli_.Get("/person/john");
  5317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5318. EXPECT_EQ(StatusCode::OK_200, res->status);
  5319. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5320. EXPECT_EQ("programmer", res->body);
  5321. }
  5322. TEST_F(ServerTest, PostMethod1) {
  5323. auto res = cli_.Get("/person/john1");
  5324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5325. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5326. res = cli_.Post("/person", "name=john1&note=coder",
  5327. "application/x-www-form-urlencoded");
  5328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5329. ASSERT_EQ(StatusCode::OK_200, res->status);
  5330. res = cli_.Get("/person/john1");
  5331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5332. ASSERT_EQ(StatusCode::OK_200, res->status);
  5333. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5334. ASSERT_EQ("coder", res->body);
  5335. }
  5336. TEST_F(ServerTest, PostMethod2) {
  5337. auto res = cli_.Get("/person/john2");
  5338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5339. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5340. Params params;
  5341. params.emplace("name", "john2");
  5342. params.emplace("note", "coder");
  5343. res = cli_.Post("/person", params);
  5344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5345. ASSERT_EQ(StatusCode::OK_200, res->status);
  5346. res = cli_.Get("/person/john2");
  5347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5348. ASSERT_EQ(StatusCode::OK_200, res->status);
  5349. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5350. ASSERT_EQ("coder", res->body);
  5351. }
  5352. TEST_F(ServerTest, PutMethod3) {
  5353. auto res = cli_.Get("/person/john3");
  5354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5355. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5356. Params params;
  5357. params.emplace("name", "john3");
  5358. params.emplace("note", "coder");
  5359. res = cli_.Put("/person", params);
  5360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5361. ASSERT_EQ(StatusCode::OK_200, res->status);
  5362. res = cli_.Get("/person/john3");
  5363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5364. ASSERT_EQ(StatusCode::OK_200, res->status);
  5365. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5366. ASSERT_EQ("coder", res->body);
  5367. }
  5368. TEST_F(ServerTest, DeleteMethod1) {
  5369. auto res = cli_.Get("/person/john4");
  5370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5371. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5372. Params params;
  5373. params.emplace("name", "john4");
  5374. params.emplace("note", "coder");
  5375. res = cli_.Post("/person", params);
  5376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5377. ASSERT_EQ(StatusCode::OK_200, res->status);
  5378. res = cli_.Get("/person/john4");
  5379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5380. ASSERT_EQ(StatusCode::OK_200, res->status);
  5381. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5382. ASSERT_EQ("coder", res->body);
  5383. Params delete_params;
  5384. delete_params.emplace("name", "john4");
  5385. res = cli_.Delete("/person", delete_params);
  5386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5387. ASSERT_EQ(StatusCode::OK_200, res->status);
  5388. ASSERT_EQ("DELETED", res->body);
  5389. res = cli_.Get("/person/john4");
  5390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5391. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5392. }
  5393. TEST_F(ServerTest, DeleteMethod2) {
  5394. auto res = cli_.Get("/person/john5");
  5395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5396. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5397. Params params;
  5398. params.emplace("name", "john5");
  5399. params.emplace("note", "developer");
  5400. res = cli_.Post("/person", params);
  5401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5402. ASSERT_EQ(StatusCode::OK_200, res->status);
  5403. res = cli_.Get("/person/john5");
  5404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5405. ASSERT_EQ(StatusCode::OK_200, res->status);
  5406. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5407. ASSERT_EQ("developer", res->body);
  5408. Params delete_params;
  5409. delete_params.emplace("name", "john5");
  5410. Headers headers;
  5411. headers.emplace("Custom-Header", "test-value");
  5412. res = cli_.Delete("/person", headers, delete_params);
  5413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5414. ASSERT_EQ(StatusCode::OK_200, res->status);
  5415. ASSERT_EQ("DELETED", res->body);
  5416. res = cli_.Get("/person/john5");
  5417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5418. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5419. }
  5420. TEST_F(ServerTest, DeleteMethod3) {
  5421. auto res = cli_.Get("/person/john6");
  5422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5423. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5424. Params params;
  5425. params.emplace("name", "john6");
  5426. params.emplace("note", "tester");
  5427. res = cli_.Post("/person", params);
  5428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5429. ASSERT_EQ(StatusCode::OK_200, res->status);
  5430. res = cli_.Get("/person/john6");
  5431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5432. ASSERT_EQ(StatusCode::OK_200, res->status);
  5433. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5434. ASSERT_EQ("tester", res->body);
  5435. Params delete_params;
  5436. delete_params.emplace("name", "john6");
  5437. Headers headers;
  5438. headers.emplace("Custom-Header", "test-value");
  5439. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5441. ASSERT_EQ(StatusCode::OK_200, res->status);
  5442. ASSERT_EQ("DELETED", res->body);
  5443. res = cli_.Get("/person/john6");
  5444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5445. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5446. }
  5447. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5448. Params params;
  5449. params.emplace("json", JSON_DATA);
  5450. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5452. ASSERT_EQ(StatusCode::OK_200, res->status);
  5453. ASSERT_EQ(JSON_DATA, res->body);
  5454. }
  5455. TEST_F(ServerTest, PostEmptyContent) {
  5456. auto res = cli_.Post("/empty", "", "text/plain");
  5457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5458. ASSERT_EQ(StatusCode::OK_200, res->status);
  5459. ASSERT_EQ("empty", res->body);
  5460. }
  5461. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5462. auto res = cli_.Post("/empty-no-content-type");
  5463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5464. ASSERT_EQ(StatusCode::OK_200, res->status);
  5465. ASSERT_EQ("empty-no-content-type", res->body);
  5466. }
  5467. TEST_F(ServerTest, PostPathOnly) {
  5468. auto res = cli_.Post("/path-only");
  5469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5470. ASSERT_EQ(StatusCode::OK_200, res->status);
  5471. ASSERT_EQ("path-only", res->body);
  5472. }
  5473. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5474. auto res = cli_.Post("/path-headers-only",
  5475. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5477. ASSERT_EQ(StatusCode::OK_200, res->status);
  5478. ASSERT_EQ("path-headers-only", res->body);
  5479. }
  5480. TEST_F(ServerTest, PostLarge) {
  5481. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5483. ASSERT_EQ(StatusCode::OK_200, res->status);
  5484. EXPECT_EQ(LARGE_DATA, res->body);
  5485. }
  5486. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5487. auto res = cli_.Put("/empty-no-content-type");
  5488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5489. ASSERT_EQ(StatusCode::OK_200, res->status);
  5490. ASSERT_EQ("empty-no-content-type", res->body);
  5491. }
  5492. TEST_F(ServerTest, GetMethodDir) {
  5493. auto res = cli_.Get("/dir/");
  5494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5495. EXPECT_EQ(StatusCode::OK_200, res->status);
  5496. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5497. auto body = R"(<html>
  5498. <head>
  5499. </head>
  5500. <body>
  5501. <a href="/dir/test.html">Test</a>
  5502. <a href="/hi">hi</a>
  5503. </body>
  5504. </html>
  5505. )";
  5506. EXPECT_EQ(body, res->body);
  5507. }
  5508. TEST_F(ServerTest, GetMethodDirTest) {
  5509. auto res = cli_.Get("/dir/test.html");
  5510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5511. EXPECT_EQ(StatusCode::OK_200, res->status);
  5512. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5513. EXPECT_EQ("test.html", res->body);
  5514. }
  5515. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5516. auto res = cli_.Get("/dir/../dir/test.html");
  5517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5518. EXPECT_EQ(StatusCode::OK_200, res->status);
  5519. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5520. EXPECT_EQ("test.html", res->body);
  5521. }
  5522. TEST_F(ServerTest, GetMethodInvalidPath) {
  5523. auto res = cli_.Get("/dir/../test.html");
  5524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5526. }
  5527. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5528. auto res = cli_.Get("/../www/dir/test.html");
  5529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5530. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5531. }
  5532. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5533. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5535. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5536. }
  5537. TEST_F(ServerTest, GetMethodDirMountTest) {
  5538. auto res = cli_.Get("/mount/dir/test.html");
  5539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5540. EXPECT_EQ(StatusCode::OK_200, res->status);
  5541. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5542. EXPECT_EQ("test.html", res->body);
  5543. }
  5544. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5545. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5549. EXPECT_EQ("test.html", res->body);
  5550. }
  5551. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5552. auto res = cli_.Get("/mount/dir/../test.html");
  5553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5554. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5555. }
  5556. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5557. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5559. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5560. }
  5561. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5562. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5564. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5565. }
  5566. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5567. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5569. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5570. }
  5571. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5572. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5574. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5575. }
  5576. TEST_F(ServerTest, PostMethod303) {
  5577. auto res = cli_.Post("/1", "body", "text/plain");
  5578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5579. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5580. EXPECT_EQ("/2", res->get_header_value("Location"));
  5581. }
  5582. TEST_F(ServerTest, PostMethod303Redirect) {
  5583. cli_.set_follow_location(true);
  5584. auto res = cli_.Post("/1", "body", "text/plain");
  5585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5586. EXPECT_EQ(StatusCode::OK_200, res->status);
  5587. EXPECT_EQ("redirected.", res->body);
  5588. EXPECT_EQ("/2", res->location);
  5589. }
  5590. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5591. auto res = cli_.Get("/dir/test.abcde");
  5592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5593. EXPECT_EQ(StatusCode::OK_200, res->status);
  5594. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5595. EXPECT_EQ("abcde", res->body);
  5596. }
  5597. TEST_F(ServerTest, StaticFileRange) {
  5598. auto res =
  5599. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5601. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5602. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5603. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5604. EXPECT_EQ(true, res->has_header("Content-Range"));
  5605. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5606. EXPECT_EQ(std::string("cd"), res->body);
  5607. }
  5608. TEST_F(ServerTest, StaticFileRanges) {
  5609. auto res = cli_.Get("/dir/test.abcde",
  5610. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5612. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5613. EXPECT_TRUE(
  5614. res->get_header_value("Content-Type")
  5615. .find(
  5616. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5617. 0);
  5618. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5619. }
  5620. TEST_F(ServerTest, StaticFileRangeHead) {
  5621. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5623. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5624. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5625. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5626. EXPECT_EQ(true, res->has_header("Content-Range"));
  5627. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5628. }
  5629. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5630. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5632. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5633. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5634. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5635. EXPECT_EQ(true, res->has_header("Content-Range"));
  5636. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5637. res->get_header_value("Content-Range"));
  5638. EXPECT_EQ("LAST\n", res->body);
  5639. }
  5640. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5641. auto res =
  5642. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5644. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5645. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5646. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5647. EXPECT_EQ(true, res->has_header("Content-Range"));
  5648. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5649. }
  5650. TEST_F(ServerTest, StaticFileBigFile) {
  5651. auto res = cli_.Get("/dir/1MB.txt");
  5652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5653. EXPECT_EQ(StatusCode::OK_200, res->status);
  5654. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5655. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5656. }
  5657. TEST_F(ServerTest, InvalidBaseDirMount) {
  5658. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5659. }
  5660. TEST_F(ServerTest, Binary) {
  5661. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5662. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5663. "application/octet-stream");
  5664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5665. ASSERT_EQ(StatusCode::OK_200, res->status);
  5666. ASSERT_EQ(4U, res->body.size());
  5667. res = cli_.Put("/binary", binary.data(), binary.size(),
  5668. "application/octet-stream");
  5669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5670. ASSERT_EQ(StatusCode::OK_200, res->status);
  5671. ASSERT_EQ(4U, res->body.size());
  5672. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5673. "application/octet-stream");
  5674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5675. ASSERT_EQ(StatusCode::OK_200, res->status);
  5676. ASSERT_EQ(4U, res->body.size());
  5677. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5678. "application/octet-stream");
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. ASSERT_EQ(StatusCode::OK_200, res->status);
  5681. ASSERT_EQ(4U, res->body.size());
  5682. }
  5683. TEST_F(ServerTest, BinaryString) {
  5684. auto binary = std::string("\x00\x01\x02\x03", 4);
  5685. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5687. ASSERT_EQ(StatusCode::OK_200, res->status);
  5688. ASSERT_EQ(4U, res->body.size());
  5689. res = cli_.Put("/binary", binary, "application/octet-stream");
  5690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5691. ASSERT_EQ(StatusCode::OK_200, res->status);
  5692. ASSERT_EQ(4U, res->body.size());
  5693. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5695. ASSERT_EQ(StatusCode::OK_200, res->status);
  5696. ASSERT_EQ(4U, res->body.size());
  5697. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5699. ASSERT_EQ(StatusCode::OK_200, res->status);
  5700. ASSERT_EQ(4U, res->body.size());
  5701. }
  5702. TEST_F(ServerTest, EmptyRequest) {
  5703. auto res = cli_.Get("");
  5704. ASSERT_TRUE(!res);
  5705. EXPECT_EQ(Error::Connection, res.error());
  5706. }
  5707. TEST_F(ServerTest, LongRequest) {
  5708. std::string request;
  5709. for (size_t i = 0; i < 545; i++) {
  5710. request += "/TooLongRequest";
  5711. }
  5712. request += "OK";
  5713. auto res = cli_.Get(request.c_str());
  5714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5715. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5716. }
  5717. TEST_F(ServerTest, TooLongRequest) {
  5718. std::string request;
  5719. for (size_t i = 0; i < 546; i++) {
  5720. request += "/TooLongRequest";
  5721. }
  5722. request += "_NG";
  5723. auto start = std::chrono::high_resolution_clock::now();
  5724. cli_.set_keep_alive(true);
  5725. auto res = cli_.Get(request.c_str());
  5726. auto end = std::chrono::high_resolution_clock::now();
  5727. auto elapsed =
  5728. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5729. .count();
  5730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5731. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5732. EXPECT_LE(elapsed, 1000);
  5733. EXPECT_EQ("close", res->get_header_value("Connection"));
  5734. EXPECT_FALSE(cli_.is_socket_open());
  5735. }
  5736. TEST_F(ServerTest, AlmostTooLongRequest) {
  5737. // test for #2046 - URI length check shouldn't include other content on req
  5738. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5739. // leading /, space, HTTP/1.1)
  5740. std::string request =
  5741. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5742. auto res = cli_.Get(request.c_str());
  5743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5744. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5745. }
  5746. TEST_F(ServerTest, LongHeader) {
  5747. Request req;
  5748. req.method = "GET";
  5749. req.path = "/hi";
  5750. std::string host_and_port;
  5751. host_and_port += HOST;
  5752. host_and_port += ":";
  5753. host_and_port += std::to_string(PORT);
  5754. req.headers.emplace("Host", host_and_port.c_str());
  5755. req.headers.emplace("Accept", "*/*");
  5756. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5757. req.headers.emplace(
  5758. "Header-Name",
  5759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5787. "@@@@@@@@@@@@@@@@");
  5788. auto res = std::make_shared<Response>();
  5789. auto error = Error::Success;
  5790. auto ret = cli_.send(req, *res, error);
  5791. ASSERT_TRUE(ret);
  5792. EXPECT_EQ(StatusCode::OK_200, res->status);
  5793. }
  5794. TEST_F(ServerTest, LongQueryValue) {
  5795. auto start = std::chrono::high_resolution_clock::now();
  5796. cli_.set_keep_alive(true);
  5797. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5798. auto end = std::chrono::high_resolution_clock::now();
  5799. auto elapsed =
  5800. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5801. .count();
  5802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5803. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5804. EXPECT_LE(elapsed, 1000);
  5805. EXPECT_EQ("close", res->get_header_value("Connection"));
  5806. EXPECT_FALSE(cli_.is_socket_open());
  5807. }
  5808. TEST_F(ServerTest, TooLongQueryValue) {
  5809. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5810. ASSERT_FALSE(res);
  5811. EXPECT_EQ(Error::Read, res.error());
  5812. }
  5813. TEST_F(ServerTest, TooLongHeader) {
  5814. Request req;
  5815. req.method = "GET";
  5816. req.path = "/hi";
  5817. std::string host_and_port;
  5818. host_and_port += HOST;
  5819. host_and_port += ":";
  5820. host_and_port += std::to_string(PORT);
  5821. req.headers.emplace("Host", host_and_port.c_str());
  5822. req.headers.emplace("Accept", "*/*");
  5823. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5824. req.headers.emplace(
  5825. "Header-Name",
  5826. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5827. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5828. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5854. "@@@@@@@@@@@@@@@@@");
  5855. auto res = std::make_shared<Response>();
  5856. auto error = Error::Success;
  5857. auto ret = cli_.send(req, *res, error);
  5858. ASSERT_TRUE(ret);
  5859. EXPECT_EQ(StatusCode::OK_200, res->status);
  5860. }
  5861. TEST_F(ServerTest, HeaderCountAtLimit) {
  5862. // Test with headers just under the 100 limit
  5863. httplib::Headers headers;
  5864. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5865. // This should keep us just under the 100 header limit
  5866. for (int i = 0; i < 95; i++) {
  5867. std::string name = "X-Test-Header-" + std::to_string(i);
  5868. std::string value = "value" + std::to_string(i);
  5869. headers.emplace(name, value);
  5870. }
  5871. // This should work fine as we're under the limit
  5872. auto res = cli_.Get("/hi", headers);
  5873. EXPECT_TRUE(res);
  5874. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5875. }
  5876. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5877. // Test with many headers to exceed the 100 limit
  5878. httplib::Headers headers;
  5879. // Add 150 headers to definitely exceed the 100 limit
  5880. for (int i = 0; i < 150; i++) {
  5881. std::string name = "X-Test-Header-" + std::to_string(i);
  5882. std::string value = "value" + std::to_string(i);
  5883. headers.emplace(name, value);
  5884. }
  5885. // This should fail due to exceeding header count limit
  5886. cli_.set_keep_alive(true);
  5887. auto res = cli_.Get("/hi", headers);
  5888. // The server should respond with 400 Bad Request
  5889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5890. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5891. EXPECT_EQ("close", res->get_header_value("Connection"));
  5892. EXPECT_FALSE(cli_.is_socket_open());
  5893. }
  5894. TEST_F(ServerTest, PercentEncoding) {
  5895. auto res = cli_.Get("/e%6edwith%");
  5896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5897. EXPECT_EQ(StatusCode::OK_200, res->status);
  5898. }
  5899. TEST_F(ServerTest, PercentEncodingUnicode) {
  5900. auto res = cli_.Get("/e%u006edwith%");
  5901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5902. EXPECT_EQ(StatusCode::OK_200, res->status);
  5903. }
  5904. TEST_F(ServerTest, InvalidPercentEncoding) {
  5905. auto res = cli_.Get("/%endwith%");
  5906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5907. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5908. }
  5909. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5910. auto res = cli_.Get("/%uendwith%");
  5911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5912. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5913. }
  5914. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5915. auto res = cli_.Get("/hello?aaa=bbb%");
  5916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5917. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5918. }
  5919. TEST_F(ServerTest, PlusSignEncoding) {
  5920. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5922. EXPECT_EQ(StatusCode::OK_200, res->status);
  5923. EXPECT_EQ("a +b", res->body);
  5924. }
  5925. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5926. // This test simulates a potential DoS attack using many headers
  5927. // to verify our security fix prevents memory exhaustion
  5928. httplib::Headers attack_headers;
  5929. // Attempt to add many headers like an attacker would (200 headers to far
  5930. // exceed limit)
  5931. for (int i = 0; i < 200; i++) {
  5932. std::string name = "X-Attack-Header-" + std::to_string(i);
  5933. std::string value = "attack_payload_" + std::to_string(i);
  5934. attack_headers.emplace(name, value);
  5935. }
  5936. // Try to POST with excessive headers
  5937. cli_.set_keep_alive(true);
  5938. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5939. // Should either fail or return 400 Bad Request due to security limit
  5940. if (res) {
  5941. // If we get a response, it should be 400 Bad Request
  5942. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5943. EXPECT_EQ("close", res->get_header_value("Connection"));
  5944. }
  5945. EXPECT_FALSE(cli_.is_socket_open());
  5946. }
  5947. TEST_F(ServerTest, MultipartFormData) {
  5948. UploadFormDataItems items = {
  5949. {"text1", "text default", "", ""},
  5950. {"text2", "aωb", "", ""},
  5951. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5952. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5953. {"file3", "", "", "application/octet-stream"},
  5954. {"file4", "", "", " application/json tmp-string "}};
  5955. auto res = cli_.Post("/multipart", items);
  5956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5957. EXPECT_EQ(StatusCode::OK_200, res->status);
  5958. }
  5959. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5960. UploadFormDataItems items = {
  5961. {"text", "default text", "", ""},
  5962. {"multi_text1", "aaaaa", "", ""},
  5963. {"multi_text1", "bbbbb", "", ""},
  5964. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5965. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5966. "application/json"},
  5967. };
  5968. auto res = cli_.Post("/multipart/multi_file_values", items);
  5969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5970. EXPECT_EQ(StatusCode::OK_200, res->status);
  5971. }
  5972. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5973. auto res = cli_.Get("/hi");
  5974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5975. EXPECT_EQ(StatusCode::OK_200, res->status);
  5976. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5977. EXPECT_EQ("Hello World!", res->body);
  5978. }
  5979. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5980. Request req;
  5981. req.method = "POST";
  5982. req.path = "/chunked";
  5983. std::string host_and_port;
  5984. host_and_port += HOST;
  5985. host_and_port += ":";
  5986. host_and_port += std::to_string(PORT);
  5987. req.headers.emplace("Host", host_and_port.c_str());
  5988. req.headers.emplace("Accept", "*/*");
  5989. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5990. req.headers.emplace("Content-Type", "text/plain");
  5991. req.headers.emplace("Content-Length", "0");
  5992. req.headers.emplace(
  5993. "Transfer-Encoding",
  5994. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5995. // Client does not chunk, so make a chunked body manually.
  5996. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5997. auto res = std::make_shared<Response>();
  5998. auto error = Error::Success;
  5999. auto ret = cli_.send(req, *res, error);
  6000. ASSERT_TRUE(ret);
  6001. EXPECT_EQ(StatusCode::OK_200, res->status);
  6002. }
  6003. template <typename ClientT>
  6004. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6005. int expected_status) {
  6006. Request req;
  6007. req.method = "POST";
  6008. req.path = "/chunked";
  6009. std::string host_and_port;
  6010. host_and_port += HOST;
  6011. host_and_port += ":";
  6012. host_and_port += std::to_string(PORT);
  6013. req.headers.emplace("Host", host_and_port.c_str());
  6014. req.headers.emplace("Content-Length", "0");
  6015. req.headers.emplace("Transfer-Encoding", "chunked");
  6016. req.body = body;
  6017. auto res = std::make_shared<Response>();
  6018. auto error = Error::Success;
  6019. ASSERT_TRUE(cli.send(req, *res, error));
  6020. EXPECT_EQ(expected_status, res->status);
  6021. }
  6022. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6023. // rather than treat them as valid lengths.
  6024. template <typename ClientT>
  6025. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6026. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6027. }
  6028. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6029. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6030. }
  6031. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6032. expect_chunked_body_rejected(
  6033. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6034. }
  6035. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6036. // chunk-size line carries no CR, LF or other control character ahead of its
  6037. // terminator. Such a line must be refused rather than read as extension text.
  6038. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6039. expect_chunked_body_rejected(
  6040. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6041. }
  6042. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6043. expect_chunked_body_rejected(
  6044. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6045. }
  6046. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6047. expect_chunked_body_rejected(
  6048. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6049. }
  6050. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6051. // The literal stays split: a hex escape consumes every hex digit that
  6052. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6053. expect_chunked_body_rejected(
  6054. cli_, "4;a\x01"
  6055. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6056. }
  6057. TEST_F(ServerTest, AcceptsChunkExtension) {
  6058. expect_chunked_body_status(cli_,
  6059. "4;name=value\r\ndech\r\n"
  6060. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6061. "0;last\r\n\r\n",
  6062. StatusCode::OK_200);
  6063. }
  6064. TEST_F(ServerTest, GetStreamed2) {
  6065. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6067. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6068. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6069. EXPECT_EQ(true, res->has_header("Content-Range"));
  6070. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6071. EXPECT_EQ(std::string("ab"), res->body);
  6072. }
  6073. TEST_F(ServerTest, GetStreamed) {
  6074. auto res = cli_.Get("/streamed");
  6075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6076. EXPECT_EQ(StatusCode::OK_200, res->status);
  6077. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6078. EXPECT_EQ(std::string("aaabbb"), res->body);
  6079. }
  6080. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6081. auto res = cli_.Get("/streamed-without-length",
  6082. Headers{make_range_header({{0, -1}})});
  6083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6084. EXPECT_EQ(StatusCode::OK_200, res->status);
  6085. EXPECT_EQ(false, res->has_header("Content-Length"));
  6086. EXPECT_EQ(false, res->has_header("Content-Range"));
  6087. EXPECT_EQ(std::string("abcdefg"), res->body);
  6088. }
  6089. TEST_F(ServerTest, GetStreamedWithRange1) {
  6090. auto res =
  6091. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6093. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6094. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6095. EXPECT_EQ(true, res->has_header("Content-Range"));
  6096. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6097. EXPECT_EQ(std::string("def"), res->body);
  6098. }
  6099. TEST_F(ServerTest, GetStreamedWithRange2) {
  6100. auto res =
  6101. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6103. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6104. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6105. EXPECT_EQ(true, res->has_header("Content-Range"));
  6106. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6107. EXPECT_EQ(std::string("bcdefg"), res->body);
  6108. }
  6109. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6110. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6112. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6113. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6114. EXPECT_EQ(true, res->has_header("Content-Range"));
  6115. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6116. EXPECT_EQ(std::string("efg"), res->body);
  6117. }
  6118. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6119. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6120. // the entire representation.
  6121. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6122. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6124. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6125. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6126. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6127. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6128. }
  6129. }
  6130. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6131. auto res =
  6132. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6135. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6136. EXPECT_EQ(false, res->has_header("Content-Range"));
  6137. EXPECT_EQ(0U, res->body.size());
  6138. }
  6139. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6140. // Only a 206 is served as a partial representation. Under any other status
  6141. // `apply_ranges()` reported the full content length, so the body must match
  6142. // that header, and the content provider must never be asked for an offset
  6143. // outside the representation.
  6144. auto check = [&](int status, const char *range) {
  6145. auto path =
  6146. std::string("/streamed-with-range?status=") + std::to_string(status);
  6147. auto ctx = path + " Range: " + range;
  6148. auto res = cli_.Get(path, Headers{{"Range", range}});
  6149. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6150. EXPECT_EQ(status, res->status) << ctx;
  6151. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6152. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6153. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6154. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6155. };
  6156. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6157. check(403, "bytes=3-5");
  6158. // The offset is far past the representation.
  6159. check(403, "bytes=100000-100200");
  6160. // `first_pos` is still -1 here, and the bounds asserts in
  6161. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6162. check(403, "bytes=-3");
  6163. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6164. // multipart branch would have written one that is empty.
  6165. check(403, "bytes=1-2, 4-5");
  6166. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6167. // covers the whole representation.
  6168. check(200, "bytes=3-5");
  6169. check(200, "bytes=1-2, 4-5");
  6170. }
  6171. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6172. auto res =
  6173. cli_.Get("/streamed-with-range",
  6174. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6175. "92233720368547758079223372036854775807"}});
  6176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6177. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6178. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6179. EXPECT_EQ(false, res->has_header("Content-Range"));
  6180. EXPECT_EQ(0U, res->body.size());
  6181. }
  6182. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6183. auto res = cli_.Get(
  6184. "/with-range",
  6185. Headers{{"Range",
  6186. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6187. {"Accept-Encoding", ""}});
  6188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6189. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6190. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6191. EXPECT_EQ(true, res->has_header("Content-Range"));
  6192. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6193. EXPECT_EQ(std::string("abcdefg"), res->body);
  6194. }
  6195. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6196. auto res = cli_.Get("/with-range", Headers{
  6197. {"Range", "bytes=0-"},
  6198. {"Accept-Encoding", ""},
  6199. });
  6200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6201. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6202. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6203. EXPECT_EQ(true, res->has_header("Content-Range"));
  6204. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6205. EXPECT_EQ(std::string("abcdefg"), res->body);
  6206. }
  6207. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6208. auto res = cli_.Get("/streamed-with-range",
  6209. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6212. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6213. EXPECT_EQ(false, res->has_header("Content-Range"));
  6214. EXPECT_EQ(267U, res->body.size());
  6215. // Check that both range contents are present
  6216. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6217. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6218. // Check that Content-Range headers are present for both ranges
  6219. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6220. std::string::npos);
  6221. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6222. std::string::npos);
  6223. }
  6224. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6225. Ranges ranges;
  6226. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6227. ranges.emplace_back(0, -1);
  6228. }
  6229. auto res = cli_.Get("/streamed-with-range?error",
  6230. Headers{{make_range_header(ranges)}});
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6233. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6234. EXPECT_EQ(false, res->has_header("Content-Range"));
  6235. EXPECT_EQ(0U, res->body.size());
  6236. }
  6237. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6238. auto res = cli_.Get("/streamed-with-range",
  6239. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6241. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6242. EXPECT_EQ(5U, res->body.size());
  6243. // Check that overlapping ranges are coalesced into a single range
  6244. EXPECT_EQ("bcdef", res->body);
  6245. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6246. // Should be single range, not multipart
  6247. EXPECT_TRUE(res->has_header("Content-Range"));
  6248. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6249. }
  6250. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6251. auto res = cli_.Get("/streamed-with-range",
  6252. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6254. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6255. EXPECT_EQ(268U, res->body.size());
  6256. // Check that both range contents are present
  6257. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6258. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6259. // Check that Content-Range headers are present for both ranges
  6260. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6261. std::string::npos);
  6262. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6263. std::string::npos);
  6264. }
  6265. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6266. auto res = cli_.Get("/streamed-with-range",
  6267. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6269. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6270. EXPECT_EQ(269U, res->body.size());
  6271. // Check that both duplicate range contents are present
  6272. size_t first_abc = res->body.find("abc\r\n");
  6273. EXPECT_TRUE(first_abc != std::string::npos);
  6274. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6275. EXPECT_TRUE(second_abc != std::string::npos);
  6276. // Check that Content-Range headers are present for both ranges
  6277. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6278. EXPECT_TRUE(first_range != std::string::npos);
  6279. size_t second_range =
  6280. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6281. EXPECT_TRUE(second_range != std::string::npos);
  6282. }
  6283. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6284. auto res =
  6285. cli_.Get("/streamed-with-range?error",
  6286. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6288. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6289. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6290. EXPECT_EQ(false, res->has_header("Content-Range"));
  6291. EXPECT_EQ(0U, res->body.size());
  6292. }
  6293. TEST_F(ServerTest, GetStreamedEndless) {
  6294. uint64_t offset = 0;
  6295. auto res = cli_.Get("/streamed-cancel",
  6296. [&](const char * /*data*/, uint64_t data_length) {
  6297. if (offset < 100) {
  6298. offset += data_length;
  6299. return true;
  6300. }
  6301. return false;
  6302. });
  6303. ASSERT_TRUE(!res);
  6304. EXPECT_EQ(Error::Canceled, res.error());
  6305. }
  6306. TEST_F(ServerTest, ClientStop) {
  6307. std::atomic_size_t count{4};
  6308. std::vector<std::thread> threads;
  6309. for (auto i = count.load(); i != 0; --i) {
  6310. threads.emplace_back([&]() {
  6311. auto res = cli_.Get("/streamed-cancel",
  6312. [&](const char *, uint64_t) { return true; });
  6313. --count;
  6314. ASSERT_TRUE(!res);
  6315. EXPECT_TRUE(res.error() == Error::Canceled ||
  6316. res.error() == Error::Read || res.error() == Error::Write);
  6317. });
  6318. }
  6319. std::this_thread::sleep_for(std::chrono::seconds(2));
  6320. while (count != 0) {
  6321. cli_.stop();
  6322. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6323. }
  6324. for (auto &t : threads) {
  6325. t.join();
  6326. }
  6327. }
  6328. TEST_F(ServerTest, GetWithRange1) {
  6329. auto res = cli_.Get("/with-range", Headers{
  6330. make_range_header({{3, 5}}),
  6331. {"Accept-Encoding", ""},
  6332. });
  6333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6334. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6335. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6336. EXPECT_EQ(true, res->has_header("Content-Range"));
  6337. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6338. EXPECT_EQ(std::string("def"), res->body);
  6339. }
  6340. TEST_F(ServerTest, GetWithRange2) {
  6341. auto res = cli_.Get("/with-range", Headers{
  6342. make_range_header({{1, -1}}),
  6343. {"Accept-Encoding", ""},
  6344. });
  6345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6346. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6347. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6348. EXPECT_EQ(true, res->has_header("Content-Range"));
  6349. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6350. EXPECT_EQ(std::string("bcdefg"), res->body);
  6351. }
  6352. TEST_F(ServerTest, GetWithRange3) {
  6353. auto res = cli_.Get("/with-range", Headers{
  6354. make_range_header({{0, 0}}),
  6355. {"Accept-Encoding", ""},
  6356. });
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6359. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6360. EXPECT_EQ(true, res->has_header("Content-Range"));
  6361. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6362. EXPECT_EQ(std::string("a"), res->body);
  6363. }
  6364. TEST_F(ServerTest, GetWithRange4) {
  6365. auto res = cli_.Get("/with-range", Headers{
  6366. make_range_header({{-1, 2}}),
  6367. {"Accept-Encoding", ""},
  6368. });
  6369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6370. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6371. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6372. EXPECT_EQ(true, res->has_header("Content-Range"));
  6373. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6374. EXPECT_EQ(std::string("fg"), res->body);
  6375. }
  6376. TEST_F(ServerTest, GetWithRange5) {
  6377. auto res = cli_.Get("/with-range", Headers{
  6378. make_range_header({{0, 5}}),
  6379. {"Accept-Encoding", ""},
  6380. });
  6381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6382. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6383. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6384. EXPECT_EQ(true, res->has_header("Content-Range"));
  6385. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6386. EXPECT_EQ(std::string("abcdef"), res->body);
  6387. }
  6388. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6389. auto res =
  6390. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6392. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6393. }
  6394. TEST_F(ServerTest, GetWithRangeMultipart) {
  6395. auto res =
  6396. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6398. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6399. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6400. EXPECT_EQ(false, res->has_header("Content-Range"));
  6401. EXPECT_EQ(267U, res->body.size());
  6402. }
  6403. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6404. auto res = cli_.Get("/with-range",
  6405. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6407. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6408. }
  6409. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6410. auto res = cli_.Get("/with-range-customized-response",
  6411. Headers{{make_range_header({{1, 2}})}});
  6412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6413. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6414. EXPECT_EQ(true, res->has_header("Content-Length"));
  6415. EXPECT_EQ(false, res->has_header("Content-Range"));
  6416. EXPECT_EQ(JSON_DATA, res->body);
  6417. }
  6418. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6419. auto res = cli_.Get("/with-range-customized-response",
  6420. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6422. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6423. EXPECT_EQ(true, res->has_header("Content-Length"));
  6424. EXPECT_EQ(false, res->has_header("Content-Range"));
  6425. EXPECT_EQ(JSON_DATA, res->body);
  6426. }
  6427. TEST_F(ServerTest, Issue1772) {
  6428. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6431. }
  6432. TEST_F(ServerTest, Issue609) {
  6433. auto res = cli_.Delete("/issue609");
  6434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6435. EXPECT_EQ(StatusCode::OK_200, res->status);
  6436. EXPECT_EQ(std::string("ok"), res->body);
  6437. }
  6438. TEST_F(ServerTest, GetStreamedChunked) {
  6439. auto res = cli_.Get("/streamed-chunked");
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. EXPECT_EQ(std::string("123456789"), res->body);
  6443. }
  6444. TEST_F(ServerTest, GetStreamedChunked2) {
  6445. auto res = cli_.Get("/streamed-chunked2");
  6446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6447. EXPECT_EQ(StatusCode::OK_200, res->status);
  6448. EXPECT_EQ(std::string("123456789"), res->body);
  6449. }
  6450. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6451. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. EXPECT_EQ(StatusCode::OK_200, res->status);
  6454. EXPECT_EQ(std::string("123456789"), res->body);
  6455. EXPECT_TRUE(res->has_header("Trailer"));
  6456. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6457. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6458. // Trailers are now stored separately from headers (security fix)
  6459. EXPECT_EQ(2U, res->trailers.size());
  6460. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6461. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6462. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6463. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6464. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6465. // Verify trailers are NOT in headers (security verification)
  6466. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6467. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6468. }
  6469. TEST_F(ServerTest, LargeChunkedPost) {
  6470. Request req;
  6471. req.method = "POST";
  6472. req.path = "/large-chunked";
  6473. std::string host_and_port;
  6474. host_and_port += HOST;
  6475. host_and_port += ":";
  6476. host_and_port += std::to_string(PORT);
  6477. req.headers.emplace("Host", host_and_port.c_str());
  6478. req.headers.emplace("Accept", "*/*");
  6479. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6480. req.headers.emplace("Content-Type", "text/plain");
  6481. req.headers.emplace("Content-Length", "0");
  6482. req.headers.emplace("Transfer-Encoding", "chunked");
  6483. std::string long_string(30 * 1024u, 'a');
  6484. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6485. // Attempt to make a large enough post to exceed OS buffers, to test that
  6486. // the server handles short reads if the full chunk data isn't available.
  6487. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6488. auto res = std::make_shared<Response>();
  6489. auto error = Error::Success;
  6490. auto ret = cli_.send(req, *res, error);
  6491. ASSERT_TRUE(ret);
  6492. EXPECT_EQ(StatusCode::OK_200, res->status);
  6493. }
  6494. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6495. auto res = cli_.Get("/remote_addr");
  6496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6497. EXPECT_EQ(StatusCode::OK_200, res->status);
  6498. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6499. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6500. }
  6501. TEST_F(ServerTest, GetMethodLocalAddr) {
  6502. auto res = cli_.Get("/local_addr");
  6503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6504. EXPECT_EQ(StatusCode::OK_200, res->status);
  6505. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6506. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6507. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6508. }
  6509. TEST_F(ServerTest, HTTPResponseSplitting) {
  6510. auto res = cli_.Get("/http_response_splitting");
  6511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6512. EXPECT_EQ(StatusCode::OK_200, res->status);
  6513. }
  6514. TEST_F(ServerTest, SlowRequest) {
  6515. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6516. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6517. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6518. }
  6519. #if 0
  6520. TEST_F(ServerTest, SlowPost) {
  6521. char buffer[64 * 1024];
  6522. memset(buffer, 0x42, sizeof(buffer));
  6523. auto res = cli_.Post(
  6524. "/slowpost", 64 * 1024 * 1024,
  6525. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6526. auto ret = sink.write(buffer, sizeof(buffer));
  6527. EXPECT_TRUE(ret);
  6528. return true;
  6529. },
  6530. "text/plain");
  6531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6532. EXPECT_EQ(StatusCode::OK_200, res->status);
  6533. }
  6534. TEST_F(ServerTest, SlowPostFail) {
  6535. char buffer[64 * 1024];
  6536. memset(buffer, 0x42, sizeof(buffer));
  6537. cli_.set_write_timeout(std::chrono::seconds(0));
  6538. auto res = cli_.Post(
  6539. "/slowpost", 64 * 1024 * 1024,
  6540. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6541. sink.write(buffer, sizeof(buffer));
  6542. return true;
  6543. },
  6544. "text/plain");
  6545. ASSERT_TRUE(!res);
  6546. EXPECT_EQ(Error::Write, res.error());
  6547. }
  6548. #endif
  6549. TEST_F(ServerTest, Put) {
  6550. auto res = cli_.Put("/put", "PUT", "text/plain");
  6551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6552. EXPECT_EQ(StatusCode::OK_200, res->status);
  6553. EXPECT_EQ("PUT", res->body);
  6554. }
  6555. TEST_F(ServerTest, PutWithContentProvider) {
  6556. auto res = cli_.Put(
  6557. "/put", 3,
  6558. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6559. sink.os << "PUT";
  6560. return true;
  6561. },
  6562. "text/plain");
  6563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6564. EXPECT_EQ(StatusCode::OK_200, res->status);
  6565. EXPECT_EQ("PUT", res->body);
  6566. }
  6567. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6568. auto res = cli_.Post(
  6569. "/post", 42,
  6570. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6571. return false;
  6572. },
  6573. "text/plain");
  6574. ASSERT_TRUE(!res);
  6575. EXPECT_EQ(Error::Canceled, res.error());
  6576. }
  6577. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6578. auto res = cli_.Put(
  6579. "/put",
  6580. [](size_t /*offset*/, DataSink &sink) {
  6581. sink.os << "PUT";
  6582. sink.done();
  6583. return true;
  6584. },
  6585. "text/plain");
  6586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6587. EXPECT_EQ(StatusCode::OK_200, res->status);
  6588. EXPECT_EQ("PUT", res->body);
  6589. }
  6590. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6591. auto res = cli_.Post(
  6592. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6593. "text/plain");
  6594. ASSERT_TRUE(!res);
  6595. EXPECT_EQ(Error::Canceled, res.error());
  6596. }
  6597. TEST_F(ServerTest, PostLoopBack) {
  6598. std::string body;
  6599. auto res = cli_.Post(
  6600. "/post-loopback", 9,
  6601. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6602. EXPECT_EQ(9u, length);
  6603. sink.write("123", 3);
  6604. sink.write("456", 3);
  6605. sink.write("789", 3);
  6606. return true;
  6607. },
  6608. "text/plain",
  6609. [&body](const char *data, size_t data_length) {
  6610. body.append(data, data_length);
  6611. return true;
  6612. });
  6613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6614. EXPECT_EQ(StatusCode::OK_200, res->status);
  6615. EXPECT_EQ("123456789", body);
  6616. }
  6617. TEST_F(ServerTest, PutLoopBack) {
  6618. std::string body;
  6619. auto res = cli_.Put(
  6620. "/put-loopback", 9,
  6621. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6622. EXPECT_EQ(9u, length);
  6623. sink.write("123", 3);
  6624. sink.write("456", 3);
  6625. sink.write("789", 3);
  6626. return true;
  6627. },
  6628. "text/plain",
  6629. [&body](const char *data, size_t data_length) {
  6630. body.append(data, data_length);
  6631. return true;
  6632. });
  6633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6634. EXPECT_EQ(StatusCode::OK_200, res->status);
  6635. EXPECT_EQ("123456789", body);
  6636. }
  6637. TEST_F(ServerTest, PatchLoopBack) {
  6638. std::string body;
  6639. auto res = cli_.Patch(
  6640. "/patch-loopback", 9,
  6641. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6642. EXPECT_EQ(9u, length);
  6643. sink.write("123", 3);
  6644. sink.write("456", 3);
  6645. sink.write("789", 3);
  6646. return true;
  6647. },
  6648. "text/plain",
  6649. [&body](const char *data, size_t data_length) {
  6650. body.append(data, data_length);
  6651. return true;
  6652. });
  6653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6654. EXPECT_EQ(StatusCode::OK_200, res->status);
  6655. EXPECT_EQ("123456789", body);
  6656. }
  6657. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6658. std::string body;
  6659. auto res = cli_.Post(
  6660. "/post-loopback",
  6661. [](size_t /*offset*/, DataSink &sink) {
  6662. sink.write("123", 3);
  6663. sink.write("456", 3);
  6664. sink.write("789", 3);
  6665. sink.done();
  6666. return true;
  6667. },
  6668. "text/plain",
  6669. [&body](const char *data, size_t data_length) {
  6670. body.append(data, data_length);
  6671. return true;
  6672. });
  6673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6674. EXPECT_EQ(StatusCode::OK_200, res->status);
  6675. EXPECT_EQ("123456789", body);
  6676. }
  6677. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6678. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6679. cli_.set_compress(true);
  6680. auto res = cli_.Put(
  6681. "/put", 3,
  6682. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6683. sink.os << "PUT";
  6684. return true;
  6685. },
  6686. "text/plain");
  6687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6688. EXPECT_EQ(StatusCode::OK_200, res->status);
  6689. EXPECT_EQ("PUT", res->body);
  6690. }
  6691. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6692. cli_.set_compress(true);
  6693. auto res = cli_.Post(
  6694. "/post", 42,
  6695. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6696. return false;
  6697. },
  6698. "text/plain");
  6699. ASSERT_TRUE(!res);
  6700. EXPECT_EQ(Error::Canceled, res.error());
  6701. }
  6702. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6703. cli_.set_compress(true);
  6704. auto res = cli_.Put(
  6705. "/put",
  6706. [](size_t /*offset*/, DataSink &sink) {
  6707. sink.os << "PUT";
  6708. sink.done();
  6709. return true;
  6710. },
  6711. "text/plain");
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_EQ(StatusCode::OK_200, res->status);
  6714. EXPECT_EQ("PUT", res->body);
  6715. }
  6716. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6717. cli_.set_compress(true);
  6718. auto res = cli_.Post(
  6719. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6720. "text/plain");
  6721. ASSERT_TRUE(!res);
  6722. EXPECT_EQ(Error::Canceled, res.error());
  6723. }
  6724. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6725. cli_.set_compress(true);
  6726. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::OK_200, res->status);
  6729. EXPECT_EQ(LARGE_DATA, res->body);
  6730. }
  6731. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6732. #ifdef CPPHTTPLIB_SSL_ENABLED
  6733. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6734. Client cli(s.c_str());
  6735. cli.enable_server_certificate_verification(false);
  6736. #else
  6737. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6738. Client cli(s.c_str());
  6739. #endif
  6740. cli.set_compress(true);
  6741. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6743. EXPECT_EQ(StatusCode::OK_200, res->status);
  6744. EXPECT_EQ(LARGE_DATA, res->body);
  6745. // The compressed size should be less than a 10th of the original. May vary
  6746. // depending on the zlib library.
  6747. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6748. static_cast<uint64_t>(10 * 1024 * 1024));
  6749. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6750. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6751. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6752. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6753. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6754. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6755. #endif
  6756. }
  6757. TEST_F(ServerTest, PutContentWithDeflate) {
  6758. cli_.set_compress(false);
  6759. Headers headers;
  6760. headers.emplace("Content-Encoding", "deflate");
  6761. // PUT in deflate format:
  6762. auto res = cli_.Put("/put", headers,
  6763. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6765. EXPECT_EQ(StatusCode::OK_200, res->status);
  6766. EXPECT_EQ("PUT", res->body);
  6767. }
  6768. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6769. Headers headers;
  6770. headers.emplace("Accept-Encoding", "gzip, deflate");
  6771. auto res = cli_.Get("/streamed-chunked", headers);
  6772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6773. EXPECT_EQ(StatusCode::OK_200, res->status);
  6774. EXPECT_EQ(std::string("123456789"), res->body);
  6775. }
  6776. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6777. Headers headers;
  6778. headers.emplace("Accept-Encoding", "gzip, deflate");
  6779. auto res = cli_.Get("/streamed-chunked2", headers);
  6780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6781. EXPECT_EQ(StatusCode::OK_200, res->status);
  6782. EXPECT_EQ(std::string("123456789"), res->body);
  6783. }
  6784. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6785. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6787. EXPECT_EQ(StatusCode::OK_200, res->status);
  6788. }
  6789. TEST(GzipDecompressor, ChunkedDecompression) {
  6790. std::string data;
  6791. for (size_t i = 0; i < 32 * 1024; ++i) {
  6792. data.push_back(static_cast<char>('a' + i % 26));
  6793. }
  6794. std::string compressed_data;
  6795. {
  6796. httplib::detail::gzip_compressor compressor;
  6797. bool result = compressor.compress(
  6798. data.data(), data.size(),
  6799. /*last=*/true,
  6800. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6801. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6802. compressed_data_size);
  6803. return true;
  6804. });
  6805. ASSERT_TRUE(result);
  6806. }
  6807. std::string decompressed_data;
  6808. {
  6809. httplib::detail::gzip_decompressor decompressor;
  6810. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6811. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6812. size_t chunk_size = 130;
  6813. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6814. chunk_begin += chunk_size) {
  6815. size_t current_chunk_size =
  6816. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6817. bool result = decompressor.decompress(
  6818. compressed_data.data() + chunk_begin, current_chunk_size,
  6819. [&](const char *decompressed_data_chunk,
  6820. size_t decompressed_data_chunk_size) {
  6821. decompressed_data.insert(decompressed_data.size(),
  6822. decompressed_data_chunk,
  6823. decompressed_data_chunk_size);
  6824. return true;
  6825. });
  6826. ASSERT_TRUE(result);
  6827. }
  6828. }
  6829. ASSERT_EQ(data, decompressed_data);
  6830. }
  6831. TEST(GzipDecompressor, DeflateDecompression) {
  6832. std::string original_text = "Raw deflate without gzip";
  6833. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6834. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6835. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6836. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6837. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6838. std::string decompressed_data;
  6839. {
  6840. httplib::detail::gzip_decompressor decompressor;
  6841. bool result = decompressor.decompress(
  6842. compressed_data.data(), compressed_data.size(),
  6843. [&](const char *decompressed_data_chunk,
  6844. size_t decompressed_data_chunk_size) {
  6845. decompressed_data.insert(decompressed_data.size(),
  6846. decompressed_data_chunk,
  6847. decompressed_data_chunk_size);
  6848. return true;
  6849. });
  6850. ASSERT_TRUE(result);
  6851. }
  6852. ASSERT_EQ(original_text, decompressed_data);
  6853. }
  6854. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6855. std::string original_text = "Raw deflate without gzip";
  6856. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6857. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6858. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6859. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6860. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6861. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6862. std::string decompressed_data;
  6863. {
  6864. httplib::detail::gzip_decompressor decompressor;
  6865. bool result = decompressor.decompress(
  6866. compressed_data.data(), compressed_data.size(),
  6867. [&](const char *decompressed_data_chunk,
  6868. size_t decompressed_data_chunk_size) {
  6869. decompressed_data.insert(decompressed_data.size(),
  6870. decompressed_data_chunk,
  6871. decompressed_data_chunk_size);
  6872. return true;
  6873. });
  6874. ASSERT_TRUE(result);
  6875. }
  6876. ASSERT_EQ(original_text, decompressed_data);
  6877. }
  6878. #endif
  6879. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6880. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6881. Headers headers;
  6882. headers.emplace("Accept-Encoding", "br");
  6883. auto res = cli_.Get("/streamed-chunked", headers);
  6884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6885. EXPECT_EQ(StatusCode::OK_200, res->status);
  6886. EXPECT_EQ(std::string("123456789"), res->body);
  6887. }
  6888. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6889. Headers headers;
  6890. headers.emplace("Accept-Encoding", "br");
  6891. auto res = cli_.Get("/streamed-chunked2", headers);
  6892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6893. EXPECT_EQ(StatusCode::OK_200, res->status);
  6894. EXPECT_EQ(std::string("123456789"), res->body);
  6895. }
  6896. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6897. cli_.set_compress(true);
  6898. auto res = cli_.Put(
  6899. "/put", 3,
  6900. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6901. sink.os << "PUT";
  6902. return true;
  6903. },
  6904. "text/plain");
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::OK_200, res->status);
  6907. EXPECT_EQ("PUT", res->body);
  6908. }
  6909. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6910. cli_.set_compress(true);
  6911. auto res = cli_.Put(
  6912. "/put",
  6913. [](size_t /*offset*/, DataSink &sink) {
  6914. sink.os << "PUT";
  6915. sink.done();
  6916. return true;
  6917. },
  6918. "text/plain");
  6919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6920. EXPECT_EQ(StatusCode::OK_200, res->status);
  6921. EXPECT_EQ("PUT", res->body);
  6922. }
  6923. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6924. cli_.set_compress(true);
  6925. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6927. EXPECT_EQ(StatusCode::OK_200, res->status);
  6928. EXPECT_EQ(LARGE_DATA, res->body);
  6929. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6930. }
  6931. #endif
  6932. TEST_F(ServerTest, Patch) {
  6933. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6935. EXPECT_EQ(StatusCode::OK_200, res->status);
  6936. EXPECT_EQ("PATCH", res->body);
  6937. }
  6938. TEST_F(ServerTest, Delete) {
  6939. auto res = cli_.Delete("/delete");
  6940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6941. EXPECT_EQ(StatusCode::OK_200, res->status);
  6942. EXPECT_EQ("DELETE", res->body);
  6943. }
  6944. TEST_F(ServerTest, DeleteContentReceiver) {
  6945. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. EXPECT_EQ(StatusCode::OK_200, res->status);
  6948. EXPECT_EQ("content", res->body);
  6949. }
  6950. TEST_F(ServerTest, Options) {
  6951. auto res = cli_.Options("*");
  6952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6953. EXPECT_EQ(StatusCode::OK_200, res->status);
  6954. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6955. EXPECT_TRUE(res->body.empty());
  6956. }
  6957. TEST_F(ServerTest, URL) {
  6958. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6960. EXPECT_EQ(StatusCode::OK_200, res->status);
  6961. }
  6962. TEST_F(ServerTest, ArrayParam) {
  6963. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. EXPECT_EQ(StatusCode::OK_200, res->status);
  6966. }
  6967. TEST_F(ServerTest, ArrayParamValues) {
  6968. auto res =
  6969. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6971. EXPECT_EQ(StatusCode::OK_200, res->status);
  6972. }
  6973. TEST_F(ServerTest, NoMultipleHeaders) {
  6974. Headers headers = {{"Content-Length", "5"}};
  6975. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6976. "text/plain");
  6977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6978. EXPECT_EQ(StatusCode::OK_200, res->status);
  6979. }
  6980. TEST_F(ServerTest, PostContentReceiver) {
  6981. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6983. ASSERT_EQ(StatusCode::OK_200, res->status);
  6984. ASSERT_EQ("content", res->body);
  6985. }
  6986. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6987. UploadFormDataItems items = {
  6988. {"text1", "text default", "", ""},
  6989. {"text2", "aωb", "", ""},
  6990. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6991. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6992. {"file3", "", "", "application/octet-stream"},
  6993. };
  6994. auto res = cli_.Post("/content_receiver", items);
  6995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6996. EXPECT_EQ(StatusCode::OK_200, res->status);
  6997. }
  6998. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6999. UploadFormDataItems items = {
  7000. {"text1", "text default", "", ""},
  7001. {"text2", "aωb", "", ""},
  7002. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7003. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7004. {"file3", "", "", "application/octet-stream"},
  7005. };
  7006. auto boundary = std::string("+++++");
  7007. std::string body;
  7008. for (const auto &item : items) {
  7009. body += "--" + boundary + "\r\n";
  7010. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7011. if (!item.filename.empty()) {
  7012. body += "; filename=\"" + item.filename + "\"";
  7013. }
  7014. body += "\r\n";
  7015. if (!item.content_type.empty()) {
  7016. body += "Content-Type: " + item.content_type + "\r\n";
  7017. }
  7018. body += "\r\n";
  7019. body += item.content + "\r\n";
  7020. }
  7021. body += "--" + boundary + "--\r\n";
  7022. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7023. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7025. EXPECT_EQ(StatusCode::OK_200, res->status);
  7026. }
  7027. TEST(MultipartFormDataTest, FieldEscaping) {
  7028. Server svr;
  7029. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7030. const ContentReader &content_reader) {
  7031. ASSERT_TRUE(req.is_multipart_form_data());
  7032. std::vector<FormData> received;
  7033. content_reader(
  7034. [&](const FormData &file) {
  7035. received.push_back(file);
  7036. return true;
  7037. },
  7038. [&](const char *data, size_t data_length) {
  7039. received.back().content.append(data, data_length);
  7040. return true;
  7041. });
  7042. // '"', CR and LF in names and filenames are escaped following the
  7043. // WHATWG HTML standard, so each part still parses as a single part
  7044. // with no injected headers. Content types get CR/LF escaped too,
  7045. // while '"' (legal there, e.g. quoted charset) is preserved.
  7046. ASSERT_EQ(4U, received.size());
  7047. EXPECT_EQ("na%22me", received[0].name);
  7048. EXPECT_EQ("quoted name", received[0].content);
  7049. EXPECT_EQ("file", received[1].name);
  7050. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7051. received[1].filename);
  7052. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7053. EXPECT_EQ("injected", received[1].content);
  7054. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7055. EXPECT_EQ("my%22file.txt", received[2].filename);
  7056. EXPECT_EQ("cr lf name", received[2].content);
  7057. EXPECT_EQ("typed", received[3].name);
  7058. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7059. received[3].content_type);
  7060. EXPECT_EQ("typed content", received[3].content);
  7061. });
  7062. auto port = svr.bind_to_any_port("localhost");
  7063. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7064. auto se = detail::scope_exit([&] {
  7065. svr.stop();
  7066. t.join();
  7067. ASSERT_FALSE(svr.is_running());
  7068. });
  7069. svr.wait_until_ready();
  7070. Client cli("localhost", port);
  7071. UploadFormDataItems items = {
  7072. {"na\"me", "quoted name", "", ""},
  7073. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7074. "application/octet-stream"},
  7075. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7076. {"typed", "typed content", "",
  7077. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7078. };
  7079. auto res = cli.Post("/post", items);
  7080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7081. EXPECT_EQ(StatusCode::OK_200, res->status);
  7082. }
  7083. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7084. const UploadFormDataItems items = {
  7085. {"name1", "Content 1", "", ""},
  7086. {"name2", "Content 2", "file2.txt", "text/plain"},
  7087. };
  7088. Server svr;
  7089. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7090. const ContentReader &content_reader) {
  7091. ASSERT_TRUE(req.is_multipart_form_data());
  7092. std::vector<FormData> received;
  7093. content_reader(
  7094. [&](const FormData &file) {
  7095. received.push_back(file);
  7096. return true;
  7097. },
  7098. [&](const char *data, size_t data_length) {
  7099. received.back().content.append(data, data_length);
  7100. return true;
  7101. });
  7102. ASSERT_EQ(2U, received.size());
  7103. EXPECT_EQ("name1", received[0].name);
  7104. EXPECT_EQ("Content 1", received[0].content);
  7105. EXPECT_EQ("name2", received[1].name);
  7106. EXPECT_EQ("Content 2", received[1].content);
  7107. EXPECT_EQ("file2.txt", received[1].filename);
  7108. EXPECT_EQ("text/plain", received[1].content_type);
  7109. });
  7110. auto port = svr.bind_to_any_port("localhost");
  7111. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7112. auto se = detail::scope_exit([&] {
  7113. svr.stop();
  7114. t.join();
  7115. ASSERT_FALSE(svr.is_running());
  7116. });
  7117. svr.wait_until_ready();
  7118. Client cli("localhost", port);
  7119. // Whole-body serialization with a generated boundary
  7120. {
  7121. MultipartFormDataWriter writer;
  7122. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7123. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7124. writer.content_type());
  7125. auto body = writer.serialize(items);
  7126. EXPECT_EQ(body.size(), writer.content_length(items));
  7127. auto res = cli.Post("/post", body, writer.content_type());
  7128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7129. EXPECT_EQ(StatusCode::OK_200, res->status);
  7130. }
  7131. // Per-part framing with a custom boundary via a content provider
  7132. {
  7133. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7134. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7135. MultipartFormDataWriter writer("custom-boundary_123");
  7136. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7137. std::string body;
  7138. for (const auto &item : items) {
  7139. body += writer.item_begin(item);
  7140. body += item.content;
  7141. body += MultipartFormDataWriter::item_end();
  7142. }
  7143. body += writer.finish();
  7144. EXPECT_EQ(body.size(), writer.content_length(items));
  7145. auto res = cli.Post(
  7146. "/post", body.size(),
  7147. [&](size_t offset, size_t length, DataSink &sink) {
  7148. sink.write(body.data() + offset, length);
  7149. return true;
  7150. },
  7151. writer.content_type());
  7152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7153. EXPECT_EQ(StatusCode::OK_200, res->status);
  7154. }
  7155. }
  7156. TEST_F(ServerTest, PostContentReceiverGzip) {
  7157. cli_.set_compress(true);
  7158. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7160. ASSERT_EQ(StatusCode::OK_200, res->status);
  7161. ASSERT_EQ("content", res->body);
  7162. }
  7163. TEST_F(ServerTest, PutContentReceiver) {
  7164. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7166. ASSERT_EQ(StatusCode::OK_200, res->status);
  7167. ASSERT_EQ("content", res->body);
  7168. }
  7169. TEST_F(ServerTest, PatchContentReceiver) {
  7170. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7172. ASSERT_EQ(StatusCode::OK_200, res->status);
  7173. ASSERT_EQ("content", res->body);
  7174. }
  7175. template <typename ClientType>
  7176. void TestWithHeadersAndContentReceiver(
  7177. ClientType &cli,
  7178. std::function<Result(ClientType &, const std::string &, const Headers &,
  7179. const std::string &, const std::string &,
  7180. ContentReceiver, DownloadProgress)>
  7181. request_func) {
  7182. Headers headers;
  7183. headers.emplace("X-Custom-Header", "test-value");
  7184. std::string received_body;
  7185. auto res = request_func(
  7186. cli, "/content_receiver", headers, "content", "application/json",
  7187. [&](const char *data, size_t data_length) {
  7188. received_body.append(data, data_length);
  7189. return true;
  7190. },
  7191. nullptr);
  7192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7193. EXPECT_EQ(StatusCode::OK_200, res->status);
  7194. EXPECT_EQ("content", received_body);
  7195. }
  7196. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7197. #ifdef CPPHTTPLIB_SSL_ENABLED
  7198. using ClientT = SSLClient;
  7199. #else
  7200. using ClientT = Client;
  7201. #endif
  7202. TestWithHeadersAndContentReceiver<ClientT>(
  7203. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7204. const std::string &body, const std::string &content_type,
  7205. ContentReceiver receiver, DownloadProgress progress) {
  7206. return cli.Post(path, headers, body, content_type, receiver, progress);
  7207. });
  7208. }
  7209. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7210. #ifdef CPPHTTPLIB_SSL_ENABLED
  7211. using ClientT = SSLClient;
  7212. #else
  7213. using ClientT = Client;
  7214. #endif
  7215. TestWithHeadersAndContentReceiver<ClientT>(
  7216. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7217. const std::string &body, const std::string &content_type,
  7218. ContentReceiver receiver, DownloadProgress progress) {
  7219. return cli.Put(path, headers, body, content_type, receiver, progress);
  7220. });
  7221. }
  7222. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7223. #ifdef CPPHTTPLIB_SSL_ENABLED
  7224. using ClientT = SSLClient;
  7225. #else
  7226. using ClientT = Client;
  7227. #endif
  7228. TestWithHeadersAndContentReceiver<ClientT>(
  7229. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7230. const std::string &body, const std::string &content_type,
  7231. ContentReceiver receiver, DownloadProgress progress) {
  7232. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7233. });
  7234. }
  7235. template <typename ClientType>
  7236. void TestWithHeadersAndContentReceiverWithProgress(
  7237. ClientType &cli,
  7238. std::function<Result(ClientType &, const std::string &, const Headers &,
  7239. const std::string &, const std::string &,
  7240. ContentReceiver, DownloadProgress)>
  7241. request_func) {
  7242. Headers headers;
  7243. headers.emplace("X-Test-Header", "progress-test");
  7244. std::string received_body;
  7245. auto progress_called = false;
  7246. auto res = request_func(
  7247. cli, "/content_receiver", headers, "content", "text/plain",
  7248. [&](const char *data, size_t data_length) {
  7249. received_body.append(data, data_length);
  7250. return true;
  7251. },
  7252. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7253. progress_called = true;
  7254. return true;
  7255. });
  7256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7257. EXPECT_EQ(StatusCode::OK_200, res->status);
  7258. EXPECT_EQ("content", received_body);
  7259. EXPECT_TRUE(progress_called);
  7260. }
  7261. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7262. #ifdef CPPHTTPLIB_SSL_ENABLED
  7263. using ClientT = SSLClient;
  7264. #else
  7265. using ClientT = Client;
  7266. #endif
  7267. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7268. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7269. const std::string &body, const std::string &content_type,
  7270. ContentReceiver receiver, DownloadProgress progress) {
  7271. return cli.Post(path, headers, body, content_type, receiver, progress);
  7272. });
  7273. }
  7274. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7275. #ifdef CPPHTTPLIB_SSL_ENABLED
  7276. using ClientT = SSLClient;
  7277. #else
  7278. using ClientT = Client;
  7279. #endif
  7280. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7281. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7282. const std::string &body, const std::string &content_type,
  7283. ContentReceiver receiver, DownloadProgress progress) {
  7284. return cli.Put(path, headers, body, content_type, receiver, progress);
  7285. });
  7286. }
  7287. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7288. #ifdef CPPHTTPLIB_SSL_ENABLED
  7289. using ClientT = SSLClient;
  7290. #else
  7291. using ClientT = Client;
  7292. #endif
  7293. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7294. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7295. const std::string &body, const std::string &content_type,
  7296. ContentReceiver receiver, DownloadProgress progress) {
  7297. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7298. });
  7299. }
  7300. template <typename ClientType>
  7301. void TestWithHeadersAndContentReceiverError(
  7302. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7303. const Headers &, const std::string &,
  7304. const std::string &, ContentReceiver)>
  7305. request_func) {
  7306. Headers headers;
  7307. headers.emplace("X-Error-Test", "true");
  7308. std::string received_body;
  7309. auto receiver_failed = false;
  7310. auto res =
  7311. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7312. [&](const char *data, size_t data_length) {
  7313. received_body.append(data, data_length);
  7314. receiver_failed = true;
  7315. return false;
  7316. });
  7317. ASSERT_FALSE(res);
  7318. EXPECT_TRUE(receiver_failed);
  7319. }
  7320. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7321. #ifdef CPPHTTPLIB_SSL_ENABLED
  7322. using ClientT = SSLClient;
  7323. #else
  7324. using ClientT = Client;
  7325. #endif
  7326. TestWithHeadersAndContentReceiverError<ClientT>(
  7327. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7328. const std::string &body, const std::string &content_type,
  7329. ContentReceiver receiver) {
  7330. return cli.Post(path, headers, body, content_type, receiver);
  7331. });
  7332. }
  7333. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7334. #ifdef CPPHTTPLIB_SSL_ENABLED
  7335. using ClientT = SSLClient;
  7336. #else
  7337. using ClientT = Client;
  7338. #endif
  7339. TestWithHeadersAndContentReceiverError<ClientT>(
  7340. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7341. const std::string &body, const std::string &content_type,
  7342. ContentReceiver receiver) {
  7343. return cli.Put(path, headers, body, content_type, receiver);
  7344. });
  7345. }
  7346. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7347. #ifdef CPPHTTPLIB_SSL_ENABLED
  7348. using ClientT = SSLClient;
  7349. #else
  7350. using ClientT = Client;
  7351. #endif
  7352. TestWithHeadersAndContentReceiverError<ClientT>(
  7353. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7354. const std::string &body, const std::string &content_type,
  7355. ContentReceiver receiver) {
  7356. return cli.Patch(path, headers, body, content_type, receiver);
  7357. });
  7358. }
  7359. TEST_F(ServerTest, PostQueryStringAndBody) {
  7360. auto res =
  7361. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7363. ASSERT_EQ(StatusCode::OK_200, res->status);
  7364. }
  7365. TEST_F(ServerTest, HTTP2Magic) {
  7366. Request req;
  7367. req.method = "PRI";
  7368. req.path = "*";
  7369. req.body = "SM";
  7370. auto res = std::make_shared<Response>();
  7371. auto error = Error::Success;
  7372. auto ret = cli_.send(req, *res, error);
  7373. ASSERT_TRUE(ret);
  7374. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7375. }
  7376. TEST_F(ServerTest, KeepAlive) {
  7377. auto res = cli_.Get("/hi");
  7378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7379. EXPECT_EQ(StatusCode::OK_200, res->status);
  7380. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7381. EXPECT_EQ("Hello World!", res->body);
  7382. res = cli_.Get("/hi");
  7383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7384. EXPECT_EQ(StatusCode::OK_200, res->status);
  7385. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7386. EXPECT_EQ("Hello World!", res->body);
  7387. res = cli_.Get("/hi");
  7388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7389. EXPECT_EQ(StatusCode::OK_200, res->status);
  7390. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7391. EXPECT_EQ("Hello World!", res->body);
  7392. res = cli_.Get("/not-exist");
  7393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7394. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7395. res = cli_.Post("/empty", "", "text/plain");
  7396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7397. EXPECT_EQ(StatusCode::OK_200, res->status);
  7398. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7399. EXPECT_EQ("empty", res->body);
  7400. EXPECT_EQ("close", res->get_header_value("Connection"));
  7401. res = cli_.Post(
  7402. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7403. "text/plain");
  7404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7405. EXPECT_EQ(StatusCode::OK_200, res->status);
  7406. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7407. EXPECT_EQ("empty", res->body);
  7408. cli_.set_keep_alive(false);
  7409. res = cli_.Get("/last-request");
  7410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7411. EXPECT_EQ(StatusCode::OK_200, res->status);
  7412. EXPECT_EQ("close", res->get_header_value("Connection"));
  7413. }
  7414. TEST_F(ServerTest, TooManyRedirect) {
  7415. cli_.set_follow_location(true);
  7416. auto res = cli_.Get("/redirect/0");
  7417. ASSERT_TRUE(!res);
  7418. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7419. }
  7420. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7421. Request req;
  7422. req.method = "FOOBAR";
  7423. req.path = "/hi";
  7424. cli_.set_keep_alive(true);
  7425. auto res = cli_.send(req);
  7426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7427. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7428. EXPECT_EQ("close", res->get_header_value("Connection"));
  7429. EXPECT_FALSE(cli_.is_socket_open());
  7430. }
  7431. TEST_F(ServerTest, CustomRouteReadsBody) {
  7432. const std::string xml =
  7433. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7434. Request req;
  7435. req.method = "PROPFIND";
  7436. req.path = "/dav/dir";
  7437. req.set_header("Depth", "1");
  7438. req.body = xml;
  7439. auto res = cli_.send(req);
  7440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7441. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7442. EXPECT_EQ(xml, res->body);
  7443. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7444. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7445. }
  7446. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7447. Request req;
  7448. req.method = "PROPFIND";
  7449. req.path = "/dav/42";
  7450. auto res = cli_.send(req);
  7451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7452. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7453. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7454. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7455. }
  7456. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7457. Request req;
  7458. req.method = "PROPFIND";
  7459. req.path = "/dav-re/123";
  7460. auto res = cli_.send(req);
  7461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7462. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7463. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7464. }
  7465. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7466. Request req;
  7467. req.method = "MKCOL";
  7468. req.path = "/dav-mkcol";
  7469. auto res = cli_.send(req);
  7470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7471. EXPECT_EQ(StatusCode::Created_201, res->status);
  7472. }
  7473. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7474. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7475. Request req;
  7476. req.method = "REPORT";
  7477. req.path = "/dav-report";
  7478. req.body = xml;
  7479. auto res = cli_.send(req);
  7480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7481. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7482. EXPECT_EQ(xml, res->body);
  7483. }
  7484. // A content reader route must fire even when the request carries no body,
  7485. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7486. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7487. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7488. Request req;
  7489. req.method = "REPORT";
  7490. req.path = "/dav-report";
  7491. auto res = cli_.send(req);
  7492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7493. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7494. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7495. }
  7496. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7497. Request req;
  7498. req.method = "PROPFIND";
  7499. req.path = "/not-dav";
  7500. auto res = cli_.send(req);
  7501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7502. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7503. }
  7504. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7505. Request req;
  7506. req.method = "UNLOCK";
  7507. req.path = "/dav/dir";
  7508. cli_.set_keep_alive(true);
  7509. auto res = cli_.send(req);
  7510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7511. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7512. EXPECT_EQ("close", res->get_header_value("Connection"));
  7513. EXPECT_FALSE(cli_.is_socket_open());
  7514. }
  7515. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7516. // The mount point serves this path, but only for GET and HEAD.
  7517. auto get_res = cli_.Get("/dir/index.html");
  7518. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7519. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7520. Request req;
  7521. req.method = "PROPFIND";
  7522. req.path = "/dir/index.html";
  7523. auto res = cli_.send(req);
  7524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7526. }
  7527. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7528. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7529. cli_.set_keep_alive(true);
  7530. for (auto i = 0; i < 2; i++) {
  7531. Request req;
  7532. req.method = "PROPFIND";
  7533. req.path = "/dav/dir";
  7534. req.body = xml;
  7535. auto res = cli_.send(req);
  7536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7537. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7538. EXPECT_EQ(xml, res->body);
  7539. EXPECT_TRUE(cli_.is_socket_open());
  7540. }
  7541. // A built-in method must still be served on the same connection.
  7542. cli_.set_keep_alive(false);
  7543. auto res = cli_.Get("/hi");
  7544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7545. EXPECT_EQ(StatusCode::OK_200, res->status);
  7546. EXPECT_EQ("close", res->get_header_value("Connection"));
  7547. }
  7548. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7549. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7550. Request req;
  7551. req.method = "PROPFIND";
  7552. req.path = "/dav/dir";
  7553. req.set_header("Expect", "100-continue");
  7554. req.body = xml;
  7555. auto res = cli_.send(req);
  7556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7557. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7558. EXPECT_EQ(xml, res->body);
  7559. }
  7560. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7561. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7562. TEST_F(ServerTest, Gzip) {
  7563. Headers headers;
  7564. headers.emplace("Accept-Encoding", "gzip, deflate");
  7565. auto res = cli_.Get("/compress", headers);
  7566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7567. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7569. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7571. "7890123456789012345678901234567890",
  7572. res->body);
  7573. EXPECT_EQ(StatusCode::OK_200, res->status);
  7574. }
  7575. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7576. Headers headers;
  7577. headers.emplace("Accept-Encoding", "gzip, deflate");
  7578. auto res = cli_.Get("/compress-with-charset", headers);
  7579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7580. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7581. EXPECT_EQ("application/json; charset=utf-8",
  7582. res->get_header_value("Content-Type"));
  7583. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7584. "7890123456789012345678901234567890",
  7585. res->body);
  7586. EXPECT_EQ(StatusCode::OK_200, res->status);
  7587. }
  7588. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7589. Headers headers;
  7590. headers.emplace("Accept-Encoding", "");
  7591. auto res = cli_.Get("/compress", headers);
  7592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7593. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7594. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7595. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7596. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7597. "7890123456789012345678901234567890",
  7598. res->body);
  7599. EXPECT_EQ(StatusCode::OK_200, res->status);
  7600. }
  7601. TEST_F(ServerTest, GzipWithContentReceiver) {
  7602. Headers headers;
  7603. headers.emplace("Accept-Encoding", "gzip, deflate");
  7604. std::string body;
  7605. auto res = cli_.Get("/compress", headers,
  7606. [&](const char *data, uint64_t data_length) {
  7607. EXPECT_EQ(100U, data_length);
  7608. body.append(data, data_length);
  7609. return true;
  7610. });
  7611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7612. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7613. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7614. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7615. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7616. "7890123456789012345678901234567890",
  7617. body);
  7618. EXPECT_EQ(StatusCode::OK_200, res->status);
  7619. }
  7620. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7621. Headers headers;
  7622. headers.emplace("Accept-Encoding", "gzip, deflate");
  7623. cli_.set_decompress(false);
  7624. auto res = cli_.Get("/compress", headers);
  7625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7626. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7627. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7628. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7629. EXPECT_EQ(33U, res->body.size());
  7630. EXPECT_EQ(StatusCode::OK_200, res->status);
  7631. }
  7632. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7633. Headers headers;
  7634. headers.emplace("Accept-Encoding", "");
  7635. std::string body;
  7636. auto res = cli_.Get("/compress", headers,
  7637. [&](const char *data, uint64_t data_length) {
  7638. EXPECT_EQ(100U, data_length);
  7639. body.append(data, data_length);
  7640. return true;
  7641. });
  7642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7643. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7644. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7645. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7646. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7647. "7890123456789012345678901234567890",
  7648. body);
  7649. EXPECT_EQ(StatusCode::OK_200, res->status);
  7650. }
  7651. TEST_F(ServerTest, NoGzip) {
  7652. Headers headers;
  7653. headers.emplace("Accept-Encoding", "gzip, deflate");
  7654. auto res = cli_.Get("/nocompress", headers);
  7655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7656. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7657. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7658. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7659. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7660. "7890123456789012345678901234567890",
  7661. res->body);
  7662. EXPECT_EQ(StatusCode::OK_200, res->status);
  7663. }
  7664. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7665. Headers headers;
  7666. headers.emplace("Accept-Encoding", "gzip, deflate");
  7667. std::string body;
  7668. auto res = cli_.Get("/nocompress", headers,
  7669. [&](const char *data, uint64_t data_length) {
  7670. EXPECT_EQ(100U, data_length);
  7671. body.append(data, data_length);
  7672. return true;
  7673. });
  7674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7675. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7676. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7677. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7678. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7679. "7890123456789012345678901234567890",
  7680. body);
  7681. EXPECT_EQ(StatusCode::OK_200, res->status);
  7682. }
  7683. TEST_F(ServerTest, MultipartFormDataGzip) {
  7684. UploadFormDataItems items = {
  7685. {"key1", "test", "", ""},
  7686. {"key2", "--abcdefg123", "", ""},
  7687. };
  7688. cli_.set_compress(true);
  7689. auto res = cli_.Post("/compress-multipart", items);
  7690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7691. EXPECT_EQ(StatusCode::OK_200, res->status);
  7692. }
  7693. #endif
  7694. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7695. // Static file compression is opt-in, so these run their own server rather than
  7696. // flipping it on for the shared ServerTest fixture, which would silently
  7697. // rewrite what every other static file test is asserting.
  7698. class StaticFileCompressionTest : public ::testing::Test {
  7699. protected:
  7700. void TearDown() override {
  7701. if (t_.joinable()) {
  7702. svr_.stop();
  7703. t_.join();
  7704. }
  7705. }
  7706. int start(const std::function<void(Server &)> &configure = nullptr) {
  7707. // Serves the same tree as a directory of build-time compressed assets
  7708. // would be served: the mount point names the coding the files are already
  7709. // stored in. Registered before "/" so it is the one that matches.
  7710. svr_.set_mount_point("/pre-encoded", "./www",
  7711. {{"Content-Encoding", "gzip"}});
  7712. svr_.set_mount_point("/", "./www");
  7713. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7714. res.set_file_content("./www/dir/index.html", "text/html");
  7715. });
  7716. svr_.Get("/pre-encoded-file-content",
  7717. [](const Request & /*req*/, Response &res) {
  7718. res.set_header("Content-Encoding", "gzip");
  7719. res.set_file_content("./www/dir/index.html", "text/html");
  7720. });
  7721. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7722. res.set_content_provider(
  7723. 6, "text/plain",
  7724. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7725. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7726. return true;
  7727. });
  7728. });
  7729. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7730. res.set_content_provider(
  7731. 1000, "text/plain",
  7732. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7733. if (offset < 100) {
  7734. std::string data(100, 'A');
  7735. sink.write(data.data(), data.size());
  7736. return true;
  7737. }
  7738. std::this_thread::sleep_for(std::chrono::seconds(2));
  7739. std::string data(900, 'B');
  7740. sink.write(data.data(), data.size());
  7741. return true;
  7742. });
  7743. });
  7744. if (configure) { configure(svr_); }
  7745. auto port = svr_.bind_to_any_port(HOST);
  7746. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7747. svr_.wait_until_ready();
  7748. return port;
  7749. }
  7750. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7751. // Every file under ./www except 1MB.txt is smaller than the default
  7752. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7753. // it out of the way.
  7754. static void enable_without_floor(Server &svr) {
  7755. svr.set_static_file_compression(true);
  7756. svr.set_static_file_compression_min_length(0);
  7757. }
  7758. Server svr_;
  7759. std::thread t_;
  7760. };
  7761. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7762. auto port = start();
  7763. Client cli(HOST, port);
  7764. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7766. EXPECT_EQ(StatusCode::OK_200, res->status);
  7767. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7768. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7769. EXPECT_EQ(1048576U, res->body.size());
  7770. }
  7771. TEST_F(StaticFileCompressionTest, MountPoint) {
  7772. auto port = start(enable);
  7773. Client cli(HOST, port);
  7774. cli.set_decompress(false);
  7775. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7777. EXPECT_EQ(StatusCode::OK_200, res->status);
  7778. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7779. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7780. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7781. // The response stays self-delimiting: a length, not a chunked body.
  7782. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7783. EXPECT_EQ(std::to_string(res->body.size()),
  7784. res->get_header_value("Content-Length"));
  7785. EXPECT_LT(res->body.size(), 1048576U);
  7786. EXPECT_FALSE(res->body.empty());
  7787. }
  7788. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7789. auto port = start(enable);
  7790. Client cli(HOST, port);
  7791. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7793. EXPECT_EQ(StatusCode::OK_200, res->status);
  7794. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7795. EXPECT_EQ(1048576U, res->body.size());
  7796. }
  7797. TEST_F(StaticFileCompressionTest, FileContent) {
  7798. auto port = start(enable_without_floor);
  7799. Client cli(HOST, port);
  7800. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7802. EXPECT_EQ(StatusCode::OK_200, res->status);
  7803. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7804. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7805. EXPECT_EQ(104U, res->body.size());
  7806. }
  7807. // A handler that serves an already-encoded file names the coding itself. The
  7808. // file-backed path decided its coding from Accept-Encoding and the content
  7809. // type alone, so it compressed the stored bytes a second time and appended a
  7810. // second Content-Encoding field line.
  7811. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7812. auto port = start(enable_without_floor);
  7813. Client cli(HOST, port);
  7814. cli.set_decompress(false);
  7815. auto res = cli.Get("/pre-encoded-file-content",
  7816. Headers{{"Accept-Encoding", "gzip"}});
  7817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7818. EXPECT_EQ(StatusCode::OK_200, res->status);
  7819. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7820. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7821. // Vary belongs to a coding the server chose, and it chose none here.
  7822. EXPECT_FALSE(res->has_header("Vary"));
  7823. // The file travels exactly as it is stored on disk.
  7824. EXPECT_EQ(104U, res->body.size());
  7825. }
  7826. // The 1MB file clears the default floor, so this one runs the configuration a
  7827. // deployment would actually have.
  7828. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7829. auto port = start(enable);
  7830. Client cli(HOST, port);
  7831. cli.set_decompress(false);
  7832. auto res =
  7833. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7835. EXPECT_EQ(StatusCode::OK_200, res->status);
  7836. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7837. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7838. EXPECT_FALSE(res->has_header("Vary"));
  7839. EXPECT_EQ(1048576U, res->body.size());
  7840. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7841. }
  7842. TEST_F(StaticFileCompressionTest, Head) {
  7843. auto port = start(enable);
  7844. Client cli(HOST, port);
  7845. cli.set_decompress(false);
  7846. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7847. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7848. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7850. EXPECT_EQ(StatusCode::OK_200, res->status);
  7851. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7852. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7853. // HEAD still reports the size a GET would return.
  7854. EXPECT_EQ(get->get_header_value("Content-Length"),
  7855. res->get_header_value("Content-Length"));
  7856. EXPECT_TRUE(res->body.empty());
  7857. }
  7858. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7859. auto port = start(enable);
  7860. Client cli(HOST, port);
  7861. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7862. {"Accept-Encoding", "gzip"}});
  7863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7864. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7865. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7866. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7867. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7868. EXPECT_EQ("cd", res->body);
  7869. }
  7870. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7871. auto port = start(enable);
  7872. Client cli(HOST, port);
  7873. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7875. EXPECT_EQ(StatusCode::OK_200, res->status);
  7876. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7877. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7878. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7879. }
  7880. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7881. auto port = start(enable);
  7882. Client cli(HOST, port);
  7883. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7885. EXPECT_EQ(StatusCode::OK_200, res->status);
  7886. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7887. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7888. EXPECT_TRUE(res->body.empty());
  7889. }
  7890. TEST_F(StaticFileCompressionTest, MinLength) {
  7891. auto port = start(enable);
  7892. Client cli(HOST, port);
  7893. // 104 bytes, well under the default floor. Compressing it would add the
  7894. // gzip header and trailer to a body that already fits in one packet.
  7895. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7897. EXPECT_EQ(StatusCode::OK_200, res->status);
  7898. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7899. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7900. }
  7901. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7902. auto port = start([](Server &svr) {
  7903. svr.set_static_file_compression(true);
  7904. svr.set_static_file_compression_min_length(1);
  7905. });
  7906. Client cli(HOST, port);
  7907. cli.set_decompress(false);
  7908. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7910. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7911. // A 9-byte file comes back larger than it went in, because gzip's header and
  7912. // trailer outweigh anything deflate can save. That is the end of the range
  7913. // the floor exists to keep out.
  7914. EXPECT_GT(res->body.size(), 9U);
  7915. }
  7916. TEST_F(StaticFileCompressionTest, MaxLength) {
  7917. auto port = start([](Server &svr) {
  7918. svr.set_static_file_compression(true);
  7919. svr.set_static_file_compression_min_length(0);
  7920. svr.set_static_file_compression_max_length(1024);
  7921. });
  7922. Client cli(HOST, port);
  7923. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7924. // defines `small` as a macro on Windows.
  7925. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7926. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7927. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7928. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7929. // Under it: compressed.
  7930. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7931. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7932. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7933. }
  7934. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7935. auto port = start(enable_without_floor);
  7936. Client cli(HOST, port);
  7937. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7938. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7939. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7940. auto identity_etag = identity->get_header_value("ETag");
  7941. ASSERT_FALSE(identity_etag.empty());
  7942. auto gzipped =
  7943. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7944. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7945. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7946. auto gzip_etag = gzipped->get_header_value("ETag");
  7947. ASSERT_FALSE(gzip_etag.empty());
  7948. // Two representations, two validators.
  7949. EXPECT_NE(identity_etag, gzip_etag);
  7950. // Each one revalidates against the request that would produce it...
  7951. auto fresh =
  7952. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7953. {"If-None-Match", gzip_etag}});
  7954. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7955. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7956. auto fresh_identity =
  7957. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7958. {"If-None-Match", identity_etag}});
  7959. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7960. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7961. // ...and not against the other representation.
  7962. auto crossed =
  7963. cli.Get("/dir/index.html",
  7964. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7965. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7966. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7967. }
  7968. // The opt-in covers responses the server reads off disk itself. A caller's own
  7969. // known-length provider keeps its Content-Length and, more importantly, keeps
  7970. // delivering incrementally: routing it through a compressor would hold every
  7971. // write back until zlib's window filled.
  7972. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7973. auto port = start(enable);
  7974. Client cli(HOST, port);
  7975. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7977. EXPECT_EQ(StatusCode::OK_200, res->status);
  7978. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7979. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7980. EXPECT_EQ("aaabbb", res->body);
  7981. }
  7982. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7983. auto port = start(enable);
  7984. Client cli(HOST, port);
  7985. cli.set_read_timeout(1, 0);
  7986. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7987. Headers{{"Accept-Encoding", "gzip"}});
  7988. ASSERT_TRUE(handle.is_valid());
  7989. // The provider writes 100 bytes and then stalls for longer than the read
  7990. // timeout. Those first bytes have to arrive anyway: run the response through
  7991. // a compressor and zlib holds them until its window fills, so the read would
  7992. // come back empty instead.
  7993. char buf[256];
  7994. auto n = handle.read(buf, sizeof(buf));
  7995. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7996. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7997. }
  7998. #endif
  7999. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8000. TEST_F(ServerTest, Brotli) {
  8001. Headers headers;
  8002. headers.emplace("Accept-Encoding", "br");
  8003. auto res = cli_.Get("/compress", headers);
  8004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8005. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8006. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8007. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8008. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8009. "7890123456789012345678901234567890",
  8010. res->body);
  8011. EXPECT_EQ(StatusCode::OK_200, res->status);
  8012. }
  8013. #endif
  8014. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8015. TEST_F(ServerTest, Zstd) {
  8016. Headers headers;
  8017. headers.emplace("Accept-Encoding", "zstd");
  8018. auto res = cli_.Get("/compress", headers);
  8019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8020. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8021. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8022. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8023. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8024. "7890123456789012345678901234567890",
  8025. res->body);
  8026. EXPECT_EQ(StatusCode::OK_200, res->status);
  8027. }
  8028. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8029. Headers headers;
  8030. headers.emplace("Accept-Encoding", "");
  8031. auto res = cli_.Get("/compress", headers);
  8032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8033. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8034. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8035. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8036. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8037. "7890123456789012345678901234567890",
  8038. res->body);
  8039. EXPECT_EQ(StatusCode::OK_200, res->status);
  8040. }
  8041. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8042. Headers headers;
  8043. headers.emplace("Accept-Encoding", "zstd");
  8044. std::string body;
  8045. auto res = cli_.Get("/compress", headers,
  8046. [&](const char *data, uint64_t data_length) {
  8047. EXPECT_EQ(100U, data_length);
  8048. body.append(data, data_length);
  8049. return true;
  8050. });
  8051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8052. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8053. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8054. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8055. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8056. "7890123456789012345678901234567890",
  8057. body);
  8058. EXPECT_EQ(StatusCode::OK_200, res->status);
  8059. }
  8060. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8061. Headers headers;
  8062. headers.emplace("Accept-Encoding", "zstd");
  8063. cli_.set_decompress(false);
  8064. auto res = cli_.Get("/compress", headers);
  8065. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8066. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8067. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8068. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8070. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8071. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8072. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8073. EXPECT_EQ(StatusCode::OK_200, res->status);
  8074. ASSERT_EQ(26U, res->body.size());
  8075. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8076. 0);
  8077. }
  8078. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8079. Headers headers;
  8080. headers.emplace("Accept-Encoding", "");
  8081. std::string body;
  8082. auto res = cli_.Get("/compress", headers,
  8083. [&](const char *data, uint64_t data_length) {
  8084. EXPECT_EQ(100U, data_length);
  8085. body.append(data, data_length);
  8086. return true;
  8087. });
  8088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8089. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8090. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8091. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8092. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8093. "7890123456789012345678901234567890",
  8094. body);
  8095. EXPECT_EQ(StatusCode::OK_200, res->status);
  8096. }
  8097. TEST_F(ServerTest, NoZstd) {
  8098. Headers headers;
  8099. headers.emplace("Accept-Encoding", "zstd");
  8100. auto res = cli_.Get("/nocompress", headers);
  8101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8102. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8103. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8104. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8105. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8106. "7890123456789012345678901234567890",
  8107. res->body);
  8108. EXPECT_EQ(StatusCode::OK_200, res->status);
  8109. }
  8110. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8111. Headers headers;
  8112. headers.emplace("Accept-Encoding", "zstd");
  8113. std::string body;
  8114. auto res = cli_.Get("/nocompress", headers,
  8115. [&](const char *data, uint64_t data_length) {
  8116. EXPECT_EQ(100U, data_length);
  8117. body.append(data, data_length);
  8118. return true;
  8119. });
  8120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8121. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8122. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8123. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8124. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8125. "7890123456789012345678901234567890",
  8126. body);
  8127. EXPECT_EQ(StatusCode::OK_200, res->status);
  8128. }
  8129. // TODO: How to enable zstd ??
  8130. TEST_F(ServerTest, MultipartFormDataZstd) {
  8131. UploadFormDataItems items = {
  8132. {"key1", "test", "", ""},
  8133. {"key2", "--abcdefg123", "", ""},
  8134. };
  8135. Headers headers;
  8136. headers.emplace("Accept-Encoding", "zstd");
  8137. cli_.set_compress(true);
  8138. auto res = cli_.Post("/compress-multipart", headers, items);
  8139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8140. EXPECT_EQ(StatusCode::OK_200, res->status);
  8141. }
  8142. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8143. Headers headers;
  8144. headers.emplace("Accept-Encoding", "zstd");
  8145. cli_.set_compress(true);
  8146. auto res = cli_.Put(
  8147. "/put", headers, 3,
  8148. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8149. sink.os << "PUT";
  8150. return true;
  8151. },
  8152. "text/plain");
  8153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8154. EXPECT_EQ(StatusCode::OK_200, res->status);
  8155. EXPECT_EQ("PUT", res->body);
  8156. }
  8157. // Pre-compression logging tests
  8158. TEST_F(ServerTest, PreCompressionLogging) {
  8159. // Test data for compression (matches the actual /compress endpoint content)
  8160. const std::string test_content =
  8161. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8162. "3456789012345678901234567890";
  8163. // Variables to capture logging data
  8164. std::string pre_compression_body;
  8165. std::string pre_compression_content_type;
  8166. std::string pre_compression_content_encoding;
  8167. std::string post_compression_body;
  8168. std::string post_compression_content_type;
  8169. std::string post_compression_content_encoding;
  8170. // Set up pre-compression logger
  8171. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8172. const Response &res) {
  8173. pre_compression_body = res.body;
  8174. pre_compression_content_type = res.get_header_value("Content-Type");
  8175. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8176. });
  8177. // Set up post-compression logger
  8178. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8179. post_compression_body = res.body;
  8180. post_compression_content_type = res.get_header_value("Content-Type");
  8181. post_compression_content_encoding =
  8182. res.get_header_value("Content-Encoding");
  8183. });
  8184. // Test with gzip compression
  8185. Headers headers;
  8186. headers.emplace("Accept-Encoding", "gzip");
  8187. auto res = cli_.Get("/compress", headers);
  8188. // Verify response was compressed
  8189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8190. EXPECT_EQ(StatusCode::OK_200, res->status);
  8191. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8192. // Verify pre-compression logger captured uncompressed content
  8193. EXPECT_EQ(test_content, pre_compression_body);
  8194. EXPECT_EQ("text/plain", pre_compression_content_type);
  8195. EXPECT_TRUE(pre_compression_content_encoding
  8196. .empty()); // No encoding header before compression
  8197. // Verify post-compression logger captured compressed content
  8198. EXPECT_NE(test_content,
  8199. post_compression_body); // Should be different after compression
  8200. EXPECT_EQ("text/plain", post_compression_content_type);
  8201. EXPECT_EQ("gzip", post_compression_content_encoding);
  8202. // Verify compressed content is smaller
  8203. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8204. }
  8205. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8206. const std::string test_content =
  8207. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8208. "3456789012345678901234567890";
  8209. std::string pre_compression_body;
  8210. std::string post_compression_body;
  8211. svr_.set_pre_compression_logger(
  8212. [&](const Request & /*req*/, const Response &res) {
  8213. pre_compression_body = res.body;
  8214. });
  8215. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8216. post_compression_body = res.body;
  8217. });
  8218. Headers headers;
  8219. headers.emplace("Accept-Encoding", "br");
  8220. auto res = cli_.Get("/compress", headers);
  8221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8222. EXPECT_EQ(StatusCode::OK_200, res->status);
  8223. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8224. // Verify pre-compression content is uncompressed
  8225. EXPECT_EQ(test_content, pre_compression_body);
  8226. // Verify post-compression content is compressed
  8227. EXPECT_NE(test_content, post_compression_body);
  8228. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8229. }
  8230. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8231. const std::string test_content =
  8232. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8233. "3456789012345678901234567890";
  8234. std::string pre_compression_body;
  8235. std::string post_compression_body;
  8236. svr_.set_pre_compression_logger(
  8237. [&](const Request & /*req*/, const Response &res) {
  8238. pre_compression_body = res.body;
  8239. });
  8240. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8241. post_compression_body = res.body;
  8242. });
  8243. // Request without compression (use /nocompress endpoint)
  8244. Headers headers;
  8245. auto res = cli_.Get("/nocompress", headers);
  8246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8247. EXPECT_EQ(StatusCode::OK_200, res->status);
  8248. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8249. // Pre-compression logger should not be called when no compression is applied
  8250. EXPECT_TRUE(
  8251. pre_compression_body.empty()); // Pre-compression logger not called
  8252. EXPECT_EQ(
  8253. test_content,
  8254. post_compression_body); // Post-compression logger captures final content
  8255. }
  8256. TEST_F(ServerTest, LoggerSeesContentLength) {
  8257. size_t logged_content_length = 0;
  8258. std::string logged_content_length_header;
  8259. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8260. logged_content_length = res.content_length_;
  8261. logged_content_length_header = res.get_header_value("Content-Length");
  8262. });
  8263. auto res = cli_.Get("/nocompress");
  8264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8265. EXPECT_EQ(StatusCode::OK_200, res->status);
  8266. EXPECT_EQ(res->body.size(), logged_content_length);
  8267. EXPECT_EQ(std::to_string(logged_content_length),
  8268. logged_content_length_header);
  8269. }
  8270. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8271. const std::string test_content =
  8272. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8273. "3456789012345678901234567890";
  8274. std::string pre_compression_body;
  8275. bool pre_logger_called = false;
  8276. // Set only pre-compression logger
  8277. svr_.set_pre_compression_logger(
  8278. [&](const Request & /*req*/, const Response &res) {
  8279. pre_compression_body = res.body;
  8280. pre_logger_called = true;
  8281. });
  8282. Headers headers;
  8283. headers.emplace("Accept-Encoding", "gzip");
  8284. auto res = cli_.Get("/compress", headers);
  8285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8286. EXPECT_EQ(StatusCode::OK_200, res->status);
  8287. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8288. // Verify pre-compression logger was called
  8289. EXPECT_TRUE(pre_logger_called);
  8290. EXPECT_EQ(test_content, pre_compression_body);
  8291. }
  8292. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8293. {
  8294. // Test with Expect: 100-continue header - success case
  8295. // Server returns 100 Continue, client sends body, server returns 200 OK
  8296. Request req;
  8297. req.method = "POST";
  8298. req.path = "/post-large";
  8299. req.set_header("Expect", "100-continue");
  8300. req.body = LARGE_DATA;
  8301. Response res;
  8302. auto error = Error::Success;
  8303. cli_.set_keep_alive(true);
  8304. auto ret = cli_.send(req, res, error);
  8305. EXPECT_TRUE(ret);
  8306. EXPECT_EQ(StatusCode::OK_200, res.status);
  8307. EXPECT_EQ(LARGE_DATA, res.body);
  8308. }
  8309. {
  8310. // Test with Expect: 100-continue header - error case
  8311. // Client should not send the body when server returns an error
  8312. Request req;
  8313. req.method = "POST";
  8314. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8315. req.set_header("Expect", "100-continue");
  8316. req.body = LARGE_DATA;
  8317. Response res;
  8318. auto error = Error::Success;
  8319. auto start = std::chrono::high_resolution_clock::now();
  8320. cli_.set_keep_alive(true);
  8321. auto ret = cli_.send(req, res, error);
  8322. auto end = std::chrono::high_resolution_clock::now();
  8323. auto elapsed =
  8324. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8325. .count();
  8326. // With Expect: 100-continue, request completes successfully but with error
  8327. EXPECT_TRUE(ret);
  8328. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8329. EXPECT_EQ("close", res.get_header_value("Connection"));
  8330. EXPECT_FALSE(cli_.is_socket_open());
  8331. EXPECT_LE(elapsed, 2000);
  8332. }
  8333. {
  8334. // Send an extra GET request to ensure error recovery without hanging
  8335. Request req;
  8336. req.method = "GET";
  8337. req.path = "/hi";
  8338. auto start = std::chrono::high_resolution_clock::now();
  8339. auto res = cli_.send(req);
  8340. auto end = std::chrono::high_resolution_clock::now();
  8341. auto elapsed =
  8342. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8343. .count();
  8344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8345. EXPECT_EQ(StatusCode::OK_200, res->status);
  8346. EXPECT_EQ("Hello World!", res->body);
  8347. EXPECT_LE(elapsed, 500);
  8348. }
  8349. }
  8350. TEST(ZstdDecompressor, ChunkedDecompression) {
  8351. std::string data;
  8352. for (size_t i = 0; i < 32 * 1024; ++i) {
  8353. data.push_back(static_cast<char>('a' + i % 26));
  8354. }
  8355. std::string compressed_data;
  8356. {
  8357. httplib::detail::zstd_compressor compressor;
  8358. bool result = compressor.compress(
  8359. data.data(), data.size(),
  8360. /*last=*/true,
  8361. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8362. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8363. compressed_data_size);
  8364. return true;
  8365. });
  8366. ASSERT_TRUE(result);
  8367. }
  8368. std::string decompressed_data;
  8369. {
  8370. httplib::detail::zstd_decompressor decompressor;
  8371. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8372. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8373. size_t chunk_size = 130;
  8374. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8375. chunk_begin += chunk_size) {
  8376. size_t current_chunk_size =
  8377. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8378. bool result = decompressor.decompress(
  8379. compressed_data.data() + chunk_begin, current_chunk_size,
  8380. [&](const char *decompressed_data_chunk,
  8381. size_t decompressed_data_chunk_size) {
  8382. decompressed_data.insert(decompressed_data.size(),
  8383. decompressed_data_chunk,
  8384. decompressed_data_chunk_size);
  8385. return true;
  8386. });
  8387. ASSERT_TRUE(result);
  8388. }
  8389. }
  8390. ASSERT_EQ(data, decompressed_data);
  8391. }
  8392. TEST(ZstdDecompressor, Decompress) {
  8393. std::string original_text = "Compressed with ZSTD";
  8394. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8395. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8396. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8397. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8398. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8399. std::string decompressed_data;
  8400. {
  8401. httplib::detail::zstd_decompressor decompressor;
  8402. bool result = decompressor.decompress(
  8403. compressed_data.data(), compressed_data.size(),
  8404. [&](const char *decompressed_data_chunk,
  8405. size_t decompressed_data_chunk_size) {
  8406. decompressed_data.insert(decompressed_data.size(),
  8407. decompressed_data_chunk,
  8408. decompressed_data_chunk_size);
  8409. return true;
  8410. });
  8411. ASSERT_TRUE(result);
  8412. }
  8413. ASSERT_EQ(original_text, decompressed_data);
  8414. }
  8415. #endif
  8416. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8417. // separate chunks so that the server sees each part in its own read(). Used to
  8418. // place a read boundary at a specific offset of a request body.
  8419. static bool send_request_in_parts(time_t read_timeout_sec,
  8420. const std::vector<std::string> &parts,
  8421. std::string *resp = nullptr,
  8422. int port = PORT) {
  8423. auto error = Error::Success;
  8424. auto client_sock = detail::create_client_socket(
  8425. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8426. /*connection_timeout_sec=*/5, 0,
  8427. /*read_timeout_sec=*/5, 0,
  8428. /*write_timeout_sec=*/5, 0, std::string(), error);
  8429. if (client_sock == INVALID_SOCKET) { return false; }
  8430. auto ret = detail::process_client_socket(
  8431. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8432. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8433. for (size_t i = 0; i < parts.size(); i++) {
  8434. const auto &part = parts[i];
  8435. if (part.size() !=
  8436. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8437. return false;
  8438. }
  8439. if (i + 1 < parts.size()) {
  8440. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8441. }
  8442. }
  8443. char buf[512];
  8444. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8445. while (line_reader.getline()) {
  8446. if (resp) { *resp += line_reader.ptr(); }
  8447. }
  8448. return true;
  8449. });
  8450. detail::close_socket(client_sock);
  8451. return ret;
  8452. }
  8453. // Sends a raw request to a server listening at HOST:PORT.
  8454. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8455. std::string *resp = nullptr, int port = PORT) {
  8456. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8457. }
  8458. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8459. Server svr;
  8460. std::string header_value;
  8461. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8462. header_value = req.get_header_value("foo");
  8463. res.set_content("ok", "text/plain");
  8464. });
  8465. thread t = thread([&] { svr.listen(HOST, PORT); });
  8466. auto se = detail::scope_exit([&] {
  8467. svr.stop();
  8468. t.join();
  8469. ASSERT_FALSE(svr.is_running());
  8470. });
  8471. svr.wait_until_ready();
  8472. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8473. // like characters are not treated the same - use vertical tab and escape.
  8474. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8475. "foo: \t \v bar \x1B\t \r\n"
  8476. "Connection: close\r\n"
  8477. "\r\n";
  8478. std::string res;
  8479. ASSERT_TRUE(send_request(5, req, &res));
  8480. EXPECT_EQ(header_value, "");
  8481. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8482. }
  8483. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8484. Server svr;
  8485. std::string received;
  8486. svr.Get("/order", [&](const Request &req, Response &res) {
  8487. received = entries_to_string(req.headers);
  8488. res.set_content("ok", "text/plain");
  8489. });
  8490. auto port = svr.bind_to_any_port(HOST);
  8491. thread t = thread([&] { svr.listen_after_bind(); });
  8492. auto se = detail::scope_exit([&] {
  8493. svr.stop();
  8494. t.join();
  8495. ASSERT_FALSE(svr.is_running());
  8496. });
  8497. svr.wait_until_ready();
  8498. const std::string req = "GET /order HTTP/1.1\r\n"
  8499. "X-First: 1\r\n"
  8500. "X-Dup: a\r\n"
  8501. "X-Second: 2\r\n"
  8502. "X-Dup: b\r\n"
  8503. "Connection: close\r\n"
  8504. "\r\n";
  8505. std::string res;
  8506. ASSERT_TRUE(send_request(5, req, &res, port));
  8507. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8508. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8509. }
  8510. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8511. Server svr;
  8512. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8513. res.set_header("Set-Cookie", "first=1");
  8514. res.set_header("X-Between", "y");
  8515. res.set_header("Set-Cookie", "second=2");
  8516. res.set_content("ok", "text/plain");
  8517. });
  8518. auto port = svr.bind_to_any_port(HOST);
  8519. thread t = thread([&] { svr.listen_after_bind(); });
  8520. auto se = detail::scope_exit([&] {
  8521. svr.stop();
  8522. t.join();
  8523. ASSERT_FALSE(svr.is_running());
  8524. });
  8525. svr.wait_until_ready();
  8526. Client cli(HOST, port);
  8527. auto res = cli.Get("/cookies");
  8528. ASSERT_TRUE(res);
  8529. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8530. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8531. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8532. }
  8533. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8534. Server svr;
  8535. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8536. auto i = new int(0);
  8537. res.set_header("Trailer", "X-Safe, X-Reflected");
  8538. res.set_chunked_content_provider(
  8539. "text/plain",
  8540. [i](size_t /*offset*/, DataSink &sink) {
  8541. if (*i == 0) {
  8542. sink.os << "body";
  8543. } else {
  8544. Headers trailer;
  8545. // A valid trailer that must survive.
  8546. trailer.emplace("X-Safe", "safe");
  8547. // Attacker-controlled value carrying CR/LF (response splitting).
  8548. trailer.emplace("X-Reflected",
  8549. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8550. // Attacker-controlled name carrying CR/LF.
  8551. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8552. sink.done_with_trailer(trailer);
  8553. }
  8554. (*i)++;
  8555. return true;
  8556. },
  8557. [i](bool /*success*/) { delete i; });
  8558. });
  8559. thread t = thread([&] { svr.listen(HOST, PORT); });
  8560. auto se = detail::scope_exit([&] {
  8561. svr.stop();
  8562. t.join();
  8563. ASSERT_FALSE(svr.is_running());
  8564. });
  8565. svr.wait_until_ready();
  8566. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8567. "Host: " + HOST +
  8568. "\r\n"
  8569. "Connection: close\r\n"
  8570. "\r\n";
  8571. std::string res;
  8572. ASSERT_TRUE(send_request(5, req, &res));
  8573. // The injected fields must not appear anywhere in the raw response.
  8574. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8575. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8576. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8577. // Invalid trailers are dropped entirely, matching set_header().
  8578. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8579. // The valid trailer still passes through.
  8580. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8581. }
  8582. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8583. Server svr;
  8584. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8585. // res.headers is a public field an application can populate directly,
  8586. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8587. // A valid header that must survive.
  8588. res.headers.emplace("X-Safe", "safe");
  8589. // Attacker-controlled value carrying CR/LF (response splitting).
  8590. res.headers.emplace("X-Reflected",
  8591. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8592. // Attacker-controlled name carrying CR/LF.
  8593. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8594. res.set_content("body", "text/plain");
  8595. });
  8596. thread t = thread([&] { svr.listen(HOST, PORT); });
  8597. auto se = detail::scope_exit([&] {
  8598. svr.stop();
  8599. t.join();
  8600. ASSERT_FALSE(svr.is_running());
  8601. });
  8602. svr.wait_until_ready();
  8603. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8604. "Host: " + HOST +
  8605. "\r\n"
  8606. "Connection: close\r\n"
  8607. "\r\n";
  8608. std::string res;
  8609. ASSERT_TRUE(send_request(5, req, &res));
  8610. // The injected fields must not appear anywhere in the raw response.
  8611. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8612. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8613. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8614. // Invalid headers are dropped entirely, matching set_header().
  8615. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8616. // The valid header still passes through.
  8617. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8618. }
  8619. // Forward declaration: in split builds split.py strips `inline` and moves the
  8620. // definition into httplib.cc, so detail::write_request_line is not visible from
  8621. // the public httplib.h. Re-declaring it here lets the tests link against the
  8622. // symbol in both header-only and split builds.
  8623. namespace httplib {
  8624. namespace detail {
  8625. ssize_t write_request_line(Stream &strm, const std::string &method,
  8626. const std::string &path);
  8627. } // namespace detail
  8628. } // namespace httplib
  8629. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8630. // A well-formed target is written verbatim.
  8631. {
  8632. detail::BufferStream strm;
  8633. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8634. EXPECT_GT(n, 0);
  8635. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8636. }
  8637. // A target carrying CR/LF, SP or other control octets must be rejected
  8638. // before anything reaches the wire, otherwise it splits the request line and
  8639. // injects a header or a whole request.
  8640. const std::string evil_targets[] = {
  8641. "/a\r\nInjected: pwned",
  8642. "/a\rInjected",
  8643. "/a\nInjected",
  8644. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8645. "/a b",
  8646. "/a\tb",
  8647. "/a\x7f",
  8648. };
  8649. for (const auto &evil : evil_targets) {
  8650. detail::BufferStream strm;
  8651. auto n = detail::write_request_line(strm, "GET", evil);
  8652. EXPECT_LT(n, 0);
  8653. EXPECT_TRUE(strm.get_buffer().empty());
  8654. }
  8655. }
  8656. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8657. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8658. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8659. // target reaches write_request. The client must fail cleanly with
  8660. // Error::Write instead of putting a request-line-less, header-injecting
  8661. // request on the wire.
  8662. Server svr;
  8663. svr.Get("/a", [](const Request &, Response &res) {
  8664. res.set_content("ok", "text/plain");
  8665. });
  8666. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8667. auto se = detail::scope_exit([&] {
  8668. svr.stop();
  8669. thread.join();
  8670. ASSERT_FALSE(svr.is_running());
  8671. });
  8672. svr.wait_until_ready();
  8673. {
  8674. Client cli(HOST, PORT);
  8675. cli.set_path_encode(false);
  8676. // The request is rejected before anything is written, so the connection
  8677. // stays silent and the subsequent response read would otherwise block for
  8678. // the full default read timeout. Shorten it -- the assertion is on the
  8679. // error, not the timeout.
  8680. cli.set_read_timeout(1, 0);
  8681. auto res = cli.Get("/a\r\nInjected: pwned");
  8682. EXPECT_FALSE(res);
  8683. EXPECT_EQ(Error::Write, res.error());
  8684. }
  8685. }
  8686. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8687. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8688. // including extension methods.
  8689. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8690. for (const auto &method : good_methods) {
  8691. detail::BufferStream strm;
  8692. auto n = detail::write_request_line(strm, method, "/");
  8693. EXPECT_GT(n, 0);
  8694. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8695. }
  8696. // A method carrying CR/LF would split the request line and smuggle a whole
  8697. // request ahead of the real one. A space or an empty method corrupts the
  8698. // request line. All must be rejected before anything reaches the wire.
  8699. const std::string evil_methods[] = {
  8700. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8701. "GET\r\nInjected: pwned",
  8702. "GET\r",
  8703. "GET\n",
  8704. "GE T",
  8705. "",
  8706. };
  8707. for (const auto &evil : evil_methods) {
  8708. detail::BufferStream strm;
  8709. auto n = detail::write_request_line(strm, evil, "/");
  8710. EXPECT_LT(n, 0);
  8711. EXPECT_TRUE(strm.get_buffer().empty());
  8712. }
  8713. }
  8714. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8715. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8716. // through Client::send must fail with Error::Write and no request, neither
  8717. // the smuggled one nor the real one, may reach the server.
  8718. Server svr;
  8719. std::atomic<int> request_count(0);
  8720. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8721. request_count++;
  8722. res.status = StatusCode::OK_200;
  8723. return Server::HandlerResponse::Handled;
  8724. });
  8725. auto port = svr.bind_to_any_port(HOST);
  8726. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8727. auto se = detail::scope_exit([&] {
  8728. svr.stop();
  8729. thread.join();
  8730. ASSERT_FALSE(svr.is_running());
  8731. });
  8732. svr.wait_until_ready();
  8733. {
  8734. Client cli(HOST, port);
  8735. const std::string evil_methods[] = {
  8736. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8737. "GE T",
  8738. "",
  8739. };
  8740. for (const auto &evil : evil_methods) {
  8741. Request req;
  8742. req.method = evil;
  8743. req.path = "/";
  8744. auto res = cli.send(req);
  8745. EXPECT_FALSE(res);
  8746. EXPECT_EQ(Error::Write, res.error());
  8747. }
  8748. auto handle =
  8749. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8750. EXPECT_FALSE(handle.is_valid());
  8751. EXPECT_EQ(Error::Write, handle.error);
  8752. // A valid request on the same client still goes through.
  8753. auto res = cli.Get("/");
  8754. ASSERT_TRUE(res);
  8755. EXPECT_EQ(StatusCode::OK_200, res->status);
  8756. }
  8757. EXPECT_EQ(1, request_count.load());
  8758. }
  8759. // Sends a raw request and verifies that there isn't a crash or exception.
  8760. static void test_raw_request(const std::string &req,
  8761. std::string *out = nullptr) {
  8762. Server svr;
  8763. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8764. res.set_content("ok", "text/plain");
  8765. });
  8766. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8767. res.set_content("ok", "text/plain");
  8768. });
  8769. svr.Get("/header_field_value_check",
  8770. [&](const Request & /*req*/, Response &res) {
  8771. res.set_content("ok", "text/plain");
  8772. });
  8773. svr.CustomRoute("PROPFIND", "/dav",
  8774. [&](const Request & /*req*/, Response &res) {
  8775. res.status = StatusCode::MultiStatus_207;
  8776. });
  8777. // Server read timeout must be longer than the client read timeout for the
  8778. // bug to reproduce, probably to force the server to process a request
  8779. // without a trailing blank line.
  8780. const time_t client_read_timeout_sec = 1;
  8781. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8782. bool listen_thread_ok = false;
  8783. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8784. auto se = detail::scope_exit([&] {
  8785. svr.stop();
  8786. t.join();
  8787. ASSERT_FALSE(svr.is_running());
  8788. EXPECT_TRUE(listen_thread_ok);
  8789. });
  8790. svr.wait_until_ready();
  8791. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8792. }
  8793. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8794. // A certain header line causes an exception if the header property is parsed
  8795. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8796. test_raw_request(
  8797. "GET /hi HTTP/1.1\r\n"
  8798. " : "
  8799. " "
  8800. " ");
  8801. }
  8802. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8803. // A certain header line causes an exception if the header property *name* is
  8804. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8805. // greedy matcher and requires backtracking when there are a lot of ":"
  8806. // characters.
  8807. // This occurs with libc++ but not libstdc++.
  8808. test_raw_request(
  8809. "GET /hi HTTP/1.1\r\n"
  8810. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8811. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8812. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8813. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8814. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8815. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8816. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8817. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8818. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8819. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8820. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8821. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8822. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8823. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8824. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8825. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8826. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8827. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8828. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8829. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8830. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8831. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8832. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8833. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8834. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8835. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8836. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8837. "&&&%%%");
  8838. }
  8839. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8840. // Make sure this doesn't crash the server.
  8841. // In a previous version of the header line regex, the "\r" rendered the line
  8842. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8843. // a new position where the leading white space ended and the field value
  8844. // began.
  8845. // The crash occurs with libc++ but not libstdc++.
  8846. test_raw_request("GET /hi HTTP/1.1\r\n"
  8847. "a:" +
  8848. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8849. "\r\n"
  8850. "\r\n");
  8851. }
  8852. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8853. std::string out;
  8854. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8855. "Content-Type: text/plain\r\n"
  8856. "Transfer-Encoding: chunked\r\n"
  8857. "\r\n"
  8858. "nothex\r\n",
  8859. &out);
  8860. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8861. }
  8862. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8863. std::string out;
  8864. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8865. "Content-Type: text/plain\r\n"
  8866. "Transfer-Encoding: chunked\r\n"
  8867. "\r\n"
  8868. "3\r\n"
  8869. "xyz\r\n"
  8870. "NaN\r\n",
  8871. &out);
  8872. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8873. }
  8874. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8875. std::string out;
  8876. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8877. "Content-Type: text/plain\r\n"
  8878. "Transfer-Encoding: chunked\r\n"
  8879. "\r\n"
  8880. // Length is too large for 64 bits.
  8881. "1ffffffffffffffff\r\n"
  8882. "xyz\r\n",
  8883. &out);
  8884. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8885. }
  8886. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8887. test_raw_request("GET /hi HTTP/1.1\r\n"
  8888. "Content-Type: text/plain\r\n\r");
  8889. }
  8890. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8891. std::string out;
  8892. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8893. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8894. }
  8895. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8896. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8897. std::string out;
  8898. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8899. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8900. }
  8901. }
  8902. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8903. std::string out;
  8904. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8905. "Connection: close\r\n\r\n",
  8906. &out);
  8907. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8908. }
  8909. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8910. Server svr;
  8911. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8912. EXPECT_TRUE(!req.remote_addr.empty());
  8913. });
  8914. thread t = thread([&] { svr.listen(HOST, PORT); });
  8915. auto se = detail::scope_exit([&] {
  8916. svr.stop();
  8917. t.join();
  8918. ASSERT_FALSE(svr.is_running());
  8919. });
  8920. svr.wait_until_ready();
  8921. // Send an invalid request line to trigger Bad Request
  8922. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8923. std::string out;
  8924. ASSERT_TRUE(send_request(5, bad_req, &out));
  8925. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8926. }
  8927. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8928. // answered right away rather than blocking on a read that waits for EOF.
  8929. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8930. std::string out;
  8931. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8932. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8933. }
  8934. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8935. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8936. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8937. for (const auto *method : methods) {
  8938. Server svr;
  8939. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8940. EXPECT_FALSE(svr.is_valid()) << method;
  8941. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8942. }
  8943. }
  8944. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8945. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8946. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8947. for (const auto *method : methods) {
  8948. Server svr;
  8949. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8950. EXPECT_FALSE(svr.is_valid()) << method;
  8951. }
  8952. }
  8953. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8954. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8955. "COPY", "MOVE", "LOCK",
  8956. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8957. Server svr;
  8958. for (const auto *method : methods) {
  8959. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8960. }
  8961. EXPECT_TRUE(svr.is_valid());
  8962. }
  8963. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8964. Server svr;
  8965. svr.CustomRoute("POST", "/x",
  8966. [](const Request &, Response &, const ContentReader &) {});
  8967. EXPECT_FALSE(svr.is_valid());
  8968. }
  8969. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8970. Server svr;
  8971. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8972. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8973. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8974. EXPECT_FALSE(svr.is_valid());
  8975. }
  8976. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8977. Server svr;
  8978. auto captured = Error::Success;
  8979. svr.set_error_logger(
  8980. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8981. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8982. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8983. }
  8984. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8985. std::string out;
  8986. std::string request(
  8987. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8988. test_raw_request(request, &out);
  8989. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8990. }
  8991. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8992. std::string out;
  8993. std::string request(
  8994. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8995. test_raw_request(request, &out);
  8996. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8997. }
  8998. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8999. std::string out;
  9000. std::string request(
  9001. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9002. test_raw_request(request, &out);
  9003. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9004. }
  9005. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9006. std::string out;
  9007. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9008. "Test: \r\n\r\n",
  9009. &out);
  9010. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9011. }
  9012. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9013. Server svr;
  9014. std::string x_custom;
  9015. std::string cookie;
  9016. std::string xff;
  9017. std::string x_unicode;
  9018. std::string x_iis;
  9019. svr.Get("/check", [&](const Request &req, Response &res) {
  9020. x_custom = req.get_header_value("X-Custom");
  9021. cookie = req.get_header_value("Cookie");
  9022. xff = req.get_header_value("X-Forwarded-For");
  9023. x_unicode = req.get_header_value("X-Unicode");
  9024. x_iis = req.get_header_value("X-IIS");
  9025. res.set_content("ok", "text/plain");
  9026. });
  9027. thread t = thread([&] { svr.listen(HOST, PORT); });
  9028. auto se = detail::scope_exit([&] {
  9029. svr.stop();
  9030. t.join();
  9031. ASSERT_FALSE(svr.is_running());
  9032. });
  9033. svr.wait_until_ready();
  9034. const std::string req = "GET /check HTTP/1.1\r\n"
  9035. "Host: localhost\r\n"
  9036. "X-Custom: a%0D%0AInjected: b\r\n"
  9037. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9038. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9039. "X-Unicode: %E3%81%82\r\n"
  9040. "X-IIS: %u00E9\r\n"
  9041. "Connection: close\r\n"
  9042. "\r\n";
  9043. std::string res;
  9044. ASSERT_TRUE(send_request(5, req, &res));
  9045. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9046. // Every value must be returned verbatim (wire form), with no decoding.
  9047. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9048. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9049. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9050. EXPECT_EQ("%E3%81%82", x_unicode);
  9051. EXPECT_EQ("%u00E9", x_iis);
  9052. }
  9053. // Applications that previously relied on automatic percent-decoding can
  9054. // reproduce the old behavior by explicitly calling decode_path_component()
  9055. // or, for RFC 3986 conformance, decode_uri_component().
  9056. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9057. Server svr;
  9058. std::string decoded;
  9059. svr.Get("/check", [&](const Request &req, Response &res) {
  9060. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9061. res.set_content("ok", "text/plain");
  9062. });
  9063. thread t = thread([&] { svr.listen(HOST, PORT); });
  9064. auto se = detail::scope_exit([&] {
  9065. svr.stop();
  9066. t.join();
  9067. ASSERT_FALSE(svr.is_running());
  9068. });
  9069. svr.wait_until_ready();
  9070. const std::string req = "GET /check HTTP/1.1\r\n"
  9071. "Host: localhost\r\n"
  9072. "X-Custom: hello%20world\r\n"
  9073. "Connection: close\r\n"
  9074. "\r\n";
  9075. std::string res;
  9076. ASSERT_TRUE(send_request(5, req, &res));
  9077. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9078. EXPECT_EQ("hello world", decoded);
  9079. }
  9080. // Regression test for #2033. Browsers send Referer values that include
  9081. // percent-encoded characters such as %0A inside the URL. Decoding the
  9082. // header value would either trip the post-decode CR/LF/NUL guard (the
  9083. // original bug, returning 400) or, after that guard was relaxed, silently
  9084. // store a literal LF — both unacceptable. The wire form must round-trip.
  9085. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9086. Server svr;
  9087. std::string referer;
  9088. svr.Get("/check", [&](const Request &req, Response &res) {
  9089. referer = req.get_header_value("Referer");
  9090. res.set_content("ok", "text/plain");
  9091. });
  9092. thread t = thread([&] { svr.listen(HOST, PORT); });
  9093. auto se = detail::scope_exit([&] {
  9094. svr.stop();
  9095. t.join();
  9096. ASSERT_FALSE(svr.is_running());
  9097. });
  9098. svr.wait_until_ready();
  9099. const std::string req = "GET /check HTTP/1.1\r\n"
  9100. "Host: localhost\r\n"
  9101. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9102. "Connection: close\r\n"
  9103. "\r\n";
  9104. std::string res;
  9105. ASSERT_TRUE(send_request(5, req, &res));
  9106. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9107. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9108. }
  9109. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9110. Server svr;
  9111. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9112. res.set_header("Cache-Control", "no-cache");
  9113. res.set_chunked_content_provider(
  9114. "text/event-stream", [](size_t offset, DataSink &sink) {
  9115. std::string s = "data:";
  9116. s += std::to_string(offset);
  9117. s += "\n\n";
  9118. auto ret = sink.write(s.data(), s.size());
  9119. EXPECT_TRUE(ret);
  9120. std::this_thread::sleep_for(std::chrono::seconds(1));
  9121. return true;
  9122. });
  9123. });
  9124. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9125. svr.wait_until_ready();
  9126. Client client(HOST, PORT);
  9127. const Headers headers = {{"Accept", "text/event-stream"}};
  9128. auto get_thread = std::thread([&client, &headers]() {
  9129. auto res = client.Get(
  9130. "/events", headers,
  9131. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9132. });
  9133. auto se = detail::scope_exit([&] {
  9134. svr.stop();
  9135. get_thread.join();
  9136. listen_thread.join();
  9137. ASSERT_FALSE(svr.is_running());
  9138. });
  9139. // Give GET time to get a few messages.
  9140. std::this_thread::sleep_for(std::chrono::seconds(2));
  9141. }
  9142. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9143. httplib::Server svr;
  9144. svr.Post("/hi",
  9145. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9146. res.status = StatusCode::OK_200;
  9147. });
  9148. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9149. svr.wait_until_ready();
  9150. Client cli(HOST, PORT);
  9151. auto res = cli.Post("/hi", "data", "text/plain");
  9152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9153. EXPECT_EQ(StatusCode::OK_200, res->status);
  9154. svr.stop();
  9155. thread.join();
  9156. ASSERT_FALSE(svr.is_running());
  9157. res = cli.Post("/hi", "data", "text/plain");
  9158. ASSERT_FALSE(res);
  9159. }
  9160. TEST(ServerStopTest, ListenFailure) {
  9161. Server svr;
  9162. auto t = thread([&]() {
  9163. auto ret = svr.listen("????", PORT);
  9164. EXPECT_FALSE(ret);
  9165. });
  9166. svr.wait_until_ready();
  9167. svr.stop();
  9168. t.join();
  9169. }
  9170. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9171. TEST(ServerStopTest, Decommision) {
  9172. Server svr;
  9173. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9174. for (int i = 0; i < 4; i++) {
  9175. auto is_even = !(i % 2);
  9176. std::thread t{[&] {
  9177. try {
  9178. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9179. if (is_even) {
  9180. throw std::runtime_error("Some thing that happens to go wrong.");
  9181. }
  9182. svr.listen(HOST, PORT);
  9183. } catch (...) { svr.decommission(); }
  9184. }};
  9185. svr.wait_until_ready();
  9186. // Server is up
  9187. {
  9188. Client cli(HOST, PORT);
  9189. auto res = cli.Get("/hi");
  9190. if (is_even) {
  9191. EXPECT_FALSE(res);
  9192. } else {
  9193. EXPECT_TRUE(res);
  9194. EXPECT_EQ("hi...", res->body);
  9195. }
  9196. }
  9197. svr.stop();
  9198. t.join();
  9199. // Server is down...
  9200. {
  9201. Client cli(HOST, PORT);
  9202. auto res = cli.Get("/hi");
  9203. EXPECT_FALSE(res);
  9204. }
  9205. }
  9206. }
  9207. #endif
  9208. // Helper function for string body upload progress tests
  9209. template <typename SetupHandler, typename ClientCall>
  9210. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9211. ClientCall &&client_call,
  9212. const string &body) {
  9213. Server svr;
  9214. setup_handler(svr);
  9215. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9216. auto se = detail::scope_exit([&] {
  9217. svr.stop();
  9218. t.join();
  9219. });
  9220. svr.wait_until_ready();
  9221. Client cli(HOST, PORT);
  9222. vector<uint64_t> progress_values;
  9223. bool progress_called = false;
  9224. auto res =
  9225. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9226. progress_values.push_back(current);
  9227. progress_called = true;
  9228. return true;
  9229. });
  9230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9231. EXPECT_EQ(200, res->status);
  9232. EXPECT_TRUE(progress_called);
  9233. }
  9234. TEST(UploadProgressTest, PostStringBodyBasic) {
  9235. TestStringBodyUploadProgress(
  9236. [](Server &svr) {
  9237. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9238. res.set_content("received", "text/plain");
  9239. });
  9240. },
  9241. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9242. return cli.Post("/test", body, "text/plain", progress_callback);
  9243. },
  9244. "test data for upload progress");
  9245. }
  9246. TEST(UploadProgressTest, PutStringBodyBasic) {
  9247. TestStringBodyUploadProgress(
  9248. [](Server &svr) {
  9249. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9250. res.set_content("put received", "text/plain");
  9251. });
  9252. },
  9253. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9254. return cli.Put("/test", body, "text/plain", progress_callback);
  9255. },
  9256. "put test data for upload progress");
  9257. }
  9258. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9259. TestStringBodyUploadProgress(
  9260. [](Server &svr) {
  9261. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9262. res.set_content("patch received", "text/plain");
  9263. });
  9264. },
  9265. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9266. return cli.Patch("/test", body, "text/plain", progress_callback);
  9267. },
  9268. "patch test data for upload progress");
  9269. }
  9270. // Helper function for content provider upload progress tests
  9271. template <typename SetupHandler, typename ClientCall>
  9272. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9273. ClientCall &&client_call) {
  9274. Server svr;
  9275. setup_handler(svr);
  9276. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9277. auto se = detail::scope_exit([&] {
  9278. svr.stop();
  9279. t.join();
  9280. });
  9281. svr.wait_until_ready();
  9282. Client cli(HOST, PORT);
  9283. vector<uint64_t> progress_values;
  9284. auto res =
  9285. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9286. progress_values.push_back(current);
  9287. return true;
  9288. });
  9289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9290. EXPECT_EQ(200, res->status);
  9291. EXPECT_FALSE(progress_values.empty());
  9292. }
  9293. TEST(UploadProgressTest, PostContentProviderProgress) {
  9294. TestContentProviderUploadProgress(
  9295. [](Server &svr) {
  9296. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9297. res.set_content("provider received", "text/plain");
  9298. });
  9299. },
  9300. [](Client &cli, UploadProgress progress_callback) {
  9301. return cli.Post(
  9302. "/test", 10,
  9303. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9304. sink.os << "test data";
  9305. return true;
  9306. },
  9307. "text/plain", progress_callback);
  9308. });
  9309. }
  9310. // Helper function for multipart upload progress tests
  9311. template <typename SetupHandler, typename ClientCall>
  9312. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9313. ClientCall &&client_call,
  9314. const string &endpoint) {
  9315. Server svr;
  9316. setup_handler(svr);
  9317. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9318. auto se = detail::scope_exit([&] {
  9319. svr.stop();
  9320. t.join();
  9321. });
  9322. svr.wait_until_ready();
  9323. Client cli(HOST, PORT);
  9324. vector<uint64_t> progress_values;
  9325. UploadFormDataItems items = {
  9326. {"field1", "value1", "", ""},
  9327. {"field2", "longer value for progress tracking test", "", ""},
  9328. {"file1", "file content data for upload progress", "test.txt",
  9329. "text/plain"}};
  9330. auto res = client_call(cli, endpoint, items,
  9331. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9332. progress_values.push_back(current);
  9333. return true;
  9334. });
  9335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9336. EXPECT_EQ(200, res->status);
  9337. EXPECT_FALSE(progress_values.empty());
  9338. }
  9339. TEST(UploadProgressTest, PostMultipartProgress) {
  9340. TestMultipartUploadProgress(
  9341. [](Server &svr) {
  9342. svr.Post("/multipart", [](const Request &req, Response &res) {
  9343. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9344. res.set_content("multipart received", "text/plain");
  9345. });
  9346. },
  9347. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9348. UploadProgress progress_callback) {
  9349. return cli.Post(endpoint, items, progress_callback);
  9350. },
  9351. "/multipart");
  9352. }
  9353. // Helper function for basic download progress tests
  9354. template <typename SetupHandler, typename ClientCall>
  9355. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9356. ClientCall &&client_call, const string &endpoint,
  9357. size_t expected_content_size) {
  9358. Server svr;
  9359. setup_handler(svr);
  9360. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9361. auto se = detail::scope_exit([&] {
  9362. svr.stop();
  9363. t.join();
  9364. });
  9365. svr.wait_until_ready();
  9366. Client cli(HOST, PORT);
  9367. vector<uint64_t> progress_values;
  9368. auto res = client_call(cli, endpoint,
  9369. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9370. progress_values.push_back(current);
  9371. return true;
  9372. });
  9373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9374. EXPECT_EQ(200, res->status);
  9375. EXPECT_FALSE(progress_values.empty());
  9376. EXPECT_EQ(expected_content_size, res->body.size());
  9377. }
  9378. TEST(DownloadProgressTest, GetBasic) {
  9379. TestBasicDownloadProgress(
  9380. [](Server &svr) {
  9381. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9382. string content(1000, 'D');
  9383. res.set_content(content, "text/plain");
  9384. });
  9385. },
  9386. [](Client &cli, const string &endpoint,
  9387. DownloadProgress progress_callback) {
  9388. return cli.Get(endpoint, progress_callback);
  9389. },
  9390. "/download", 1000u);
  9391. }
  9392. // Helper function for content receiver download progress tests
  9393. template <typename SetupHandler, typename ClientCall>
  9394. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9395. ClientCall &&client_call,
  9396. const string &endpoint,
  9397. size_t expected_content_size) {
  9398. Server svr;
  9399. setup_handler(svr);
  9400. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9401. auto se = detail::scope_exit([&] {
  9402. svr.stop();
  9403. t.join();
  9404. });
  9405. svr.wait_until_ready();
  9406. Client cli(HOST, PORT);
  9407. vector<uint64_t> progress_values;
  9408. string received_body;
  9409. auto res = client_call(
  9410. cli, endpoint,
  9411. [&](const char *data, size_t data_length) -> bool {
  9412. received_body.append(data, data_length);
  9413. return true;
  9414. },
  9415. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9416. progress_values.push_back(current);
  9417. return true;
  9418. });
  9419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9420. EXPECT_EQ(200, res->status);
  9421. EXPECT_FALSE(progress_values.empty());
  9422. EXPECT_EQ(expected_content_size, received_body.size());
  9423. EXPECT_TRUE(res->body.empty());
  9424. }
  9425. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9426. TestContentReceiverDownloadProgress(
  9427. [](Server &svr) {
  9428. svr.Get("/download-receiver",
  9429. [](const Request & /*req*/, Response &res) {
  9430. string content(2000, 'R');
  9431. res.set_content(content, "text/plain");
  9432. });
  9433. },
  9434. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9435. DownloadProgress progress_callback) {
  9436. return cli.Get(endpoint, content_receiver, progress_callback);
  9437. },
  9438. "/download-receiver", 2000u);
  9439. }
  9440. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9441. // A provider reaching a pass with nothing to hand over - an empty buffer
  9442. // popped off a queue, say - must not be taken to mean the body is finished.
  9443. // It used to end the loop with the terminating chunk unwritten while the
  9444. // server still considered the response complete, so the peer waited for an
  9445. // end that never arrived.
  9446. Server svr;
  9447. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9448. auto step = std::make_shared<int>(0);
  9449. res.set_chunked_content_provider("text/plain",
  9450. [step](size_t /*offset*/, DataSink &sink) {
  9451. switch ((*step)++) {
  9452. case 0: sink.write("", 0); break;
  9453. case 1: sink.write("hello", 5); break;
  9454. default: sink.done(); break;
  9455. }
  9456. return true;
  9457. });
  9458. });
  9459. auto port = svr.bind_to_any_port(HOST);
  9460. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9461. auto listen_se = detail::scope_exit([&] {
  9462. svr.stop();
  9463. listen_thread.join();
  9464. ASSERT_FALSE(svr.is_running());
  9465. });
  9466. svr.wait_until_ready();
  9467. Client cli(HOST, port);
  9468. // Without the fix the body is never terminated, so bound the wait rather
  9469. // than letting the test hang on the default read timeout.
  9470. cli.set_read_timeout(5, 0);
  9471. auto res = cli.Get("/stream");
  9472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9473. EXPECT_EQ(StatusCode::OK_200, res->status);
  9474. EXPECT_EQ("hello", res->body);
  9475. }
  9476. TEST(StreamingTest, NoContentLengthStreaming) {
  9477. Server svr;
  9478. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9479. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9480. if (offset < 6) {
  9481. sink.os << (offset < 3 ? "a" : "b");
  9482. } else {
  9483. sink.done();
  9484. }
  9485. return true;
  9486. });
  9487. });
  9488. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9489. auto listen_se = detail::scope_exit([&] {
  9490. svr.stop();
  9491. listen_thread.join();
  9492. ASSERT_FALSE(svr.is_running());
  9493. });
  9494. svr.wait_until_ready();
  9495. Client client(HOST, PORT);
  9496. auto get_thread = std::thread([&client]() {
  9497. std::string s;
  9498. auto res =
  9499. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9500. s += std::string(data, len);
  9501. return true;
  9502. });
  9503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9504. EXPECT_EQ(StatusCode::OK_200, res->status);
  9505. EXPECT_EQ("aaabbb", s);
  9506. });
  9507. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9508. // Give GET time to get a few messages.
  9509. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9510. }
  9511. TEST(MountTest, Unmount) {
  9512. Server svr;
  9513. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9514. auto se = detail::scope_exit([&] {
  9515. svr.stop();
  9516. listen_thread.join();
  9517. ASSERT_FALSE(svr.is_running());
  9518. });
  9519. svr.wait_until_ready();
  9520. Client cli("localhost", PORT);
  9521. svr.set_mount_point("/mount2", "./www2");
  9522. auto res = cli.Get("/");
  9523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9525. res = cli.Get("/mount2/dir/test.html");
  9526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9527. EXPECT_EQ(StatusCode::OK_200, res->status);
  9528. svr.set_mount_point("/", "./www");
  9529. res = cli.Get("/dir/");
  9530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9531. EXPECT_EQ(StatusCode::OK_200, res->status);
  9532. svr.remove_mount_point("/");
  9533. res = cli.Get("/dir/");
  9534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9535. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9536. svr.remove_mount_point("/mount2");
  9537. res = cli.Get("/mount2/dir/test.html");
  9538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9539. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9540. }
  9541. TEST(MountTest, PathSegmentBoundary) {
  9542. Server svr;
  9543. svr.set_mount_point("/mount2", "./www2");
  9544. svr.set_mount_point("/", "./www");
  9545. auto port = svr.bind_to_any_port(HOST);
  9546. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9547. auto se = detail::scope_exit([&] {
  9548. svr.stop();
  9549. listen_thread.join();
  9550. ASSERT_FALSE(svr.is_running());
  9551. });
  9552. svr.wait_until_ready();
  9553. Client cli(HOST, port);
  9554. auto res = cli.Get("/mount2/dir/test.html");
  9555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9556. EXPECT_EQ(StatusCode::OK_200, res->status);
  9557. // "/mount2" must not match part-way through a path segment.
  9558. res = cli.Get("/mount2dir/test.html");
  9559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9560. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9561. // A mount point ending in '/' keeps matching every path below it.
  9562. res = cli.Get("/dir/test.html");
  9563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9564. EXPECT_EQ(StatusCode::OK_200, res->status);
  9565. }
  9566. TEST(MountTest, Redicect) {
  9567. Server svr;
  9568. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9569. auto se = detail::scope_exit([&] {
  9570. svr.stop();
  9571. listen_thread.join();
  9572. ASSERT_FALSE(svr.is_running());
  9573. });
  9574. svr.set_mount_point("/", "./www");
  9575. svr.wait_until_ready();
  9576. Client cli("localhost", PORT);
  9577. auto res = cli.Get("/dir/");
  9578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9579. EXPECT_EQ(StatusCode::OK_200, res->status);
  9580. res = cli.Get("/dir");
  9581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9582. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9583. res = cli.Get("/file");
  9584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9585. EXPECT_EQ(StatusCode::OK_200, res->status);
  9586. res = cli.Get("/file/");
  9587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9588. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9589. cli.set_follow_location(true);
  9590. res = cli.Get("/dir");
  9591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9592. EXPECT_EQ(StatusCode::OK_200, res->status);
  9593. }
  9594. TEST(MountTest, MultibytesPathName) {
  9595. Server svr;
  9596. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9597. auto se = detail::scope_exit([&] {
  9598. svr.stop();
  9599. listen_thread.join();
  9600. ASSERT_FALSE(svr.is_running());
  9601. });
  9602. svr.set_mount_point("/", "./www");
  9603. svr.wait_until_ready();
  9604. Client cli("localhost", PORT);
  9605. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9607. EXPECT_EQ(StatusCode::OK_200, res->status);
  9608. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9609. }
  9610. #ifdef _WIN32
  9611. // Issue #2435: mmap::open() must succeed even when another handle holds
  9612. // the file open for writing (e.g. an active log file).
  9613. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9614. const char *path = "mmap_concurrent_writer_test.txt";
  9615. const char *content = "hello";
  9616. {
  9617. std::ofstream f(path, std::ios::binary);
  9618. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9619. }
  9620. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9621. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9622. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9623. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9624. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9625. detail::mmap m(path);
  9626. ASSERT_TRUE(m.is_open());
  9627. EXPECT_EQ(strlen(content), m.size());
  9628. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9629. }
  9630. #endif
  9631. #ifndef _WIN32
  9632. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9633. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9634. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9635. TEST(MmapTest, FailedMappingIsNotOpen) {
  9636. const char *path = "./mmap_failed_mapping_test_dir";
  9637. ASSERT_EQ(0, ::mkdir(path, 0755));
  9638. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9639. detail::mmap m(path);
  9640. EXPECT_FALSE(m.is_open());
  9641. EXPECT_EQ(0U, m.size());
  9642. EXPECT_NE(static_cast<const void *>(m.data()),
  9643. static_cast<const void *>(MAP_FAILED));
  9644. }
  9645. #endif
  9646. TEST(KeepAliveTest, ReadTimeout) {
  9647. Server svr;
  9648. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9649. std::this_thread::sleep_for(std::chrono::seconds(2));
  9650. res.set_content("a", "text/plain");
  9651. });
  9652. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9653. res.set_content("b", "text/plain");
  9654. });
  9655. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9656. auto se = detail::scope_exit([&] {
  9657. svr.stop();
  9658. listen_thread.join();
  9659. ASSERT_FALSE(svr.is_running());
  9660. });
  9661. svr.wait_until_ready();
  9662. Client cli("localhost", PORT);
  9663. cli.set_keep_alive(true);
  9664. cli.set_read_timeout(std::chrono::seconds(1));
  9665. auto resa = cli.Get("/a");
  9666. ASSERT_FALSE(resa);
  9667. EXPECT_EQ(Error::Read, resa.error());
  9668. auto resb = cli.Get("/b");
  9669. ASSERT_TRUE(resb);
  9670. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9671. EXPECT_EQ("b", resb->body);
  9672. }
  9673. TEST(KeepAliveTest, MaxCount) {
  9674. size_t keep_alive_max_count = 3;
  9675. Server svr;
  9676. svr.set_keep_alive_max_count(keep_alive_max_count);
  9677. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9678. res.set_content("Hello World!", "text/plain");
  9679. });
  9680. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9681. auto se = detail::scope_exit([&] {
  9682. svr.stop();
  9683. listen_thread.join();
  9684. ASSERT_FALSE(svr.is_running());
  9685. });
  9686. svr.wait_until_ready();
  9687. Client cli(HOST, PORT);
  9688. cli.set_keep_alive(true);
  9689. for (size_t i = 0; i < 5; i++) {
  9690. auto result = cli.Get("/hi");
  9691. ASSERT_TRUE(result);
  9692. EXPECT_EQ(StatusCode::OK_200, result->status);
  9693. if (i == keep_alive_max_count - 1) {
  9694. EXPECT_EQ("close", result->get_header_value("Connection"));
  9695. } else {
  9696. EXPECT_FALSE(result->has_header("Connection"));
  9697. }
  9698. }
  9699. }
  9700. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9701. // can pull the next one into the server's buffer. The server must serve it
  9702. // without waiting for the socket to become readable again. The keep-alive
  9703. // timeout outlasts the client's read timeout, so a request left waiting for it
  9704. // shows up as a missing response.
  9705. static void serve_pipelining_routes(Server &svr,
  9706. const std::function<void(int)> &client) {
  9707. svr.set_keep_alive_timeout(5);
  9708. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9709. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9710. });
  9711. svr.Post("/echo", [](const Request &req, Response &res) {
  9712. res.set_content("echo " + req.body, "text/plain");
  9713. });
  9714. auto port = svr.bind_to_any_port(HOST);
  9715. thread t = thread([&] { svr.listen_after_bind(); });
  9716. auto se = detail::scope_exit([&] {
  9717. svr.stop();
  9718. t.join();
  9719. });
  9720. svr.wait_until_ready();
  9721. client(port);
  9722. }
  9723. static std::string
  9724. send_pipelined_requests(const std::vector<std::string> &parts) {
  9725. Server svr;
  9726. std::string res;
  9727. serve_pipelining_routes(svr, [&](int port) {
  9728. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9729. });
  9730. return res;
  9731. }
  9732. static void expect_in_order(const std::string &res,
  9733. const std::vector<std::string> &bodies) {
  9734. size_t pos = 0;
  9735. for (const auto &body : bodies) {
  9736. pos = res.find(body, pos);
  9737. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9738. pos += body.size();
  9739. }
  9740. }
  9741. TEST(KeepAliveTest, PipelinedRequests) {
  9742. auto res = send_pipelined_requests(
  9743. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9744. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9745. "Content-Length: 4\r\n\r\nbody"
  9746. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9747. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9748. }
  9749. // The second request starts in the server's buffer and ends on the socket.
  9750. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9751. auto res =
  9752. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9753. "GET /hi/2 HTTP/1.1\r\nHo",
  9754. "st: localhost\r\nConnection: close\r\n\r\n"});
  9755. expect_in_order(res, {"hi 1", "hi 2"});
  9756. }
  9757. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9758. // CRLF after a body does not turn into a 400 for the next request.
  9759. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9760. auto res = send_pipelined_requests(
  9761. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9762. "Content-Length: 4\r\n\r\nbody\r\n"
  9763. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9764. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9765. expect_in_order(res, {"echo body", "hi 2"});
  9766. }
  9767. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9768. // must not be served as the next request.
  9769. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9770. auto res = send_pipelined_requests(
  9771. {"INVALID REQUEST LINE\r\n\r\n"
  9772. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9773. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9774. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9775. }
  9776. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9777. // Over TLS, the next request is held by the TLS library as already decrypted
  9778. // data rather than on the socket.
  9779. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9781. std::string res;
  9782. serve_pipelining_routes(svr, [&](int port) {
  9783. auto error = Error::Success;
  9784. auto sock = detail::create_client_socket(
  9785. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9786. /*connection_timeout_sec=*/5, 0,
  9787. /*read_timeout_sec=*/2, 0,
  9788. /*write_timeout_sec=*/5, 0, std::string(), error);
  9789. ASSERT_NE(INVALID_SOCKET, sock);
  9790. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9791. auto ctx = SSL_CTX_new(TLS_client_method());
  9792. auto ssl = SSL_new(ctx);
  9793. auto ssl_se = detail::scope_exit([&] {
  9794. SSL_free(ssl);
  9795. SSL_CTX_free(ctx);
  9796. });
  9797. SSL_set_fd(ssl, static_cast<int>(sock));
  9798. ASSERT_EQ(1, SSL_connect(ssl));
  9799. // One write, so all three requests arrive in one TLS record
  9800. const std::string req =
  9801. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9802. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9803. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  9804. ASSERT_EQ(static_cast<int>(req.size()),
  9805. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  9806. char buf[512];
  9807. int n;
  9808. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9809. res.append(buf, static_cast<size_t>(n));
  9810. }
  9811. });
  9812. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  9813. }
  9814. #endif
  9815. TEST(KeepAliveTest, Issue1041) {
  9816. Server svr;
  9817. svr.set_keep_alive_timeout(3);
  9818. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9819. res.set_content("Hello World!", "text/plain");
  9820. });
  9821. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9822. auto se = detail::scope_exit([&] {
  9823. svr.stop();
  9824. listen_thread.join();
  9825. ASSERT_FALSE(svr.is_running());
  9826. });
  9827. svr.wait_until_ready();
  9828. Client cli(HOST, PORT);
  9829. cli.set_keep_alive(true);
  9830. auto result = cli.Get("/hi");
  9831. ASSERT_TRUE(result);
  9832. EXPECT_EQ(StatusCode::OK_200, result->status);
  9833. std::this_thread::sleep_for(std::chrono::seconds(5));
  9834. result = cli.Get("/hi");
  9835. ASSERT_TRUE(result);
  9836. EXPECT_EQ(StatusCode::OK_200, result->status);
  9837. }
  9838. TEST(KeepAliveTest, Issue1959) {
  9839. Server svr;
  9840. svr.set_keep_alive_timeout(5);
  9841. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9842. res.set_content("a", "text/plain");
  9843. });
  9844. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9845. auto se = detail::scope_exit([&] {
  9846. if (!svr.is_running()) return;
  9847. svr.stop();
  9848. listen_thread.join();
  9849. ASSERT_FALSE(svr.is_running());
  9850. });
  9851. svr.wait_until_ready();
  9852. Client cli("localhost", PORT);
  9853. cli.set_keep_alive(true);
  9854. using namespace std::chrono;
  9855. auto start = steady_clock::now();
  9856. cli.Get("/a");
  9857. svr.stop();
  9858. listen_thread.join();
  9859. auto end = steady_clock::now();
  9860. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9861. EXPECT_LT(elapsed, 5000);
  9862. }
  9863. #ifdef CPPHTTPLIB_SSL_ENABLED
  9864. TEST(KeepAliveTest, SSLClientReconnection) {
  9865. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9866. ASSERT_TRUE(svr.is_valid());
  9867. svr.set_keep_alive_timeout(1);
  9868. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9869. res.set_content("Hello World!", "text/plain");
  9870. });
  9871. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9872. auto se = detail::scope_exit([&] {
  9873. svr.stop();
  9874. listen_thread.join();
  9875. ASSERT_FALSE(svr.is_running());
  9876. });
  9877. svr.wait_until_ready();
  9878. SSLClient cli(HOST, PORT);
  9879. cli.enable_server_certificate_verification(false);
  9880. cli.set_keep_alive(true);
  9881. auto result = cli.Get("/hi");
  9882. ASSERT_TRUE(result);
  9883. EXPECT_EQ(StatusCode::OK_200, result->status);
  9884. result = cli.Get("/hi");
  9885. ASSERT_TRUE(result);
  9886. EXPECT_EQ(StatusCode::OK_200, result->status);
  9887. std::this_thread::sleep_for(std::chrono::seconds(2));
  9888. // Recoonect
  9889. result = cli.Get("/hi");
  9890. ASSERT_TRUE(result);
  9891. EXPECT_EQ(StatusCode::OK_200, result->status);
  9892. result = cli.Get("/hi");
  9893. ASSERT_TRUE(result);
  9894. EXPECT_EQ(StatusCode::OK_200, result->status);
  9895. }
  9896. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9897. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9898. ASSERT_TRUE(svr.is_valid());
  9899. svr.set_keep_alive_timeout(1);
  9900. std::string content = "reconnect";
  9901. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9902. res.set_content("Hello World!", "text/plain");
  9903. });
  9904. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9905. auto se = detail::scope_exit([&] {
  9906. svr.stop();
  9907. listen_thread.join();
  9908. ASSERT_FALSE(svr.is_running());
  9909. });
  9910. svr.wait_until_ready();
  9911. SSLClient cli(HOST, PORT);
  9912. cli.enable_server_certificate_verification(false);
  9913. cli.set_keep_alive(true);
  9914. auto result = cli.Post(
  9915. "/hi", content.size(),
  9916. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9917. sink.write(content.c_str(), content.size());
  9918. return true;
  9919. },
  9920. "text/plain");
  9921. ASSERT_TRUE(result);
  9922. EXPECT_EQ(200, result->status);
  9923. std::this_thread::sleep_for(std::chrono::seconds(2));
  9924. // Recoonect
  9925. result = cli.Post(
  9926. "/hi", content.size(),
  9927. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9928. sink.write(content.c_str(), content.size());
  9929. return true;
  9930. },
  9931. "text/plain");
  9932. ASSERT_TRUE(result);
  9933. EXPECT_EQ(200, result->status);
  9934. result = cli.Post(
  9935. "/hi", content.size(),
  9936. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9937. sink.write(content.c_str(), content.size());
  9938. return true;
  9939. },
  9940. "text/plain");
  9941. ASSERT_TRUE(result);
  9942. EXPECT_EQ(200, result->status);
  9943. }
  9944. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9945. using namespace httplib::tls;
  9946. {
  9947. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9948. ASSERT_TRUE(svr.is_valid());
  9949. svr.Get("/sni", [&](const Request &req, Response &res) {
  9950. std::string expected = req.sni();
  9951. EXPECT_EQ(expected, req.get_param_value("expected"));
  9952. res.set_content("ok", "text/plain");
  9953. });
  9954. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9955. auto se = detail::scope_exit([&] {
  9956. svr.stop();
  9957. listen_thread.join();
  9958. ASSERT_FALSE(svr.is_running());
  9959. });
  9960. svr.wait_until_ready();
  9961. {
  9962. SSLClient cli("localhost", PORT);
  9963. cli.enable_server_certificate_verification(false);
  9964. auto res = cli.Get("/sni?expected=localhost");
  9965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9966. }
  9967. {
  9968. SSLClient cli("::1", PORT);
  9969. cli.enable_server_certificate_verification(false);
  9970. auto res = cli.Get("/sni?expected=");
  9971. // NOTE: This may fail if the server is listening on IPv4 only
  9972. // (e.g., when localhost resolves to 127.0.0.1 only)
  9973. if (res) {
  9974. EXPECT_EQ(StatusCode::OK_200, res->status);
  9975. } else {
  9976. EXPECT_EQ(Error::Connection, res.error());
  9977. }
  9978. }
  9979. }
  9980. }
  9981. #endif
  9982. TEST(ClientProblemDetectionTest, ContentProvider) {
  9983. Server svr;
  9984. size_t content_length = 1024 * 1024;
  9985. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9986. res.set_content_provider(
  9987. content_length, "text/plain",
  9988. [&](size_t offset, size_t length, DataSink &sink) {
  9989. auto out_len = std::min(length, static_cast<size_t>(1024));
  9990. std::string out(out_len, '@');
  9991. sink.write(out.data(), out_len);
  9992. return offset < 4096;
  9993. },
  9994. [](bool success) { ASSERT_FALSE(success); });
  9995. });
  9996. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9997. res.set_content_provider(
  9998. 0, "text/plain",
  9999. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10000. EXPECT_TRUE(false);
  10001. return true;
  10002. },
  10003. [](bool success) { ASSERT_FALSE(success); });
  10004. });
  10005. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10006. auto se = detail::scope_exit([&] {
  10007. svr.stop();
  10008. listen_thread.join();
  10009. ASSERT_FALSE(svr.is_running());
  10010. });
  10011. svr.wait_until_ready();
  10012. Client cli("localhost", PORT);
  10013. {
  10014. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10015. size_t /*data_length*/) { return false; });
  10016. ASSERT_FALSE(res);
  10017. }
  10018. {
  10019. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10020. size_t /*data_length*/) { return false; });
  10021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10022. }
  10023. }
  10024. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10025. // A provider that reports success without writing anything and without
  10026. // calling done() used to be handed the same offset and length again on every
  10027. // pass, so it spun for as long as the peer stayed connected.
  10028. Server svr;
  10029. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10030. res.set_content("ok", "text/plain");
  10031. });
  10032. auto port = svr.bind_to_any_port(HOST);
  10033. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10034. auto se = detail::scope_exit([&] {
  10035. svr.stop();
  10036. listen_thread.join();
  10037. ASSERT_FALSE(svr.is_running());
  10038. });
  10039. svr.wait_until_ready();
  10040. std::atomic<int> call_count{0};
  10041. Client cli(HOST, port);
  10042. auto res = cli.Post(
  10043. "/", 1024,
  10044. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10045. // Give up after enough passes to show the spin, so that losing the
  10046. // check below fails this test instead of hanging it.
  10047. return ++call_count < 100;
  10048. },
  10049. "text/plain");
  10050. ASSERT_FALSE(res);
  10051. EXPECT_EQ(Error::Write, res.error());
  10052. EXPECT_EQ(1, call_count.load());
  10053. }
  10054. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10055. // A writer only has to assign `write`. The other three used to be left as
  10056. // empty std::functions, so a provider calling one threw
  10057. // std::bad_function_call out of the thread running it and took the whole
  10058. // process down.
  10059. DataSink sink;
  10060. std::string written;
  10061. sink.write = [&](const char *data, size_t data_len) {
  10062. written.append(data, data_len);
  10063. return true;
  10064. };
  10065. EXPECT_TRUE(sink.is_writable());
  10066. sink.done();
  10067. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10068. EXPECT_TRUE(written.empty());
  10069. }
  10070. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10071. // A sink that cannot carry trailers still has to finish.
  10072. DataSink sink;
  10073. auto done_count = 0;
  10074. sink.done = [&]() { done_count++; };
  10075. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10076. EXPECT_EQ(1, done_count);
  10077. }
  10078. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10079. Server svr;
  10080. const std::string body(4096, 'x');
  10081. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10082. res.set_content_provider(body.size(), "text/plain",
  10083. [&](size_t offset, size_t length, DataSink &sink) {
  10084. sink.write(body.data() + offset, length);
  10085. sink.done();
  10086. return true;
  10087. });
  10088. });
  10089. auto port = svr.bind_to_any_port(HOST);
  10090. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10091. auto se = detail::scope_exit([&] {
  10092. svr.stop();
  10093. listen_thread.join();
  10094. ASSERT_FALSE(svr.is_running());
  10095. });
  10096. svr.wait_until_ready();
  10097. Client cli(HOST, port);
  10098. auto res = cli.Get("/");
  10099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10100. EXPECT_EQ(StatusCode::OK_200, res->status);
  10101. EXPECT_EQ(body, res->body);
  10102. }
  10103. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10104. Server svr;
  10105. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10106. res.set_content_provider(
  10107. 1024, "text/plain",
  10108. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10109. sink.write("hello", 5);
  10110. sink.done(); // short of the 1024 bytes the response promised
  10111. return true;
  10112. });
  10113. });
  10114. auto port = svr.bind_to_any_port(HOST);
  10115. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10116. auto se = detail::scope_exit([&] {
  10117. svr.stop();
  10118. listen_thread.join();
  10119. ASSERT_FALSE(svr.is_running());
  10120. });
  10121. svr.wait_until_ready();
  10122. Client cli(HOST, port);
  10123. cli.set_read_timeout(5, 0);
  10124. // The response is short of its Content-Length, so the client cannot read a
  10125. // complete body. What matters is that this returns at all: a no-op done()
  10126. // would leave the writer looping over a provider that never makes progress.
  10127. auto res = cli.Get("/");
  10128. EXPECT_FALSE(res);
  10129. }
  10130. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10131. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10132. // The compressed path builds the whole body before connecting, so this
  10133. // fails client-side and never reaches a server.
  10134. Client cli(HOST, PORT);
  10135. cli.set_compress(true);
  10136. auto res = cli.Post(
  10137. "/", 1024,
  10138. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10139. sink.write("hello", 5);
  10140. sink.done(); // short of the 1024 bytes the request announced
  10141. return true;
  10142. },
  10143. "text/plain");
  10144. ASSERT_FALSE(res);
  10145. EXPECT_EQ(Error::Write, res.error());
  10146. }
  10147. #endif
  10148. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10149. Server svr;
  10150. svr.set_error_handler([](Request const &, Response &res) -> void {
  10151. res.set_chunked_content_provider(
  10152. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10153. sink.os << "hello";
  10154. sink.os << "world";
  10155. sink.done();
  10156. return true;
  10157. });
  10158. });
  10159. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10160. auto se = detail::scope_exit([&] {
  10161. svr.stop();
  10162. listen_thread.join();
  10163. ASSERT_FALSE(svr.is_running());
  10164. });
  10165. svr.wait_until_ready();
  10166. Client cli("localhost", PORT);
  10167. auto res = cli.Get("/");
  10168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10169. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10170. EXPECT_EQ("helloworld", res->body);
  10171. }
  10172. TEST(LongPollingTest, ClientCloseDetection) {
  10173. Server svr;
  10174. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10175. res.set_chunked_content_provider(
  10176. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10177. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10178. sink.os << "hello";
  10179. auto count = 10;
  10180. while (count > 0 && sink.is_writable()) {
  10181. this_thread::sleep_for(chrono::milliseconds(10));
  10182. count--;
  10183. }
  10184. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10185. return true;
  10186. });
  10187. });
  10188. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10189. auto se = detail::scope_exit([&] {
  10190. svr.stop();
  10191. listen_thread.join();
  10192. ASSERT_FALSE(svr.is_running());
  10193. });
  10194. svr.wait_until_ready();
  10195. Client cli("localhost", PORT);
  10196. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10197. EXPECT_EQ("hello", string(data, data_length));
  10198. return false; // close the socket immediately.
  10199. });
  10200. ASSERT_FALSE(res);
  10201. }
  10202. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10203. Server svr;
  10204. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10205. res.set_chunked_content_provider(
  10206. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10207. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10208. sink.os << "hello";
  10209. EXPECT_TRUE(sink.os.good());
  10210. // Wait for the client to close the connection
  10211. auto count = 10;
  10212. while (count > 0 && sink.is_writable()) {
  10213. this_thread::sleep_for(chrono::milliseconds(10));
  10214. count--;
  10215. }
  10216. // After client disconnect, write repeatedly until the socket
  10217. // write actually fails (small writes may be absorbed by the
  10218. // kernel buffer)
  10219. std::string chunk(1024, 'x');
  10220. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10221. sink.os << chunk;
  10222. }
  10223. EXPECT_TRUE(sink.os.fail());
  10224. return true;
  10225. });
  10226. });
  10227. auto port = svr.bind_to_any_port("localhost");
  10228. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10229. auto se = detail::scope_exit([&] {
  10230. svr.stop();
  10231. listen_thread.join();
  10232. ASSERT_FALSE(svr.is_running());
  10233. });
  10234. svr.wait_until_ready();
  10235. Client cli("localhost", port);
  10236. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10237. EXPECT_EQ("hello", string(data, data_length));
  10238. return false; // close the socket immediately.
  10239. });
  10240. ASSERT_FALSE(res);
  10241. }
  10242. TEST(GetWithParametersTest, GetWithParameters) {
  10243. Server svr;
  10244. svr.Get("/", [&](const Request &req, Response &) {
  10245. EXPECT_EQ("world", req.get_param_value("hello"));
  10246. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10247. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10248. });
  10249. svr.Get("/params", [&](const Request &req, Response &) {
  10250. EXPECT_EQ("world", req.get_param_value("hello"));
  10251. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10252. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10253. });
  10254. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10255. EXPECT_EQ("resource-id", req.matches[1]);
  10256. EXPECT_EQ("foo", req.get_param_value("param1"));
  10257. EXPECT_EQ("bar", req.get_param_value("param2"));
  10258. });
  10259. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10260. EXPECT_EQ("user-id", req.path_params.at("id"));
  10261. EXPECT_EQ("foo", req.get_param_value("param1"));
  10262. EXPECT_EQ("bar", req.get_param_value("param2"));
  10263. });
  10264. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10265. auto se = detail::scope_exit([&] {
  10266. svr.stop();
  10267. listen_thread.join();
  10268. ASSERT_FALSE(svr.is_running());
  10269. });
  10270. svr.wait_until_ready();
  10271. {
  10272. Client cli(HOST, PORT);
  10273. Params params;
  10274. params.emplace("hello", "world");
  10275. params.emplace("hello2", "world2");
  10276. params.emplace("hello3", "world3");
  10277. auto res = cli.Get("/", params, Headers{});
  10278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10279. EXPECT_EQ(StatusCode::OK_200, res->status);
  10280. }
  10281. {
  10282. Client cli(HOST, PORT);
  10283. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10285. EXPECT_EQ(StatusCode::OK_200, res->status);
  10286. }
  10287. {
  10288. Client cli(HOST, PORT);
  10289. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10291. EXPECT_EQ(StatusCode::OK_200, res->status);
  10292. }
  10293. {
  10294. Client cli(HOST, PORT);
  10295. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10297. EXPECT_EQ(StatusCode::OK_200, res->status);
  10298. }
  10299. }
  10300. TEST(GetWithParametersTest, GetWithParameters2) {
  10301. Server svr;
  10302. svr.Get("/", [&](const Request &req, Response &res) {
  10303. auto text = req.get_param_value("hello");
  10304. res.set_content(text, "text/plain");
  10305. });
  10306. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10307. auto se = detail::scope_exit([&] {
  10308. svr.stop();
  10309. listen_thread.join();
  10310. ASSERT_FALSE(svr.is_running());
  10311. });
  10312. svr.wait_until_ready();
  10313. Client cli("localhost", PORT);
  10314. Params params;
  10315. params.emplace("hello", "world");
  10316. std::string body;
  10317. auto res = cli.Get("/", params, Headers{},
  10318. [&](const char *data, size_t data_length) {
  10319. body.append(data, data_length);
  10320. return true;
  10321. });
  10322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10323. EXPECT_EQ(StatusCode::OK_200, res->status);
  10324. EXPECT_EQ("world", body);
  10325. }
  10326. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10327. Server svr;
  10328. svr.Get("/search", [&](const Request &req, Response &res) {
  10329. auto q = req.get_param_value("q");
  10330. res.set_content(q, "text/plain");
  10331. });
  10332. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10333. auto se = detail::scope_exit([&] {
  10334. svr.stop();
  10335. listen_thread.join();
  10336. ASSERT_FALSE(svr.is_running());
  10337. });
  10338. svr.wait_until_ready();
  10339. Client cli("localhost", PORT);
  10340. // Verify that Get(path, params) works without requiring Headers argument
  10341. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10343. EXPECT_EQ(StatusCode::OK_200, res->status);
  10344. EXPECT_EQ("cpp-httplib", res->body);
  10345. }
  10346. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10347. auto host = "httpbingo.org";
  10348. auto path = std::string{"/range/32"};
  10349. #ifdef CPPHTTPLIB_SSL_ENABLED
  10350. SSLClient cli(host);
  10351. #else
  10352. Client cli(host);
  10353. #endif
  10354. cli.set_default_headers({make_range_header({{1, 10}})});
  10355. cli.set_connection_timeout(5);
  10356. {
  10357. auto res = cli.Get(path);
  10358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10359. EXPECT_EQ("bcdefghijk", res->body);
  10360. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10361. }
  10362. {
  10363. auto res = cli.Get(path);
  10364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10365. EXPECT_EQ("bcdefghijk", res->body);
  10366. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10367. }
  10368. }
  10369. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10370. Server svr;
  10371. svr.set_default_headers({{"Hello", "World"}});
  10372. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10373. res.set_content("ok", "text/plain");
  10374. });
  10375. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10376. auto se = detail::scope_exit([&] {
  10377. svr.stop();
  10378. listen_thread.join();
  10379. ASSERT_FALSE(svr.is_running());
  10380. });
  10381. svr.wait_until_ready();
  10382. Client cli("localhost", PORT);
  10383. auto res = cli.Get("/");
  10384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10385. EXPECT_EQ(StatusCode::OK_200, res->status);
  10386. EXPECT_EQ("ok", res->body);
  10387. EXPECT_EQ("World", res->get_header_value("Hello"));
  10388. }
  10389. #ifdef CPPHTTPLIB_SSL_ENABLED
  10390. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10391. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10392. ASSERT_TRUE(svr.is_valid());
  10393. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10394. std::this_thread::sleep_for(std::chrono::seconds(2));
  10395. res.set_content("a", "text/plain");
  10396. });
  10397. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10398. res.set_content("b", "text/plain");
  10399. });
  10400. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10401. auto se = detail::scope_exit([&] {
  10402. svr.stop();
  10403. listen_thread.join();
  10404. ASSERT_FALSE(svr.is_running());
  10405. });
  10406. svr.wait_until_ready();
  10407. SSLClient cli("localhost", PORT);
  10408. cli.enable_server_certificate_verification(false);
  10409. cli.set_keep_alive(true);
  10410. cli.set_read_timeout(std::chrono::seconds(1));
  10411. auto resa = cli.Get("/a");
  10412. ASSERT_TRUE(!resa);
  10413. EXPECT_EQ(Error::Read, resa.error());
  10414. auto resb = cli.Get("/b");
  10415. ASSERT_TRUE(resb);
  10416. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10417. EXPECT_EQ("b", resb->body);
  10418. }
  10419. // Closing an idle keep-alive connection sends close_notify and returns. The
  10420. // server must not wait for the client's close_notify: an idle client never
  10421. // sends one, so the worker would be held until the read timeout expires, and
  10422. // stop() would wait for it.
  10423. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10424. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10425. ASSERT_TRUE(svr.is_valid());
  10426. svr.set_keep_alive_timeout(1);
  10427. svr.set_read_timeout(10, 0);
  10428. svr.Get("/", [](const Request &, Response &res) {
  10429. res.set_content("ok", "text/plain");
  10430. });
  10431. auto port = svr.bind_to_any_port(HOST);
  10432. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10433. auto se = detail::scope_exit([&] {
  10434. if (listen_thread.joinable()) {
  10435. svr.stop();
  10436. listen_thread.join();
  10437. }
  10438. });
  10439. svr.wait_until_ready();
  10440. SSLClient cli(HOST, port);
  10441. cli.enable_server_certificate_verification(false);
  10442. cli.set_keep_alive(true);
  10443. auto res = cli.Get("/");
  10444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10445. EXPECT_EQ(StatusCode::OK_200, res->status);
  10446. // Stay idle past the keep-alive timeout so the server closes the connection.
  10447. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10448. auto start = std::chrono::steady_clock::now();
  10449. svr.stop();
  10450. listen_thread.join();
  10451. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10452. std::chrono::steady_clock::now() - start)
  10453. .count();
  10454. EXPECT_LT(elapsed, 3000);
  10455. }
  10456. #endif
  10457. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10458. protected:
  10459. ServerTestWithAI_PASSIVE()
  10460. : cli_(HOST, PORT)
  10461. #ifdef CPPHTTPLIB_SSL_ENABLED
  10462. ,
  10463. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10464. #endif
  10465. {
  10466. #ifdef CPPHTTPLIB_SSL_ENABLED
  10467. cli_.enable_server_certificate_verification(false);
  10468. #endif
  10469. }
  10470. virtual void SetUp() {
  10471. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10472. res.set_content("Hello World!", "text/plain");
  10473. });
  10474. t_ = thread(
  10475. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10476. svr_.wait_until_ready();
  10477. }
  10478. virtual void TearDown() {
  10479. svr_.stop();
  10480. t_.join();
  10481. }
  10482. #ifdef CPPHTTPLIB_SSL_ENABLED
  10483. SSLClient cli_;
  10484. SSLServer svr_;
  10485. #else
  10486. Client cli_;
  10487. Server svr_;
  10488. #endif
  10489. thread t_;
  10490. };
  10491. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10492. auto res = cli_.Get("/hi");
  10493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10494. EXPECT_EQ(StatusCode::OK_200, res->status);
  10495. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10496. EXPECT_EQ("Hello World!", res->body);
  10497. }
  10498. class ServerUpDownTest : public ::testing::Test {
  10499. protected:
  10500. ServerUpDownTest() : cli_(HOST, PORT) {}
  10501. virtual void SetUp() {
  10502. t_ = thread([&]() {
  10503. svr_.bind_to_any_port(HOST);
  10504. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10505. ASSERT_TRUE(svr_.listen_after_bind());
  10506. });
  10507. svr_.wait_until_ready();
  10508. }
  10509. virtual void TearDown() {
  10510. svr_.stop();
  10511. t_.join();
  10512. }
  10513. Client cli_;
  10514. Server svr_;
  10515. thread t_;
  10516. };
  10517. TEST_F(ServerUpDownTest, QuickStartStop) {
  10518. // Should not crash, especially when run with
  10519. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10520. }
  10521. class PayloadMaxLengthTest : public ::testing::Test {
  10522. protected:
  10523. PayloadMaxLengthTest()
  10524. : cli_(HOST, PORT)
  10525. #ifdef CPPHTTPLIB_SSL_ENABLED
  10526. ,
  10527. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10528. #endif
  10529. {
  10530. #ifdef CPPHTTPLIB_SSL_ENABLED
  10531. cli_.enable_server_certificate_verification(false);
  10532. #endif
  10533. }
  10534. virtual void SetUp() {
  10535. svr_.set_payload_max_length(8);
  10536. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10537. res.set_content("test", "text/plain");
  10538. });
  10539. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10540. svr_.wait_until_ready();
  10541. }
  10542. virtual void TearDown() {
  10543. svr_.stop();
  10544. t_.join();
  10545. }
  10546. #ifdef CPPHTTPLIB_SSL_ENABLED
  10547. SSLClient cli_;
  10548. SSLServer svr_;
  10549. #else
  10550. Client cli_;
  10551. Server svr_;
  10552. #endif
  10553. thread t_;
  10554. };
  10555. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10556. auto res = cli_.Post("/test", "123456789", "text/plain");
  10557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10558. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10559. res = cli_.Post("/test", "12345678", "text/plain");
  10560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10561. EXPECT_EQ(StatusCode::OK_200, res->status);
  10562. }
  10563. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10564. // Test chunked encoding with payload exceeding the 8-byte limit
  10565. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10566. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10568. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10569. }
  10570. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10571. // Test chunked encoding with payload within the 8-byte limit
  10572. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10573. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10575. EXPECT_EQ(StatusCode::OK_200, res->status);
  10576. }
  10577. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10578. // Test using send_request to send chunked data exceeding payload limit
  10579. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10580. "Host: " +
  10581. std::string(HOST) + ":" + std::to_string(PORT) +
  10582. "\r\n"
  10583. "Transfer-Encoding: chunked\r\n"
  10584. "Connection: close\r\n"
  10585. "\r\n"
  10586. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10587. "0123456789\r\n"
  10588. "0\r\n" // End chunk
  10589. "\r\n";
  10590. std::string response;
  10591. bool result = send_request(1, chunked_request, &response);
  10592. if (!result) {
  10593. // If send_request fails, it might be because the server closed the
  10594. // connection due to payload limit enforcement, which is acceptable
  10595. SUCCEED()
  10596. << "Server rejected oversized chunked request (connection closed)";
  10597. } else {
  10598. // If we got a response, check if it's an error response or connection was
  10599. // closed early Short response length indicates connection was closed due to
  10600. // payload limit
  10601. if (response.length() <= 10) {
  10602. SUCCEED() << "Server closed connection for oversized chunked request";
  10603. } else {
  10604. // Check for error status codes
  10605. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10606. response.find("Payload Too Large") != std::string::npos ||
  10607. response.find("400") != std::string::npos);
  10608. }
  10609. }
  10610. }
  10611. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10612. // Test request without Content-Length header exceeding payload limit
  10613. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10614. "Host: " +
  10615. std::string(HOST) + ":" +
  10616. std::to_string(PORT) +
  10617. "\r\n"
  10618. "Connection: close\r\n"
  10619. "\r\n";
  10620. // Add payload exceeding the 8-byte limit
  10621. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10622. request_without_content_length += large_payload;
  10623. std::string response;
  10624. bool result = send_request(1, request_without_content_length, &response);
  10625. if (!result) {
  10626. // If send_request fails, server likely closed connection due to payload
  10627. // limit
  10628. SUCCEED() << "Server rejected oversized request without Content-Length "
  10629. "(connection closed)";
  10630. } else {
  10631. // Check if server responded with error or closed connection early
  10632. if (response.length() <= 10) {
  10633. SUCCEED() << "Server closed connection for oversized request without "
  10634. "Content-Length";
  10635. } else {
  10636. // Check for error status codes
  10637. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10638. response.find("Payload Too Large") != std::string::npos ||
  10639. response.find("400") != std::string::npos);
  10640. }
  10641. }
  10642. }
  10643. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10644. // Test request without Content-Length header within payload limit
  10645. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10646. "Host: " +
  10647. std::string(HOST) + ":" +
  10648. std::to_string(PORT) +
  10649. "\r\n"
  10650. "Connection: close\r\n"
  10651. "\r\n";
  10652. // Add payload within the 8-byte limit
  10653. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10654. request_without_content_length += small_payload;
  10655. std::string response;
  10656. bool result = send_request(1, request_without_content_length, &response);
  10657. // For requests without Content-Length, the server may have different behavior
  10658. // The key is that it should not reject due to payload limit for small
  10659. // payloads
  10660. if (result) {
  10661. // Check for any HTTP response (success or error, but not connection closed)
  10662. if (response.length() > 10) {
  10663. SUCCEED()
  10664. << "Server processed request without Content-Length within limit";
  10665. } else {
  10666. // Short response might indicate connection closed, which is acceptable
  10667. SUCCEED() << "Server closed connection for request without "
  10668. "Content-Length (acceptable behavior)";
  10669. }
  10670. } else {
  10671. // Connection failure might be due to protocol requirements
  10672. SUCCEED() << "Connection issue with request without Content-Length "
  10673. "(environment-specific)";
  10674. }
  10675. }
  10676. class LargePayloadMaxLengthTest : public ::testing::Test {
  10677. protected:
  10678. LargePayloadMaxLengthTest()
  10679. : cli_(HOST, PORT)
  10680. #ifdef CPPHTTPLIB_SSL_ENABLED
  10681. ,
  10682. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10683. #endif
  10684. {
  10685. #ifdef CPPHTTPLIB_SSL_ENABLED
  10686. cli_.enable_server_certificate_verification(false);
  10687. #endif
  10688. }
  10689. virtual void SetUp() {
  10690. // Set 10MB payload limit
  10691. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10692. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10693. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10694. res.set_content("Large payload test", "text/plain");
  10695. });
  10696. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10697. svr_.wait_until_ready();
  10698. }
  10699. virtual void TearDown() {
  10700. svr_.stop();
  10701. t_.join();
  10702. }
  10703. #ifdef CPPHTTPLIB_SSL_ENABLED
  10704. SSLClient cli_;
  10705. SSLServer svr_;
  10706. #else
  10707. Client cli_;
  10708. Server svr_;
  10709. #endif
  10710. thread t_;
  10711. };
  10712. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10713. // Test chunked encoding with payload within 10MB limit
  10714. std::string medium_payload(5 * 1024 * 1024,
  10715. 'A'); // 5MB payload, within 10MB limit
  10716. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10718. EXPECT_EQ(StatusCode::OK_200, res->status);
  10719. }
  10720. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10721. // Test chunked encoding with payload exceeding 10MB limit
  10722. std::string large_payload(12 * 1024 * 1024,
  10723. 'B'); // 12MB payload, exceeds 10MB limit
  10724. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10725. // Server may either return 413 or close the connection
  10726. if (res) {
  10727. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10728. } else {
  10729. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10730. }
  10731. }
  10732. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10733. // Test request without Content-Length header within 10MB limit
  10734. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10735. "Host: " +
  10736. std::string(HOST) + ":" +
  10737. std::to_string(PORT) +
  10738. "\r\n"
  10739. "Connection: close\r\n"
  10740. "\r\n";
  10741. // Add 1MB payload (within 10MB limit)
  10742. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10743. request_without_content_length += medium_payload;
  10744. std::string response;
  10745. bool result = send_request(5, request_without_content_length, &response);
  10746. if (result) {
  10747. // Should get a proper HTTP response for payloads within limit
  10748. if (response.length() > 10) {
  10749. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10750. "10MB limit";
  10751. } else {
  10752. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10753. "Content-Length)";
  10754. }
  10755. } else {
  10756. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10757. }
  10758. }
  10759. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10760. // Test request without Content-Length header exceeding 10MB limit
  10761. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10762. "Host: " +
  10763. std::string(HOST) + ":" +
  10764. std::to_string(PORT) +
  10765. "\r\n"
  10766. "Connection: close\r\n"
  10767. "\r\n";
  10768. // Add 12MB payload (exceeds 10MB limit)
  10769. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10770. request_without_content_length += large_payload;
  10771. std::string response;
  10772. bool result = send_request(10, request_without_content_length, &response);
  10773. if (!result) {
  10774. // Server should close connection due to payload limit
  10775. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10776. "(connection closed)";
  10777. } else {
  10778. // Check for error response
  10779. if (response.length() <= 10) {
  10780. SUCCEED()
  10781. << "Server closed connection for 12MB request exceeding 10MB limit";
  10782. } else {
  10783. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10784. response.find("Payload Too Large") != std::string::npos ||
  10785. response.find("400") != std::string::npos);
  10786. }
  10787. }
  10788. }
  10789. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10790. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10791. // path.
  10792. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10793. Server svr;
  10794. const size_t LIMIT = 64 * 1024; // 64KB
  10795. svr.set_payload_max_length(LIMIT);
  10796. size_t total = 0;
  10797. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10798. const ContentReader &content_reader) {
  10799. content_reader([&](const char * /*data*/, size_t len) {
  10800. total += len;
  10801. return true;
  10802. });
  10803. res.status = 200;
  10804. res.set_content("stream_ok", "text/plain");
  10805. });
  10806. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10807. auto se = detail::scope_exit([&] {
  10808. svr.stop();
  10809. thread.join();
  10810. ASSERT_FALSE(svr.is_running());
  10811. });
  10812. svr.wait_until_ready();
  10813. // Prepare 256KB raw data and gzip-compress it
  10814. std::string raw(256 * 1024, 'A');
  10815. std::string gz;
  10816. {
  10817. z_stream zs{};
  10818. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10819. Z_DEFAULT_STRATEGY);
  10820. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10821. zs.avail_in = static_cast<uInt>(raw.size());
  10822. char outbuf[4096];
  10823. int ret;
  10824. do {
  10825. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10826. zs.avail_out = sizeof(outbuf);
  10827. ret = deflate(&zs, Z_FINISH);
  10828. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10829. } while (ret != Z_STREAM_END);
  10830. deflateEnd(&zs);
  10831. }
  10832. Client cli(HOST, PORT);
  10833. cli.set_connection_timeout(std::chrono::seconds(5));
  10834. Headers headers = {{"Content-Encoding", "gzip"}};
  10835. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10836. "application/octet-stream");
  10837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10838. // Server must reject oversized decompressed payloads with 413.
  10839. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10840. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10841. EXPECT_LE(total, LIMIT);
  10842. }
  10843. #ifndef CPPHTTPLIB_SSL_ENABLED
  10844. // For a request with neither Content-Length nor Transfer-Encoding, the
  10845. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10846. // compressed wire bytes straight to the ContentReader without ever routing
  10847. // them through the decompressor, so payload_max_length_ only bounded the
  10848. // compressed size on the wire, not the decompressed size.
  10849. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10850. Server svr;
  10851. const size_t LIMIT = 64 * 1024; // 64KB
  10852. svr.set_payload_max_length(LIMIT);
  10853. size_t total = 0;
  10854. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10855. const ContentReader &content_reader) {
  10856. content_reader([&](const char * /*data*/, size_t len) {
  10857. total += len;
  10858. return true;
  10859. });
  10860. res.status = 200;
  10861. res.set_content("stream_ok", "text/plain");
  10862. });
  10863. auto port = svr.bind_to_any_port(HOST);
  10864. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10865. auto se = detail::scope_exit([&] {
  10866. svr.stop();
  10867. thread.join();
  10868. ASSERT_FALSE(svr.is_running());
  10869. });
  10870. svr.wait_until_ready();
  10871. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10872. // StreamingGzipDecompression test above.
  10873. std::string raw(256 * 1024, 'A');
  10874. std::string gz;
  10875. {
  10876. httplib::detail::gzip_compressor compressor;
  10877. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10878. [&](const char *chunk, size_t len) {
  10879. gz.append(chunk, len);
  10880. return true;
  10881. });
  10882. ASSERT_TRUE(result);
  10883. }
  10884. // Send the gzip body over raw TCP with neither Content-Length nor
  10885. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10886. // kicks in.
  10887. std::string req = "POST /stream HTTP/1.1\r\n"
  10888. "Host: " +
  10889. std::string(HOST) + ":" + std::to_string(port) +
  10890. "\r\n"
  10891. "Content-Encoding: gzip\r\n"
  10892. "Connection: close\r\n"
  10893. "\r\n" +
  10894. gz;
  10895. std::string response;
  10896. ASSERT_TRUE(send_request(5, req, &response, port));
  10897. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10898. EXPECT_LE(total, LIMIT);
  10899. }
  10900. #endif
  10901. #endif
  10902. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10903. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10904. // the payload must be passed through untouched instead of being rejected.
  10905. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10906. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10907. Server svr;
  10908. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10909. res.set_content(body, "image/jpeg");
  10910. res.set_header("Content-Encoding", "UTF-8");
  10911. });
  10912. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10913. res.set_content(body, "image/jpeg");
  10914. res.set_header("Content-Encoding", "identity");
  10915. });
  10916. svr.Post("/echo", [](const Request &req, Response &res) {
  10917. res.set_content(req.body, "image/jpeg");
  10918. });
  10919. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10920. auto se = detail::scope_exit([&] {
  10921. svr.stop();
  10922. t.join();
  10923. ASSERT_FALSE(svr.is_running());
  10924. });
  10925. svr.wait_until_ready();
  10926. Client cli(HOST, PORT);
  10927. {
  10928. auto res = cli.Get("/image");
  10929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10930. EXPECT_EQ(StatusCode::OK_200, res->status);
  10931. EXPECT_EQ(body, res->body);
  10932. }
  10933. {
  10934. auto res = cli.Get("/identity");
  10935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10936. EXPECT_EQ(StatusCode::OK_200, res->status);
  10937. EXPECT_EQ(body, res->body);
  10938. }
  10939. {
  10940. // The same applies to a request body reaching the server.
  10941. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10942. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10944. EXPECT_EQ(StatusCode::OK_200, res->status);
  10945. EXPECT_EQ(body, res->body);
  10946. }
  10947. }
  10948. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10949. // gzip-encoded response even when the build has no zlib support.
  10950. static const char GZIPPED_HELLO_WORLD[] = {
  10951. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10952. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10953. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10954. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10955. // A content coding is a whole token, not something the field value merely
  10956. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10957. // as "fibre" look like Brotli, and turned a multi-coding value like
  10958. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10959. // it was never meant to see.
  10960. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10961. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10962. Server svr;
  10963. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10964. res.set_content(body, "image/jpeg");
  10965. res.set_header("Content-Encoding", "fibre");
  10966. });
  10967. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10968. res.set_content(body, "image/jpeg");
  10969. res.set_header("Content-Encoding", "gzip, br");
  10970. });
  10971. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10972. res.set_content(body, "image/jpeg");
  10973. res.set_header("Content-Encoding", "x-zstd-ish");
  10974. });
  10975. auto port = svr.bind_to_any_port(HOST);
  10976. thread t = thread([&]() { svr.listen_after_bind(); });
  10977. auto se = detail::scope_exit([&] {
  10978. svr.stop();
  10979. t.join();
  10980. ASSERT_FALSE(svr.is_running());
  10981. });
  10982. svr.wait_until_ready();
  10983. Client cli(HOST, port);
  10984. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10985. auto res = cli.Get(path);
  10986. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10987. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10988. // Not a coding we recognize, so the payload comes back untouched
  10989. EXPECT_EQ(body, res->body) << path;
  10990. }
  10991. }
  10992. // A content coding cpp-httplib recognizes but was not built with must be
  10993. // reported as such. Handing the still-compressed payload back to the caller
  10994. // would silently corrupt it.
  10995. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10996. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10997. Server svr;
  10998. // "image/jpeg" keeps the server from applying a content coding of its own,
  10999. // so the hand-crafted Content-Encoding below survives.
  11000. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11001. res.set_content(gzipped, "image/jpeg");
  11002. res.set_header("Content-Encoding", "gzip");
  11003. });
  11004. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11005. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11006. res.set_content(gzipped, "image/jpeg");
  11007. res.set_header("Content-Encoding", "GZIP");
  11008. });
  11009. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11010. auto se = detail::scope_exit([&] {
  11011. svr.stop();
  11012. t.join();
  11013. ASSERT_FALSE(svr.is_running());
  11014. });
  11015. svr.wait_until_ready();
  11016. Client cli(HOST, PORT);
  11017. {
  11018. auto res = cli.Get("/gzipped");
  11019. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11021. EXPECT_EQ("Hello World!", res->body);
  11022. #else
  11023. ASSERT_FALSE(res);
  11024. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11025. #endif
  11026. }
  11027. {
  11028. // open_stream() must behave the same way.
  11029. auto handle = cli.open_stream("GET", "/gzipped");
  11030. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11031. ASSERT_TRUE(handle.is_valid());
  11032. std::string received;
  11033. char buf[256];
  11034. ssize_t n;
  11035. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11036. received.append(buf, static_cast<size_t>(n));
  11037. }
  11038. EXPECT_EQ("Hello World!", received);
  11039. #else
  11040. EXPECT_FALSE(handle.is_valid());
  11041. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11042. #endif
  11043. }
  11044. {
  11045. // A differently-cased coding must not be mistaken for an unknown one, or
  11046. // the body would be handed back still compressed.
  11047. auto res = cli.Get("/gzipped-uppercase");
  11048. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11050. EXPECT_EQ("Hello World!", res->body);
  11051. #else
  11052. ASSERT_FALSE(res);
  11053. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11054. #endif
  11055. }
  11056. }
  11057. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11058. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11059. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11060. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11061. // body a second time and appending a second Content-Encoding field line, so
  11062. // clients that decode one coding per listed value handed back raw gzip bytes.
  11063. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11064. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11065. Server svr;
  11066. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11067. // keeps the server from applying a coding of its own.
  11068. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11069. res.set_content(gzipped, "text/plain");
  11070. res.set_header("Content-Encoding", "gzip");
  11071. });
  11072. auto port = svr.bind_to_any_port(HOST);
  11073. thread t = thread([&]() { svr.listen_after_bind(); });
  11074. auto se = detail::scope_exit([&] {
  11075. svr.stop();
  11076. t.join();
  11077. ASSERT_FALSE(svr.is_running());
  11078. });
  11079. svr.wait_until_ready();
  11080. Client cli(HOST, port);
  11081. Headers headers = {{"Accept-Encoding", "gzip"}};
  11082. auto res = cli.Get("/pre-gzipped", headers);
  11083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11084. EXPECT_EQ(StatusCode::OK_200, res->status);
  11085. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11086. EXPECT_EQ("Hello World!", res->body);
  11087. }
  11088. // A chunked provider settles its coding where the headers are written and
  11089. // reuses it at write time. Both ends of that have to hold: a handler's own
  11090. // Content-Encoding suppresses the coding, and a response without one is still
  11091. // compressed as it always was.
  11092. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11093. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11094. const std::string plain = "Hello World! Hello World! Hello World!";
  11095. Server svr;
  11096. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11097. res.set_header("Content-Encoding", "gzip");
  11098. res.set_chunked_content_provider(
  11099. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11100. sink.write(gzipped.data(), gzipped.size());
  11101. sink.done();
  11102. return true;
  11103. });
  11104. });
  11105. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11106. res.set_chunked_content_provider(
  11107. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11108. sink.write(plain.data(), plain.size());
  11109. sink.done();
  11110. return true;
  11111. });
  11112. });
  11113. auto port = svr.bind_to_any_port(HOST);
  11114. thread t = thread([&]() { svr.listen_after_bind(); });
  11115. auto se = detail::scope_exit([&] {
  11116. svr.stop();
  11117. t.join();
  11118. ASSERT_FALSE(svr.is_running());
  11119. });
  11120. svr.wait_until_ready();
  11121. Client cli(HOST, port);
  11122. Headers headers = {{"Accept-Encoding", "gzip"}};
  11123. {
  11124. auto res = cli.Get("/pre-gzipped", headers);
  11125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11126. EXPECT_EQ(StatusCode::OK_200, res->status);
  11127. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11128. EXPECT_EQ("Hello World!", res->body);
  11129. }
  11130. {
  11131. auto res = cli.Get("/negotiated", headers);
  11132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11133. EXPECT_EQ(StatusCode::OK_200, res->status);
  11134. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11135. EXPECT_EQ(plain, res->body);
  11136. }
  11137. }
  11138. #endif
  11139. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11140. // the same message as the comma-joined one, so both have to be read the same
  11141. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11142. // single gzip coding, and a body the sender says was encoded twice was handed
  11143. // back after one pass, still compressed but presented as decoded.
  11144. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11145. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11146. Server svr;
  11147. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11148. res.set_content(body, "image/jpeg");
  11149. res.headers.emplace("Content-Encoding", "gzip");
  11150. res.headers.emplace("Content-Encoding", "gzip");
  11151. });
  11152. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11153. res.set_content(body, "image/jpeg");
  11154. res.set_header("Content-Encoding", "gzip, gzip");
  11155. });
  11156. auto port = svr.bind_to_any_port(HOST);
  11157. thread t = thread([&]() { svr.listen_after_bind(); });
  11158. auto se = detail::scope_exit([&] {
  11159. svr.stop();
  11160. t.join();
  11161. ASSERT_FALSE(svr.is_running());
  11162. });
  11163. svr.wait_until_ready();
  11164. Client cli(HOST, port);
  11165. // Two codings is not something cpp-httplib decodes, so both representations
  11166. // take the pass-through path rather than one of them being gunzipped once.
  11167. for (const char *path : {"/split", "/joined"}) {
  11168. auto res = cli.Get(path);
  11169. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11170. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11171. EXPECT_EQ(body, res->body) << path;
  11172. }
  11173. }
  11174. // Regression test for DoS vulnerability: a malicious server sending a response
  11175. // without Content-Length header must not cause unbounded memory consumption on
  11176. // the client side. The client should stop reading after a reasonable limit,
  11177. // similar to the server-side set_payload_max_length protection.
  11178. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11179. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11180. #ifndef _WIN32
  11181. signal(SIGPIPE, SIG_IGN);
  11182. #endif
  11183. auto server_thread = std::thread([] {
  11184. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11185. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11186. default_socket_options(srv);
  11187. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11188. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11189. sockaddr_in addr{};
  11190. addr.sin_family = AF_INET;
  11191. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11192. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11193. int opt = 1;
  11194. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11195. #ifdef _WIN32
  11196. reinterpret_cast<const char *>(&opt),
  11197. #else
  11198. &opt,
  11199. #endif
  11200. sizeof(opt));
  11201. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11202. ::listen(srv, 1);
  11203. sockaddr_in cli_addr{};
  11204. socklen_t cli_len = sizeof(cli_addr);
  11205. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11206. if (cli != INVALID_SOCKET) {
  11207. char buf[4096];
  11208. ::recv(cli, buf, sizeof(buf), 0);
  11209. // Malicious response: no Content-Length, no chunked encoding
  11210. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11211. "Connection: close\r\n"
  11212. "\r\n";
  11213. ::send(cli,
  11214. #ifdef _WIN32
  11215. static_cast<const char *>(response_header.c_str()),
  11216. static_cast<int>(response_header.size()),
  11217. #else
  11218. response_header.c_str(), response_header.size(),
  11219. #endif
  11220. 0);
  11221. // Send 10MB of data
  11222. std::string chunk(64 * 1024, 'A');
  11223. size_t total_sent = 0;
  11224. while (total_sent < MALICIOUS_DATA_SIZE) {
  11225. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11226. auto sent = ::send(cli,
  11227. #ifdef _WIN32
  11228. static_cast<const char *>(chunk.c_str()),
  11229. static_cast<int>(to_send),
  11230. #else
  11231. chunk.c_str(), to_send,
  11232. #endif
  11233. 0);
  11234. if (sent <= 0) break;
  11235. total_sent += static_cast<size_t>(sent);
  11236. }
  11237. detail::close_socket(cli);
  11238. }
  11239. detail::close_socket(srv);
  11240. });
  11241. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11242. size_t total_read = 0;
  11243. {
  11244. Client cli("127.0.0.1", PORT + 2);
  11245. cli.set_read_timeout(5, 0);
  11246. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11247. auto stream = cli.open_stream("GET", "/malicious");
  11248. ASSERT_TRUE(stream.is_valid());
  11249. char buffer[64 * 1024];
  11250. ssize_t n;
  11251. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11252. total_read += static_cast<size_t>(n);
  11253. }
  11254. } // StreamHandle and Client destroyed here, closing the socket
  11255. server_thread.join();
  11256. // With set_payload_max_length, the client must stop reading before consuming
  11257. // all 10MB. The read loop should be cut off at or near the configured limit.
  11258. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11259. << "Client read " << total_read << " bytes, exceeding the configured "
  11260. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11261. }
  11262. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11263. // the entire response body without truncation.
  11264. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11265. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11266. #ifndef _WIN32
  11267. signal(SIGPIPE, SIG_IGN);
  11268. #endif
  11269. auto server_thread = std::thread([] {
  11270. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11271. default_socket_options(srv);
  11272. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11273. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11274. sockaddr_in addr{};
  11275. addr.sin_family = AF_INET;
  11276. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11277. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11278. int opt = 1;
  11279. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11280. #ifdef _WIN32
  11281. reinterpret_cast<const char *>(&opt),
  11282. #else
  11283. &opt,
  11284. #endif
  11285. sizeof(opt));
  11286. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11287. ::listen(srv, 1);
  11288. sockaddr_in cli_addr{};
  11289. socklen_t cli_len = sizeof(cli_addr);
  11290. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11291. if (cli != INVALID_SOCKET) {
  11292. char buf[4096];
  11293. ::recv(cli, buf, sizeof(buf), 0);
  11294. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11295. "Connection: close\r\n"
  11296. "\r\n";
  11297. ::send(cli,
  11298. #ifdef _WIN32
  11299. static_cast<const char *>(response_header.c_str()),
  11300. static_cast<int>(response_header.size()),
  11301. #else
  11302. response_header.c_str(), response_header.size(),
  11303. #endif
  11304. 0);
  11305. std::string chunk(64 * 1024, 'A');
  11306. size_t total_sent = 0;
  11307. while (total_sent < DATA_SIZE) {
  11308. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11309. auto sent = ::send(cli,
  11310. #ifdef _WIN32
  11311. static_cast<const char *>(chunk.c_str()),
  11312. static_cast<int>(to_send),
  11313. #else
  11314. chunk.c_str(), to_send,
  11315. #endif
  11316. 0);
  11317. if (sent <= 0) break;
  11318. total_sent += static_cast<size_t>(sent);
  11319. }
  11320. #ifdef _WIN32
  11321. ::shutdown(cli, SD_SEND);
  11322. #else
  11323. ::shutdown(cli, SHUT_WR);
  11324. #endif
  11325. // Drain until the client closes its end, ensuring all data is delivered
  11326. char drain[1024];
  11327. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11328. detail::close_socket(cli);
  11329. }
  11330. detail::close_socket(srv);
  11331. });
  11332. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11333. size_t total_read = 0;
  11334. {
  11335. Client cli("127.0.0.1", PORT + 2);
  11336. cli.set_read_timeout(5, 0);
  11337. cli.set_payload_max_length(0); // 0 means no limit
  11338. auto stream = cli.open_stream("GET", "/data");
  11339. ASSERT_TRUE(stream.is_valid());
  11340. char buffer[64 * 1024];
  11341. ssize_t n;
  11342. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11343. total_read += static_cast<size_t>(n);
  11344. }
  11345. }
  11346. server_thread.join();
  11347. EXPECT_EQ(total_read, DATA_SIZE)
  11348. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11349. << " bytes without truncation, but only read " << total_read << " bytes.";
  11350. }
  11351. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11352. // enormous Content-Length must not cause the client to pre-allocate a huge
  11353. // response body buffer. The reservation is capped at payload_max_length_, and
  11354. // the read itself fails when the body exceeds the limit.
  11355. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11356. #ifndef _WIN32
  11357. signal(SIGPIPE, SIG_IGN);
  11358. #endif
  11359. auto server_thread = std::thread([] {
  11360. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11361. default_socket_options(srv);
  11362. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11363. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11364. sockaddr_in addr{};
  11365. addr.sin_family = AF_INET;
  11366. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11367. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11368. int opt = 1;
  11369. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11370. #ifdef _WIN32
  11371. reinterpret_cast<const char *>(&opt),
  11372. #else
  11373. &opt,
  11374. #endif
  11375. sizeof(opt));
  11376. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11377. ::listen(srv, 1);
  11378. sockaddr_in cli_addr{};
  11379. socklen_t cli_len = sizeof(cli_addr);
  11380. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11381. if (cli != INVALID_SOCKET) {
  11382. char buf[4096];
  11383. ::recv(cli, buf, sizeof(buf), 0);
  11384. // Malicious response: claim a 20GB body but send only a tiny payload.
  11385. std::string response = "HTTP/1.1 200 OK\r\n"
  11386. "Content-Length: 20000000000\r\n"
  11387. "\r\n"
  11388. "abc";
  11389. ::send(cli,
  11390. #ifdef _WIN32
  11391. static_cast<const char *>(response.c_str()),
  11392. static_cast<int>(response.size()),
  11393. #else
  11394. response.c_str(), response.size(),
  11395. #endif
  11396. 0);
  11397. detail::close_socket(cli);
  11398. }
  11399. detail::close_socket(srv);
  11400. });
  11401. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11402. {
  11403. Client cli("127.0.0.1", PORT + 2);
  11404. cli.set_read_timeout(5, 0);
  11405. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11406. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11407. // (server claims more bytes than payload_max_length permits), but it must
  11408. // not exhaust memory before getting there.
  11409. auto res = cli.Get("/malicious");
  11410. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11411. }
  11412. server_thread.join();
  11413. }
  11414. // Verify that content_receiver bypasses the default payload_max_length,
  11415. // allowing streaming downloads larger than 100MB without requiring an explicit
  11416. // set_payload_max_length call.
  11417. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11418. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11419. #ifndef _WIN32
  11420. signal(SIGPIPE, SIG_IGN);
  11421. #endif
  11422. auto server_thread = std::thread([] {
  11423. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11424. default_socket_options(srv);
  11425. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11426. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11427. sockaddr_in addr{};
  11428. addr.sin_family = AF_INET;
  11429. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11430. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11431. int opt = 1;
  11432. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11433. #ifdef _WIN32
  11434. reinterpret_cast<const char *>(&opt),
  11435. #else
  11436. &opt,
  11437. #endif
  11438. sizeof(opt));
  11439. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11440. ::listen(srv, 1);
  11441. sockaddr_in cli_addr{};
  11442. socklen_t cli_len = sizeof(cli_addr);
  11443. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11444. if (cli != INVALID_SOCKET) {
  11445. char buf[4096];
  11446. ::recv(cli, buf, sizeof(buf), 0);
  11447. // Response with Content-Length larger than default 100MB limit
  11448. auto content_length = std::to_string(DATA_SIZE);
  11449. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11450. "Content-Length: " +
  11451. content_length +
  11452. "\r\n"
  11453. "Connection: close\r\n"
  11454. "\r\n";
  11455. ::send(cli,
  11456. #ifdef _WIN32
  11457. static_cast<const char *>(response_header.c_str()),
  11458. static_cast<int>(response_header.size()),
  11459. #else
  11460. response_header.c_str(), response_header.size(),
  11461. #endif
  11462. 0);
  11463. std::string chunk(64 * 1024, 'A');
  11464. size_t total_sent = 0;
  11465. while (total_sent < DATA_SIZE) {
  11466. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11467. auto sent = ::send(cli,
  11468. #ifdef _WIN32
  11469. static_cast<const char *>(chunk.c_str()),
  11470. static_cast<int>(to_send),
  11471. #else
  11472. chunk.c_str(), to_send,
  11473. #endif
  11474. 0);
  11475. if (sent <= 0) break;
  11476. total_sent += static_cast<size_t>(sent);
  11477. }
  11478. detail::close_socket(cli);
  11479. }
  11480. detail::close_socket(srv);
  11481. });
  11482. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11483. size_t total_received = 0;
  11484. {
  11485. Client cli("127.0.0.1", PORT + 2);
  11486. cli.set_read_timeout(10, 0);
  11487. // Do NOT call set_payload_max_length — use the default 100MB limit
  11488. auto res =
  11489. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11490. total_received += data_length;
  11491. return true;
  11492. });
  11493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11494. EXPECT_EQ(StatusCode::OK_200, res->status);
  11495. }
  11496. server_thread.join();
  11497. EXPECT_EQ(total_received, DATA_SIZE)
  11498. << "With content_receiver, the client should read all " << DATA_SIZE
  11499. << " bytes despite the default 100MB payload_max_length, but only read "
  11500. << total_received << " bytes.";
  11501. }
  11502. // Verify that an explicit set_payload_max_length smaller than the response is
  11503. // enforced even when a content_receiver is used.
  11504. TEST(ClientVulnerabilityTest,
  11505. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11506. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11507. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11508. #ifndef _WIN32
  11509. signal(SIGPIPE, SIG_IGN);
  11510. #endif
  11511. auto server_thread = std::thread([] {
  11512. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11513. default_socket_options(srv);
  11514. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11515. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11516. sockaddr_in addr{};
  11517. addr.sin_family = AF_INET;
  11518. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11519. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11520. int opt = 1;
  11521. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11522. #ifdef _WIN32
  11523. reinterpret_cast<const char *>(&opt),
  11524. #else
  11525. &opt,
  11526. #endif
  11527. sizeof(opt));
  11528. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11529. ::listen(srv, 1);
  11530. sockaddr_in cli_addr{};
  11531. socklen_t cli_len = sizeof(cli_addr);
  11532. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11533. if (cli != INVALID_SOCKET) {
  11534. char buf[4096];
  11535. ::recv(cli, buf, sizeof(buf), 0);
  11536. auto content_length = std::to_string(DATA_SIZE);
  11537. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11538. "Content-Length: " +
  11539. content_length +
  11540. "\r\n"
  11541. "Connection: close\r\n"
  11542. "\r\n";
  11543. ::send(cli,
  11544. #ifdef _WIN32
  11545. static_cast<const char *>(response_header.c_str()),
  11546. static_cast<int>(response_header.size()),
  11547. #else
  11548. response_header.c_str(), response_header.size(),
  11549. #endif
  11550. 0);
  11551. std::string chunk(64 * 1024, 'A');
  11552. size_t total_sent = 0;
  11553. while (total_sent < DATA_SIZE) {
  11554. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11555. auto sent = ::send(cli,
  11556. #ifdef _WIN32
  11557. static_cast<const char *>(chunk.c_str()),
  11558. static_cast<int>(to_send),
  11559. #else
  11560. chunk.c_str(), to_send,
  11561. #endif
  11562. 0);
  11563. if (sent <= 0) break;
  11564. total_sent += static_cast<size_t>(sent);
  11565. }
  11566. detail::close_socket(cli);
  11567. }
  11568. detail::close_socket(srv);
  11569. });
  11570. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11571. size_t total_received = 0;
  11572. {
  11573. Client cli("127.0.0.1", PORT + 2);
  11574. cli.set_read_timeout(10, 0);
  11575. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11576. auto res =
  11577. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11578. total_received += data_length;
  11579. return true;
  11580. });
  11581. // Should fail because 200MB exceeds the explicit 150MB limit
  11582. EXPECT_FALSE(res);
  11583. }
  11584. server_thread.join();
  11585. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11586. << "Client with content_receiver should respect the explicit "
  11587. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11588. << total_received << " bytes.";
  11589. }
  11590. // Verify that an explicit set_payload_max_length larger than the response
  11591. // allows the content_receiver to read all data successfully.
  11592. TEST(ClientVulnerabilityTest,
  11593. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11594. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11595. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11596. #ifndef _WIN32
  11597. signal(SIGPIPE, SIG_IGN);
  11598. #endif
  11599. auto server_thread = std::thread([] {
  11600. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11601. default_socket_options(srv);
  11602. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11603. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11604. sockaddr_in addr{};
  11605. addr.sin_family = AF_INET;
  11606. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11607. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11608. int opt = 1;
  11609. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11610. #ifdef _WIN32
  11611. reinterpret_cast<const char *>(&opt),
  11612. #else
  11613. &opt,
  11614. #endif
  11615. sizeof(opt));
  11616. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11617. ::listen(srv, 1);
  11618. sockaddr_in cli_addr{};
  11619. socklen_t cli_len = sizeof(cli_addr);
  11620. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11621. if (cli != INVALID_SOCKET) {
  11622. char buf[4096];
  11623. ::recv(cli, buf, sizeof(buf), 0);
  11624. auto content_length = std::to_string(DATA_SIZE);
  11625. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11626. "Content-Length: " +
  11627. content_length +
  11628. "\r\n"
  11629. "Connection: close\r\n"
  11630. "\r\n";
  11631. ::send(cli,
  11632. #ifdef _WIN32
  11633. static_cast<const char *>(response_header.c_str()),
  11634. static_cast<int>(response_header.size()),
  11635. #else
  11636. response_header.c_str(), response_header.size(),
  11637. #endif
  11638. 0);
  11639. std::string chunk(64 * 1024, 'A');
  11640. size_t total_sent = 0;
  11641. while (total_sent < DATA_SIZE) {
  11642. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11643. auto sent = ::send(cli,
  11644. #ifdef _WIN32
  11645. static_cast<const char *>(chunk.c_str()),
  11646. static_cast<int>(to_send),
  11647. #else
  11648. chunk.c_str(), to_send,
  11649. #endif
  11650. 0);
  11651. if (sent <= 0) break;
  11652. total_sent += static_cast<size_t>(sent);
  11653. }
  11654. #ifdef _WIN32
  11655. ::shutdown(cli, SD_SEND);
  11656. #else
  11657. ::shutdown(cli, SHUT_WR);
  11658. #endif
  11659. char drain[1024];
  11660. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11661. detail::close_socket(cli);
  11662. }
  11663. detail::close_socket(srv);
  11664. });
  11665. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11666. size_t total_received = 0;
  11667. {
  11668. Client cli("127.0.0.1", PORT + 2);
  11669. cli.set_read_timeout(10, 0);
  11670. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11671. auto res =
  11672. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11673. total_received += data_length;
  11674. return true;
  11675. });
  11676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11677. EXPECT_EQ(StatusCode::OK_200, res->status);
  11678. }
  11679. server_thread.join();
  11680. EXPECT_EQ(total_received, DATA_SIZE)
  11681. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11682. << " bytes (larger than " << DATA_SIZE
  11683. << " bytes response), content_receiver should read all data, but only "
  11684. "read "
  11685. << total_received << " bytes.";
  11686. }
  11687. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11688. // Regression test for "zip bomb" attack on the client side: a malicious server
  11689. // sends a small gzip-compressed response that decompresses to a huge payload.
  11690. // The client must enforce payload_max_length on the decompressed size.
  11691. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11692. constexpr size_t DECOMPRESSED_SIZE =
  11693. 10 * 1024 * 1024; // 10MB after decompression
  11694. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11695. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11696. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11697. std::string compressed;
  11698. {
  11699. httplib::detail::gzip_compressor compressor;
  11700. bool ok =
  11701. compressor.compress(uncompressed.data(), uncompressed.size(),
  11702. /*last=*/true, [&](const char *buf, size_t len) {
  11703. compressed.append(buf, len);
  11704. return true;
  11705. });
  11706. ASSERT_TRUE(ok);
  11707. }
  11708. // Sanity: compressed data should be much smaller than the decompressed size
  11709. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11710. #ifndef _WIN32
  11711. signal(SIGPIPE, SIG_IGN);
  11712. #endif
  11713. // Set up the listening socket in the main thread so the server is guaranteed
  11714. // to be ready before the client connects (eliminates race condition).
  11715. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11716. default_socket_options(srv);
  11717. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11718. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11719. sockaddr_in addr{};
  11720. addr.sin_family = AF_INET;
  11721. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11722. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11723. int opt = 1;
  11724. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11725. #ifdef _WIN32
  11726. reinterpret_cast<const char *>(&opt),
  11727. #else
  11728. &opt,
  11729. #endif
  11730. sizeof(opt));
  11731. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11732. ASSERT_EQ(0, ::listen(srv, 1));
  11733. auto server_thread = std::thread([&compressed, srv] {
  11734. sockaddr_in cli_addr{};
  11735. socklen_t cli_len = sizeof(cli_addr);
  11736. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11737. if (cli != INVALID_SOCKET) {
  11738. // Read the full HTTP request (until \r\n\r\n)
  11739. char buf[4096];
  11740. size_t total = 0;
  11741. while (total < sizeof(buf)) {
  11742. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11743. if (n <= 0) break;
  11744. total += static_cast<size_t>(n);
  11745. // Check for end of headers
  11746. if (total >= 4) {
  11747. std::string req(buf, total);
  11748. if (req.find("\r\n\r\n") != std::string::npos) break;
  11749. }
  11750. }
  11751. // Malicious response: gzip-compressed body, no Content-Length
  11752. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11753. "Content-Encoding: gzip\r\n"
  11754. "Connection: close\r\n"
  11755. "\r\n";
  11756. ::send(cli,
  11757. #ifdef _WIN32
  11758. static_cast<const char *>(response_header.c_str()),
  11759. static_cast<int>(response_header.size()),
  11760. #else
  11761. response_header.c_str(), response_header.size(),
  11762. #endif
  11763. 0);
  11764. // Send the compressed payload (small on the wire, huge when decompressed)
  11765. size_t total_sent = 0;
  11766. while (total_sent < compressed.size()) {
  11767. auto to_send = std::min(compressed.size() - total_sent,
  11768. static_cast<size_t>(64 * 1024));
  11769. auto sent =
  11770. ::send(cli,
  11771. #ifdef _WIN32
  11772. static_cast<const char *>(compressed.c_str() + total_sent),
  11773. static_cast<int>(to_send),
  11774. #else
  11775. compressed.c_str() + total_sent, to_send,
  11776. #endif
  11777. 0);
  11778. if (sent <= 0) break;
  11779. total_sent += static_cast<size_t>(sent);
  11780. }
  11781. detail::close_socket(cli);
  11782. }
  11783. });
  11784. auto se = detail::scope_exit([&] {
  11785. detail::close_socket(srv);
  11786. server_thread.join();
  11787. });
  11788. size_t total_decompressed = 0;
  11789. {
  11790. Client cli("127.0.0.1", PORT + 3);
  11791. cli.set_read_timeout(5, 0);
  11792. cli.set_decompress(true);
  11793. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11794. auto stream = cli.open_stream("GET", "/zipbomb");
  11795. ASSERT_TRUE(stream.is_valid());
  11796. char buffer[64 * 1024];
  11797. ssize_t n;
  11798. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11799. total_decompressed += static_cast<size_t>(n);
  11800. }
  11801. }
  11802. // The decompressed size must be capped by payload_max_length. Without
  11803. // protection, the client would decompress the full 10MB from a tiny
  11804. // compressed payload, enabling a zip bomb DoS attack.
  11805. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11806. << "Client decompressed " << total_decompressed
  11807. << " bytes from a gzip response. The decompressed size should be "
  11808. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11809. }
  11810. #endif
  11811. TEST(HostAndPortPropertiesTest, NoSSL) {
  11812. httplib::Client cli("www.google.com", 1234);
  11813. ASSERT_EQ("www.google.com", cli.host());
  11814. ASSERT_EQ(1234, cli.port());
  11815. }
  11816. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11817. httplib::Client cli("www.google.com:1234");
  11818. ASSERT_EQ("www.google.com", cli.host());
  11819. ASSERT_EQ(1234, cli.port());
  11820. }
  11821. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11822. // Port number that overflows int — should not crash, client becomes invalid
  11823. httplib::Client cli("http://www.google.com:99999999999999999999");
  11824. ASSERT_FALSE(cli.is_valid());
  11825. }
  11826. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11827. // Port 99999 exceeds valid range (1-65535) — should not crash
  11828. httplib::Client cli("http://www.google.com:99999");
  11829. ASSERT_FALSE(cli.is_valid());
  11830. }
  11831. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  11832. httplib::Client cli("http://www.google.com:80abc");
  11833. ASSERT_FALSE(cli.is_valid());
  11834. }
  11835. #ifdef CPPHTTPLIB_SSL_ENABLED
  11836. TEST(HostAndPortPropertiesTest, SSL) {
  11837. httplib::SSLClient cli("www.google.com");
  11838. ASSERT_EQ("www.google.com", cli.host());
  11839. ASSERT_EQ(443, cli.port());
  11840. }
  11841. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11842. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11843. std::string cert;
  11844. read_file(CA_CERT_FILE, cert);
  11845. httplib::SSLClient httplib_client("www.google.com");
  11846. // Load CA store first time
  11847. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11848. // Load CA store second time (update)
  11849. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11850. // Verify client is still valid and can make connections
  11851. httplib_client.enable_server_certificate_verification(true);
  11852. auto res = httplib_client.Get("/");
  11853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11854. // Google may return 200 or 301 depending on various factors
  11855. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11856. res->status == StatusCode::MovedPermanently_301);
  11857. }
  11858. TEST(SSLClientTest, ServerNameIndication_Online) {
  11859. auto host = "httpbingo.org";
  11860. auto path = std::string{"/get"};
  11861. SSLClient cli(host, 443);
  11862. auto res = cli.Get(path);
  11863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11864. ASSERT_EQ(StatusCode::OK_200, res->status);
  11865. }
  11866. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11867. // Use a site that will cause SSL verification failure due to self-signed cert
  11868. SSLClient cli("self-signed.badssl.com", 443);
  11869. cli.enable_server_certificate_verification(true);
  11870. auto res = cli.Get("/");
  11871. ASSERT_TRUE(!res);
  11872. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11873. // Verify backend error is captured for SSLServerVerification
  11874. // This occurs when certificate verification fails
  11875. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11876. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11877. EXPECT_NE(0UL, res.ssl_backend_error());
  11878. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11879. // For OpenSSL, ssl_error is 0 for verification errors
  11880. EXPECT_EQ(0, res.ssl_error());
  11881. #if !defined(_WIN32) || \
  11882. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11883. // On non-Windows or when Windows Schannel is disabled, the error comes
  11884. // from OpenSSL's verification
  11885. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11886. res.ssl_backend_error());
  11887. #endif
  11888. #endif
  11889. }
  11890. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11891. // Use a site where hostname doesn't match the certificate
  11892. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11893. SSLClient cli("wrong.host.badssl.com", 443);
  11894. cli.enable_server_certificate_verification(true);
  11895. cli.enable_server_hostname_verification(true);
  11896. auto res = cli.Get("/");
  11897. ASSERT_TRUE(!res);
  11898. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11899. // Verify backend error is captured for hostname verification failure
  11900. EXPECT_NE(0UL, res.ssl_backend_error());
  11901. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11902. // For OpenSSL, ssl_error is 0 for verification errors
  11903. EXPECT_EQ(0, res.ssl_error());
  11904. #if !defined(_WIN32) || \
  11905. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11906. // On non-Windows or when Windows Schannel is disabled, the error comes
  11907. // from OpenSSL's hostname verification
  11908. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11909. res.ssl_backend_error());
  11910. #endif
  11911. #endif
  11912. }
  11913. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11914. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11915. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11916. SSLClient cli("www.google.com", 443);
  11917. cli.enable_server_certificate_verification(true);
  11918. auto res = cli.Get("/");
  11919. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11920. }
  11921. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11922. SSLClient cli("www.google.com", 443);
  11923. cli.enable_server_certificate_verification(true);
  11924. cli.enable_windows_certificate_verification(false);
  11925. auto res = cli.Get("/");
  11926. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11927. }
  11928. // The server sends an intermediate cross-signed by a root Windows trusts,
  11929. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  11930. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  11931. SSLClient cli("accounts.spotify.com", 443);
  11932. auto res = cli.Get("/");
  11933. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  11934. << " ssl_backend_error=" << res.ssl_backend_error();
  11935. }
  11936. // Windows, not the backend, decides on the chain: the error carries a
  11937. // CryptoAPI trust status, which no backend error for a self-signed
  11938. // certificate has.
  11939. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  11940. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11941. ASSERT_TRUE(svr.is_valid());
  11942. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11943. auto se = detail::scope_exit([&] {
  11944. svr.stop();
  11945. t.join();
  11946. ASSERT_FALSE(svr.is_running());
  11947. });
  11948. svr.wait_until_ready();
  11949. SSLClient cli("127.0.0.1", PORT);
  11950. cli.set_connection_timeout(30);
  11951. auto res = cli.Get("/");
  11952. ASSERT_FALSE(res);
  11953. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11954. EXPECT_NE(0u, res.ssl_backend_error() & CERT_TRUST_IS_UNTRUSTED_ROOT)
  11955. << "ssl_backend_error=" << res.ssl_backend_error();
  11956. }
  11957. #endif
  11958. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11959. Client cli("https://google.com");
  11960. auto res = cli.Get("/");
  11961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11962. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11963. }
  11964. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11965. SSLClient cli("google.com");
  11966. cli.set_ca_cert_path(CA_CERT_FILE);
  11967. auto res = cli.Get("/");
  11968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11969. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11970. }
  11971. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11972. SSLClient cli("google.com");
  11973. cli.enable_server_certificate_verification(true);
  11974. cli.set_ca_cert_path("hello");
  11975. auto res = cli.Get("/");
  11976. ASSERT_TRUE(!res);
  11977. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11978. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11979. // should be set
  11980. EXPECT_EQ(0, res.ssl_error());
  11981. // Verify backend error is captured for SSLLoadingCerts
  11982. // This error occurs when loading CA certificates fails
  11983. EXPECT_NE(0UL, res.ssl_backend_error());
  11984. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11985. // OpenSSL specific error codes:
  11986. // > openssl errstr 0x80000002
  11987. // error:80000002:system library::No such file or directory
  11988. // > openssl errstr 0xA000126
  11989. // error:0A000126:SSL routines::unexpected eof while reading
  11990. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11991. res.ssl_backend_error() == 0xA000126);
  11992. #endif
  11993. }
  11994. TEST(SSLClientTest, ServerCertificateVerification4) {
  11995. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11996. ASSERT_TRUE(svr.is_valid());
  11997. svr.Get("/test", [&](const Request &, Response &res) {
  11998. res.set_content("test", "text/plain");
  11999. svr.stop();
  12000. ASSERT_TRUE(true);
  12001. });
  12002. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12003. auto se = detail::scope_exit([&] {
  12004. t.join();
  12005. ASSERT_FALSE(svr.is_running());
  12006. });
  12007. svr.wait_until_ready();
  12008. SSLClient cli("127.0.0.1", PORT);
  12009. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12010. cli.enable_server_certificate_verification(true);
  12011. cli.set_connection_timeout(30);
  12012. auto res = cli.Get("/test");
  12013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12014. ASSERT_EQ(StatusCode::OK_200, res->status);
  12015. }
  12016. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12017. std::string cert;
  12018. read_file(CA_CERT_FILE, cert);
  12019. SSLClient cli("google.com");
  12020. cli.load_ca_cert_store(cert.data(), cert.size());
  12021. const auto res = cli.Get("/");
  12022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12023. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12024. }
  12025. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12026. // clang-format off
  12027. static constexpr char cert[] =
  12028. "GlobalSign Root CA\n"
  12029. "==================\n"
  12030. "-----BEGIN CERTIFICATE-----\n"
  12031. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12032. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12033. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12034. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12035. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12036. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12037. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12038. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12039. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12040. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12041. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12042. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12043. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12044. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12045. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12046. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12047. "-----END CERTIFICATE-----\n";
  12048. // clang-format on
  12049. SSLClient cli("google.com");
  12050. cli.load_ca_cert_store(cert, sizeof(cert));
  12051. const auto res = cli.Get("/");
  12052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12053. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12054. }
  12055. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12056. SSLClient cli("www.youtube.com");
  12057. cli.set_ca_cert_path(CA_CERT_FILE);
  12058. cli.enable_server_certificate_verification(true);
  12059. cli.set_follow_location(true);
  12060. auto res = cli.Get("/");
  12061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12062. ASSERT_EQ(StatusCode::OK_200, res->status);
  12063. }
  12064. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12065. SSLClient cli("wWw.YouTube.Com");
  12066. cli.set_ca_cert_path(CA_CERT_FILE);
  12067. cli.enable_server_certificate_verification(true);
  12068. cli.enable_server_hostname_verification(true);
  12069. cli.set_follow_location(true);
  12070. auto res = cli.Get("/");
  12071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12072. ASSERT_EQ(StatusCode::OK_200, res->status);
  12073. }
  12074. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12075. SSLClient cli("gOoGlE.COm");
  12076. cli.enable_server_certificate_verification(true);
  12077. cli.enable_server_hostname_verification(true);
  12078. cli.set_follow_location(true);
  12079. auto res = cli.Get("/");
  12080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12081. ASSERT_EQ(StatusCode::OK_200, res->status);
  12082. }
  12083. TEST(SSLClientTest, Issue2004_Online) {
  12084. Client client("https://google.com");
  12085. client.set_follow_location(true);
  12086. auto res = client.Get("/");
  12087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12088. ASSERT_EQ(StatusCode::OK_200, res->status);
  12089. auto body = res->body;
  12090. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12091. }
  12092. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12093. // Create SSLClient with invalid cert/key to make is_valid() return false
  12094. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12095. "nonexistent_key.pem");
  12096. // is_valid() should be false due to cert loading failure
  12097. ASSERT_FALSE(cli.is_valid());
  12098. auto res = cli.Get("/");
  12099. ASSERT_FALSE(res);
  12100. EXPECT_EQ(Error::SSLConnection, res.error());
  12101. }
  12102. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12103. // Test for Issue #2251: SSL error not properly reported when client cert
  12104. // and key paths are swapped or mismatched
  12105. // This simulates the scenario where user accidentally swaps the cert and key
  12106. // files
  12107. // Using client cert file as private key and vice versa (completely wrong)
  12108. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12109. // Should fail validation due to cert/key mismatch
  12110. ASSERT_FALSE(cli.is_valid());
  12111. // Attempt to make a request should fail with proper error
  12112. auto res = cli.Get("/");
  12113. ASSERT_FALSE(res);
  12114. EXPECT_EQ(Error::SSLConnection, res.error());
  12115. // SSL error should be recorded in the Result object (this is the key fix for
  12116. // Issue #2251)
  12117. auto backend_error = res.ssl_backend_error();
  12118. EXPECT_NE(0u, backend_error);
  12119. }
  12120. // Tests cert/key mismatch detection at the TLS context level
  12121. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12122. // Test that using mismatched cert/key causes connection failure.
  12123. // We verify this at the SSLClient level rather than through internal
  12124. // TLS API functions.
  12125. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12126. cli.enable_server_certificate_verification(false);
  12127. cli.set_connection_timeout(2);
  12128. // The mismatch should cause a connection or handshake error
  12129. auto res = cli.Get("/test");
  12130. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12131. // Either way, the request should fail
  12132. EXPECT_FALSE(res);
  12133. }
  12134. #endif
  12135. #if 0
  12136. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12137. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12138. ASSERT_TRUE(cli != nullptr);
  12139. cli->set_address_family(AF_INET6);
  12140. cli->set_interface("en0");
  12141. auto res = cli->Get("/get");
  12142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12143. ASSERT_EQ(StatusCode::OK_200, res->status);
  12144. }
  12145. #endif
  12146. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12147. #ifdef CPPHTTPLIB_SSL_ENABLED
  12148. void ClientCertPresent(
  12149. const std::string &client_cert_file,
  12150. const std::string &client_private_key_file,
  12151. const std::string &client_encrypted_private_key_pass = std::string()) {
  12152. using namespace httplib::tls;
  12153. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12154. CLIENT_CA_CERT_DIR);
  12155. ASSERT_TRUE(svr.is_valid());
  12156. svr.Get("/test", [&](const Request &req, Response &res) {
  12157. res.set_content("test", "text/plain");
  12158. auto cert = req.peer_cert();
  12159. ASSERT_TRUE(static_cast<bool>(cert));
  12160. std::string common_name = cert.subject_cn();
  12161. EXPECT_EQ("Common Name", common_name);
  12162. });
  12163. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12164. auto se = detail::scope_exit([&] {
  12165. svr.stop();
  12166. t.join();
  12167. ASSERT_FALSE(svr.is_running());
  12168. });
  12169. svr.wait_until_ready();
  12170. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12171. client_encrypted_private_key_pass);
  12172. cli.enable_server_certificate_verification(false);
  12173. cli.set_connection_timeout(30);
  12174. auto res = cli.Get("/test");
  12175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12176. ASSERT_EQ(StatusCode::OK_200, res->status);
  12177. }
  12178. TEST(SSLClientServerTest, ClientCertPresent) {
  12179. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12180. }
  12181. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12182. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12183. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12184. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12185. }
  12186. // PEM memory-based constructor tests (works with all TLS backends)
  12187. void PemMemoryClientCertPresent(
  12188. const std::string &client_cert_file,
  12189. const std::string &client_private_key_file,
  12190. const std::string &client_encrypted_private_key_pass = std::string()) {
  12191. // Read PEM files into memory
  12192. std::string server_cert_pem, server_key_pem;
  12193. std::string client_ca_pem;
  12194. std::string client_cert_pem, client_key_pem;
  12195. read_file(SERVER_CERT_FILE, server_cert_pem);
  12196. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12197. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12198. read_file(client_cert_file, client_cert_pem);
  12199. read_file(client_private_key_file, client_key_pem);
  12200. // Create server with PEM memory
  12201. SSLServer::PemMemory server_pem = {
  12202. server_cert_pem.c_str(),
  12203. server_cert_pem.size(),
  12204. server_key_pem.c_str(),
  12205. server_key_pem.size(),
  12206. client_ca_pem.c_str(),
  12207. client_ca_pem.size(),
  12208. nullptr // no password for server key
  12209. };
  12210. SSLServer svr(server_pem);
  12211. ASSERT_TRUE(svr.is_valid());
  12212. svr.Get("/test", [&](const Request &, Response &res) {
  12213. res.set_content("test", "text/plain");
  12214. });
  12215. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12216. auto se = detail::scope_exit([&] {
  12217. svr.stop();
  12218. t.join();
  12219. ASSERT_FALSE(svr.is_running());
  12220. });
  12221. svr.wait_until_ready();
  12222. // Create client with PEM memory
  12223. const char *password = client_encrypted_private_key_pass.empty()
  12224. ? nullptr
  12225. : client_encrypted_private_key_pass.c_str();
  12226. SSLClient::PemMemory client_pem = {
  12227. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12228. client_key_pem.size(), password};
  12229. SSLClient cli(HOST, PORT, client_pem);
  12230. cli.enable_server_certificate_verification(false);
  12231. cli.set_connection_timeout(30);
  12232. auto res = cli.Get("/test");
  12233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12234. ASSERT_EQ(StatusCode::OK_200, res->status);
  12235. }
  12236. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12237. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12238. }
  12239. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12240. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12241. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12242. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12243. }
  12244. TEST(SSLClientServerTest, ClientCertMissing) {
  12245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12246. CLIENT_CA_CERT_DIR);
  12247. ASSERT_TRUE(svr.is_valid());
  12248. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12249. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12250. auto se = detail::scope_exit([&] {
  12251. svr.stop();
  12252. t.join();
  12253. ASSERT_FALSE(svr.is_running());
  12254. });
  12255. svr.wait_until_ready();
  12256. SSLClient cli(HOST, PORT);
  12257. cli.set_connection_timeout(30);
  12258. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12259. // the chain check on Windows, so the result does not depend on the order.
  12260. cli.enable_server_hostname_verification(false);
  12261. auto res = cli.Get("/test");
  12262. ASSERT_TRUE(!res);
  12263. // When client cert is missing and server requires it, connection fails
  12264. // Error type depends on backend implementation
  12265. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12266. res.error() == Error::SSLConnection);
  12267. // Verify backend error is captured
  12268. // Note: This test may have different error codes depending on the exact
  12269. // verification failure
  12270. EXPECT_NE(0UL, res.ssl_backend_error());
  12271. }
  12272. TEST(SSLClientServerTest, TrustDirOptional) {
  12273. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12274. ASSERT_TRUE(svr.is_valid());
  12275. svr.Get("/test", [&](const Request &, Response &res) {
  12276. res.set_content("test", "text/plain");
  12277. });
  12278. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12279. auto se = detail::scope_exit([&] {
  12280. svr.stop();
  12281. t.join();
  12282. ASSERT_FALSE(svr.is_running());
  12283. });
  12284. svr.wait_until_ready();
  12285. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12286. cli.enable_server_certificate_verification(false);
  12287. cli.set_connection_timeout(30);
  12288. auto res = cli.Get("/test");
  12289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12290. ASSERT_EQ(StatusCode::OK_200, res->status);
  12291. }
  12292. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12293. class NoListenSSLServer : public SSLServer {
  12294. public:
  12295. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12296. const char *client_ca_cert_file_path,
  12297. const char *client_ca_cert_dir_path = nullptr)
  12298. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12299. client_ca_cert_dir_path),
  12300. stop_(false) {}
  12301. std::atomic_bool stop_;
  12302. private:
  12303. bool process_and_close_socket(socket_t /*sock*/) override {
  12304. // Don't create SSL context
  12305. while (!stop_.load()) {
  12306. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12307. }
  12308. return true;
  12309. }
  12310. };
  12311. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12312. CLIENT_CA_CERT_FILE);
  12313. ASSERT_TRUE(svr.is_valid());
  12314. svr.Get("/test", [&](const Request &, Response &res) {
  12315. res.set_content("test", "text/plain");
  12316. });
  12317. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12318. auto se = detail::scope_exit([&] {
  12319. svr.stop_ = true;
  12320. svr.stop();
  12321. t.join();
  12322. ASSERT_FALSE(svr.is_running());
  12323. });
  12324. svr.wait_until_ready();
  12325. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12326. cli.enable_server_certificate_verification(false);
  12327. cli.set_connection_timeout(1);
  12328. auto res = cli.Get("/test");
  12329. ASSERT_TRUE(!res);
  12330. EXPECT_EQ(Error::SSLConnection, res.error());
  12331. // Timeout results in WantRead error code (maps to backend-specific value)
  12332. EXPECT_NE(0, res.ssl_error());
  12333. }
  12334. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12335. // Test SSLServer with client certificate verification using the standard
  12336. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12337. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12338. CLIENT_CA_CERT_DIR);
  12339. ASSERT_TRUE(svr.is_valid());
  12340. svr.Get("/test", [&](const Request &req, Response &res) {
  12341. res.set_content("test", "text/plain");
  12342. auto cert = req.peer_cert();
  12343. ASSERT_TRUE(static_cast<bool>(cert));
  12344. auto common_name = cert.subject_cn();
  12345. EXPECT_EQ("Common Name", common_name);
  12346. });
  12347. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12348. auto se = detail::scope_exit([&] {
  12349. svr.stop();
  12350. t.join();
  12351. ASSERT_FALSE(svr.is_running());
  12352. });
  12353. svr.wait_until_ready();
  12354. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12355. cli.enable_server_certificate_verification(false);
  12356. cli.set_connection_timeout(30);
  12357. auto res = cli.Get("/test");
  12358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12359. ASSERT_EQ(StatusCode::OK_200, res->status);
  12360. }
  12361. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12362. // Verifies that wildcard matching and exact matching work consistently
  12363. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12364. using namespace httplib::tls;
  12365. // We need a running server to test against
  12366. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12367. ASSERT_TRUE(svr.is_valid());
  12368. svr.Get("/test", [](const Request &, Response &res) {
  12369. res.set_content("ok", "text/plain");
  12370. });
  12371. thread t([&]() { svr.listen(HOST, PORT); });
  12372. auto se = detail::scope_exit([&] {
  12373. svr.stop();
  12374. t.join();
  12375. });
  12376. svr.wait_until_ready();
  12377. bool verify_callback_called = false;
  12378. bool verify_result_wrong = false;
  12379. SSLClient cli(HOST, PORT);
  12380. cli.enable_server_certificate_verification(true);
  12381. cli.set_ca_cert_path(CA_CERT_FILE);
  12382. cli.set_connection_timeout(5);
  12383. // Note: Test certificate has CN="Common Name", not "localhost"
  12384. bool verify_result_cn = false;
  12385. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12386. verify_callback_called = true;
  12387. if (!ctx.cert) return false;
  12388. // Test 1: "Common Name" should match (our test server cert CN)
  12389. verify_result_cn = ctx.check_hostname("Common Name");
  12390. // Test 2: wrong hostname should not match
  12391. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12392. return true; // Accept for the purpose of this test
  12393. });
  12394. auto res = cli.Get("/test");
  12395. // The request may succeed or fail depending on cert configuration
  12396. // but the callback should have been called
  12397. ASSERT_TRUE(verify_callback_called)
  12398. << "Verify callback should have been called";
  12399. // CN="Common Name" should match our test certificate
  12400. //
  12401. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12402. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12403. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12404. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12405. // <openssl/base.h>, which is included transitively when
  12406. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12407. #if defined(OPENSSL_IS_BORINGSSL)
  12408. EXPECT_FALSE(verify_result_cn)
  12409. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12410. #else
  12411. EXPECT_TRUE(verify_result_cn)
  12412. << "verify_hostname should match 'Common Name' (certificate CN)";
  12413. #endif
  12414. // Wrong hostname should not match
  12415. EXPECT_FALSE(verify_result_wrong)
  12416. << "verify_hostname should not match 'wronghost.example.com'";
  12417. }
  12418. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12419. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12420. // X509_check_ip behavior and must hold for every backend.
  12421. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12422. using namespace httplib::tls;
  12423. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12424. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12425. ASSERT_TRUE(svr.is_valid());
  12426. svr.Get("/test", [](const Request &, Response &res) {
  12427. res.set_content("ok", "text/plain");
  12428. });
  12429. thread t([&]() { svr.listen(HOST, PORT); });
  12430. auto se = detail::scope_exit([&] {
  12431. svr.stop();
  12432. t.join();
  12433. });
  12434. svr.wait_until_ready();
  12435. bool verify_callback_called = false;
  12436. bool ip_matched_via_cn = true;
  12437. SSLClient cli(HOST, PORT);
  12438. cli.enable_server_certificate_verification(true);
  12439. cli.set_ca_cert_path(CA_CERT_FILE);
  12440. cli.set_connection_timeout(5);
  12441. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12442. verify_callback_called = true;
  12443. if (!ctx.cert) return false;
  12444. // The IP appears only in the CN, so it must NOT be accepted.
  12445. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12446. return true; // Accept for the purpose of this test
  12447. });
  12448. cli.Get("/test");
  12449. ASSERT_TRUE(verify_callback_called)
  12450. << "Verify callback should have been called";
  12451. EXPECT_FALSE(ip_matched_via_cn)
  12452. << "An IP host must not be authenticated via the certificate CN";
  12453. }
  12454. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12455. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12456. using namespace httplib::tls;
  12457. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12458. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12459. ASSERT_TRUE(svr.is_valid());
  12460. svr.Get("/test", [](const Request &, Response &res) {
  12461. res.set_content("ok", "text/plain");
  12462. });
  12463. thread t([&]() { svr.listen(HOST, PORT); });
  12464. auto se = detail::scope_exit([&] {
  12465. svr.stop();
  12466. t.join();
  12467. });
  12468. svr.wait_until_ready();
  12469. bool verify_callback_called = false;
  12470. bool san_matched = false;
  12471. bool wrong_ipv6_matched = true;
  12472. bool cn_ipv6_matched = true;
  12473. SSLClient cli(HOST, PORT);
  12474. cli.enable_server_certificate_verification(true);
  12475. cli.set_ca_cert_path(CA_CERT_FILE);
  12476. cli.set_connection_timeout(5);
  12477. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12478. verify_callback_called = true;
  12479. if (!ctx.cert) return false;
  12480. // Matches the IPv6 iPAddress SAN.
  12481. san_matched = ctx.check_hostname("2001:db8::1");
  12482. // A different IPv6 address must not match.
  12483. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12484. // "::1" lives only in the CN, so it must not be accepted.
  12485. cn_ipv6_matched = ctx.check_hostname("::1");
  12486. return true; // Accept for the purpose of this test
  12487. });
  12488. cli.Get("/test");
  12489. ASSERT_TRUE(verify_callback_called)
  12490. << "Verify callback should have been called";
  12491. EXPECT_TRUE(san_matched)
  12492. << "verify_hostname should match an IPv6 iPAddress SAN";
  12493. EXPECT_FALSE(wrong_ipv6_matched)
  12494. << "verify_hostname should not match a non-matching IPv6 address";
  12495. EXPECT_FALSE(cn_ipv6_matched)
  12496. << "An IPv6 host must not be authenticated via the certificate CN";
  12497. }
  12498. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12499. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12500. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12501. using namespace httplib::tls;
  12502. // SANs: DNS:a.zz, IP:42.46.122.122
  12503. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12504. ASSERT_TRUE(svr.is_valid());
  12505. svr.Get("/test", [](const Request &, Response &res) {
  12506. res.set_content("ok", "text/plain");
  12507. });
  12508. auto port = svr.bind_to_any_port(HOST);
  12509. thread t([&]() { svr.listen_after_bind(); });
  12510. auto se = detail::scope_exit([&] {
  12511. svr.stop();
  12512. t.join();
  12513. });
  12514. svr.wait_until_ready();
  12515. bool verify_callback_called = false;
  12516. bool dns_san_matched = false;
  12517. bool ip_san_matched = false;
  12518. bool ip_matched_via_dns_san = true;
  12519. bool dns_matched_via_ip_san = true;
  12520. SSLClient cli(HOST, port);
  12521. cli.enable_server_certificate_verification(true);
  12522. cli.set_ca_cert_path(CA_CERT_FILE);
  12523. cli.set_connection_timeout(5);
  12524. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12525. verify_callback_called = true;
  12526. if (!ctx.cert) return false;
  12527. dns_san_matched = ctx.check_hostname("a.zz");
  12528. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12529. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12530. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12531. return true; // Accept for the purpose of this test
  12532. });
  12533. cli.Get("/test");
  12534. ASSERT_TRUE(verify_callback_called)
  12535. << "Verify callback should have been called";
  12536. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12537. EXPECT_TRUE(ip_san_matched)
  12538. << "verify_hostname should match an iPAddress SAN";
  12539. EXPECT_FALSE(ip_matched_via_dns_san)
  12540. << "An IP host must not be authenticated via a dNSName SAN";
  12541. EXPECT_FALSE(dns_matched_via_ip_san)
  12542. << "A DNS host must not be authenticated via an iPAddress SAN";
  12543. }
  12544. // sans() must report each SAN entry under its own type.
  12545. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  12546. using namespace httplib::tls;
  12547. // SANs: DNS:a.zz, IP:42.46.122.122
  12548. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12549. ASSERT_TRUE(svr.is_valid());
  12550. svr.Get("/test", [](const Request &, Response &res) {
  12551. res.set_content("ok", "text/plain");
  12552. });
  12553. auto port = svr.bind_to_any_port(HOST);
  12554. thread t([&]() { svr.listen_after_bind(); });
  12555. auto se = detail::scope_exit([&] {
  12556. svr.stop();
  12557. t.join();
  12558. });
  12559. svr.wait_until_ready();
  12560. bool verify_callback_called = false;
  12561. std::vector<SanEntry> sans;
  12562. SSLClient cli(HOST, port);
  12563. cli.enable_server_certificate_verification(true);
  12564. cli.set_ca_cert_path(CA_CERT_FILE);
  12565. cli.set_connection_timeout(5);
  12566. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12567. verify_callback_called = true;
  12568. if (!ctx.cert) return false;
  12569. sans = ctx.sans();
  12570. return true; // Accept for the purpose of this test
  12571. });
  12572. cli.Get("/test");
  12573. ASSERT_TRUE(verify_callback_called)
  12574. << "Verify callback should have been called";
  12575. auto has_san = [&](SanType type, const std::string &value) {
  12576. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  12577. return san.type == type && san.value == value;
  12578. });
  12579. };
  12580. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  12581. << "sans() should report the dNSName SAN";
  12582. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  12583. << "sans() should report the iPAddress SAN";
  12584. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  12585. << "sans() must not report the dNSName SAN as an address";
  12586. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  12587. << "sans() must not report the iPAddress SAN as a DNS name";
  12588. }
  12589. #endif
  12590. // mbedTLS-specific callback constructor test
  12591. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12592. #ifdef CPPHTTPLIB_SSL_ENABLED
  12593. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12594. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12595. ASSERT_TRUE(svr.is_valid());
  12596. // Set up a handler to verify client certificate is present
  12597. bool client_cert_verified = false;
  12598. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12599. // Verify that client certificate was provided
  12600. client_cert_verified = true;
  12601. res.set_content("success", "text/plain");
  12602. });
  12603. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12604. auto se = detail::scope_exit([&] {
  12605. svr.stop();
  12606. t.join();
  12607. ASSERT_FALSE(svr.is_running());
  12608. });
  12609. svr.wait_until_ready();
  12610. // Client with certificate
  12611. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12612. cli.enable_server_certificate_verification(false);
  12613. cli.set_connection_timeout(30);
  12614. auto res = cli.Get("/test");
  12615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12616. ASSERT_EQ(StatusCode::OK_200, res->status);
  12617. ASSERT_TRUE(client_cert_verified);
  12618. EXPECT_EQ("success", res->body);
  12619. }
  12620. #endif
  12621. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12622. // backends
  12623. #ifdef CPPHTTPLIB_SSL_ENABLED
  12624. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12625. using namespace httplib::tls;
  12626. // Test that when client CA cert file is provided,
  12627. // the server properly requests and validates client certificates
  12628. // Create a server with client authentication
  12629. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12630. ASSERT_TRUE(svr.is_valid());
  12631. bool handler_called = false;
  12632. svr.Get("/test", [&](const Request &req, Response &res) {
  12633. handler_called = true;
  12634. // Verify that a client certificate was provided
  12635. auto cert = req.peer_cert();
  12636. ASSERT_TRUE(static_cast<bool>(cert));
  12637. // Get the issuer name
  12638. std::string issuer_str = cert.issuer_name();
  12639. ASSERT_FALSE(issuer_str.empty());
  12640. // The client certificate should be issued by our test CA
  12641. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12642. res.set_content("authenticated", "text/plain");
  12643. });
  12644. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12645. auto se = detail::scope_exit([&] {
  12646. svr.stop();
  12647. t.join();
  12648. ASSERT_FALSE(svr.is_running());
  12649. });
  12650. svr.wait_until_ready();
  12651. // Connect with a client certificate issued by the CA
  12652. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12653. cli.enable_server_certificate_verification(false);
  12654. cli.set_connection_timeout(30);
  12655. auto res = cli.Get("/test");
  12656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12657. ASSERT_EQ(StatusCode::OK_200, res->status);
  12658. ASSERT_TRUE(handler_called);
  12659. EXPECT_EQ("authenticated", res->body);
  12660. }
  12661. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12662. using namespace httplib::tls;
  12663. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12664. ASSERT_TRUE(svr.is_valid());
  12665. svr.Get("/test", [](const Request &, Response &res) {
  12666. res.set_content("ok", "text/plain");
  12667. });
  12668. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12669. auto se = detail::scope_exit([&] {
  12670. svr.stop();
  12671. t.join();
  12672. });
  12673. svr.wait_until_ready();
  12674. SSLClient cli(HOST, PORT);
  12675. cli.enable_server_certificate_verification(false);
  12676. cli.set_connection_timeout(30);
  12677. bool cert_checked = false;
  12678. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12679. if (ctx.cert) {
  12680. auto sans = ctx.sans();
  12681. // Test certificate may or may not have SANs - just verify the API
  12682. // works If SANs exist, verify the types are valid
  12683. for (const auto &san : sans) {
  12684. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12685. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12686. san.type == SanType::OTHER);
  12687. EXPECT_FALSE(san.value.empty());
  12688. }
  12689. cert_checked = true;
  12690. }
  12691. return true;
  12692. });
  12693. auto res = cli.Get("/test");
  12694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12695. EXPECT_TRUE(cert_checked);
  12696. }
  12697. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12698. using namespace httplib::tls;
  12699. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12700. ASSERT_TRUE(svr.is_valid());
  12701. svr.Get("/test", [](const Request &, Response &res) {
  12702. res.set_content("ok", "text/plain");
  12703. });
  12704. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12705. auto se = detail::scope_exit([&] {
  12706. svr.stop();
  12707. t.join();
  12708. });
  12709. svr.wait_until_ready();
  12710. SSLClient cli(HOST, PORT);
  12711. cli.enable_server_certificate_verification(false);
  12712. cli.set_connection_timeout(30);
  12713. bool validity_checked = false;
  12714. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12715. if (ctx.cert) {
  12716. time_t not_before = 0, not_after = 0;
  12717. bool result = ctx.validity(not_before, not_after);
  12718. EXPECT_TRUE(result);
  12719. // Verify that not_before < now < not_after for a valid cert
  12720. time_t now = time(nullptr);
  12721. EXPECT_LT(not_before, now);
  12722. EXPECT_GT(not_after, now);
  12723. validity_checked = true;
  12724. }
  12725. return true;
  12726. });
  12727. auto res = cli.Get("/test");
  12728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12729. EXPECT_TRUE(validity_checked);
  12730. }
  12731. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12732. using namespace httplib::tls;
  12733. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12734. ASSERT_TRUE(svr.is_valid());
  12735. svr.Get("/test", [](const Request &, Response &res) {
  12736. res.set_content("ok", "text/plain");
  12737. });
  12738. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12739. auto se = detail::scope_exit([&] {
  12740. svr.stop();
  12741. t.join();
  12742. });
  12743. svr.wait_until_ready();
  12744. SSLClient cli(HOST, PORT);
  12745. cli.enable_server_certificate_verification(false);
  12746. cli.set_connection_timeout(30);
  12747. bool serial_checked = false;
  12748. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12749. if (ctx.cert) {
  12750. std::string serial = ctx.serial();
  12751. EXPECT_FALSE(serial.empty());
  12752. // Serial should be a hex string
  12753. for (char c : serial) {
  12754. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12755. (c >= 'a' && c <= 'f'));
  12756. }
  12757. serial_checked = true;
  12758. }
  12759. return true;
  12760. });
  12761. auto res = cli.Get("/test");
  12762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12763. EXPECT_TRUE(serial_checked);
  12764. }
  12765. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12766. // Test 1: Valid CA file - no error should be recorded
  12767. {
  12768. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12769. CLIENT_CA_CERT_FILE);
  12770. ASSERT_TRUE(svr.is_valid());
  12771. // With valid setup, last_ssl_error should be 0
  12772. EXPECT_EQ(0, svr.ssl_last_error());
  12773. }
  12774. // Test 2: Invalid CA file content
  12775. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12776. {
  12777. // Create a temporary file with completely invalid content
  12778. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12779. {
  12780. std::ofstream ofs(temp_invalid_ca);
  12781. ofs << "This is not a certificate file at all\n";
  12782. ofs << "Just plain text content\n";
  12783. }
  12784. // Create server with invalid CA file
  12785. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12786. // Clean up temporary file
  12787. std::remove(temp_invalid_ca);
  12788. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12789. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12790. // Note: SSL_CTX_load_verify_locations typically fails first,
  12791. // but our error handling code path is still exercised
  12792. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12793. }
  12794. }
  12795. TEST(VerifyCallbackTest, VerifyContextFields) {
  12796. using namespace httplib::tls;
  12797. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12798. ASSERT_TRUE(svr.is_valid());
  12799. svr.Get("/test", [](const Request &, Response &res) {
  12800. res.set_content("ok", "text/plain");
  12801. });
  12802. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12803. auto se = detail::scope_exit([&] {
  12804. svr.stop();
  12805. t.join();
  12806. });
  12807. svr.wait_until_ready();
  12808. SSLClient cli(HOST, PORT);
  12809. cli.enable_server_certificate_verification(false);
  12810. cli.set_connection_timeout(30);
  12811. int callback_count = 0;
  12812. bool saw_leaf_cert = false;
  12813. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12814. if (ctx.cert) {
  12815. callback_count++;
  12816. // We should see at least one certificate (the leaf)
  12817. std::string cn = ctx.subject_cn();
  12818. if (!cn.empty()) { saw_leaf_cert = true; }
  12819. // Verify context fields are populated
  12820. EXPECT_NE(ctx.session, nullptr);
  12821. EXPECT_GE(ctx.depth, 0);
  12822. }
  12823. return true;
  12824. });
  12825. auto res = cli.Get("/test");
  12826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12827. EXPECT_GT(callback_count, 0);
  12828. EXPECT_TRUE(saw_leaf_cert);
  12829. }
  12830. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12831. using httplib::tls::TlsError;
  12832. // Test that verify_error_to_string returns empty for success
  12833. std::string success_str = TlsError::verify_error_to_string(0);
  12834. EXPECT_TRUE(success_str.empty());
  12835. // Test that verify_error_to_string returns non-empty for error codes
  12836. // Using a common error code (certificate expired)
  12837. std::string error_str =
  12838. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12839. EXPECT_FALSE(error_str.empty());
  12840. }
  12841. TEST(SessionVerifierTest, CertificateAccepted) {
  12842. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12843. ASSERT_TRUE(svr.is_valid());
  12844. svr.Get("/test", [](const Request &, Response &res) {
  12845. res.set_content("ok", "text/plain");
  12846. });
  12847. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12848. auto se = detail::scope_exit([&] {
  12849. svr.stop();
  12850. t.join();
  12851. });
  12852. svr.wait_until_ready();
  12853. SSLClient cli(HOST, PORT);
  12854. cli.enable_server_certificate_verification(false);
  12855. cli.set_connection_timeout(30);
  12856. bool callback_called = false;
  12857. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12858. EXPECT_NE(session, nullptr);
  12859. callback_called = true;
  12860. return SSLVerifierResponse::CertificateAccepted;
  12861. });
  12862. auto res = cli.Get("/test");
  12863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12864. EXPECT_EQ(200, res->status);
  12865. EXPECT_TRUE(callback_called);
  12866. }
  12867. TEST(SessionVerifierTest, CertificateRejected) {
  12868. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12869. ASSERT_TRUE(svr.is_valid());
  12870. svr.Get("/test", [](const Request &, Response &res) {
  12871. res.set_content("ok", "text/plain");
  12872. });
  12873. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12874. auto se = detail::scope_exit([&] {
  12875. svr.stop();
  12876. t.join();
  12877. });
  12878. svr.wait_until_ready();
  12879. SSLClient cli(HOST, PORT);
  12880. cli.enable_server_certificate_verification(false);
  12881. cli.set_connection_timeout(30);
  12882. bool callback_called = false;
  12883. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12884. EXPECT_NE(session, nullptr);
  12885. callback_called = true;
  12886. return SSLVerifierResponse::CertificateRejected;
  12887. });
  12888. auto res = cli.Get("/test");
  12889. EXPECT_FALSE(res);
  12890. EXPECT_TRUE(callback_called);
  12891. }
  12892. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12894. ASSERT_TRUE(svr.is_valid());
  12895. svr.Get("/test", [](const Request &, Response &res) {
  12896. res.set_content("ok", "text/plain");
  12897. });
  12898. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12899. auto se = detail::scope_exit([&] {
  12900. svr.stop();
  12901. t.join();
  12902. });
  12903. svr.wait_until_ready();
  12904. // NoDecisionMade with verification disabled should succeed (no default check)
  12905. SSLClient cli(HOST, PORT);
  12906. cli.enable_server_certificate_verification(false);
  12907. cli.set_connection_timeout(30);
  12908. bool callback_called = false;
  12909. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12910. EXPECT_NE(session, nullptr);
  12911. callback_called = true;
  12912. return SSLVerifierResponse::NoDecisionMade;
  12913. });
  12914. auto res = cli.Get("/test");
  12915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12916. EXPECT_EQ(200, res->status);
  12917. EXPECT_TRUE(callback_called);
  12918. }
  12919. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12920. SSLServer svr(SERVER_CERT_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 = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12926. auto se = detail::scope_exit([&] {
  12927. svr.stop();
  12928. t.join();
  12929. });
  12930. svr.wait_until_ready();
  12931. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12932. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12933. // so we only check that the request fails, not whether the callback was
  12934. // called.
  12935. SSLClient cli(HOST, PORT);
  12936. cli.enable_server_certificate_verification(true);
  12937. cli.set_connection_timeout(30);
  12938. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12939. EXPECT_NE(session, nullptr);
  12940. return SSLVerifierResponse::NoDecisionMade;
  12941. });
  12942. auto res = cli.Get("/test");
  12943. EXPECT_FALSE(res);
  12944. }
  12945. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12946. // Test SSL server using PemMemory constructor with client CA certificates
  12947. // Read PEM files
  12948. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12949. read_file(SERVER_CERT_FILE, server_cert_pem);
  12950. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12951. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12952. // Create SSLServer with PemMemory constructor including client CA
  12953. SSLServer::PemMemory server_pem = {
  12954. server_cert_pem.c_str(),
  12955. server_cert_pem.size(),
  12956. server_key_pem.c_str(),
  12957. server_key_pem.size(),
  12958. client_ca_pem.c_str(),
  12959. client_ca_pem.size(),
  12960. nullptr // no password for server key
  12961. };
  12962. SSLServer svr(server_pem);
  12963. ASSERT_TRUE(svr.is_valid());
  12964. // No SSL error should be recorded for valid setup
  12965. EXPECT_EQ(0, svr.ssl_last_error());
  12966. // Set up server endpoints
  12967. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12968. res.set_content("ok", "text/plain");
  12969. });
  12970. // Start server in a thread
  12971. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12972. svr.wait_until_ready();
  12973. // Connect with client certificate (using constructor with paths)
  12974. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12975. cli.enable_server_certificate_verification(false);
  12976. auto res = cli.Get("/test-pem-ca");
  12977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12978. EXPECT_EQ(200, res->status);
  12979. EXPECT_EQ("ok", res->body);
  12980. svr.stop();
  12981. server_thread.join();
  12982. }
  12983. #endif
  12984. #ifdef _WIN32
  12985. TEST(CleanupTest, WSACleanup) {
  12986. int ret = WSACleanup();
  12987. ASSERT_EQ(0, ret);
  12988. }
  12989. #endif
  12990. #ifndef CPPHTTPLIB_SSL_ENABLED
  12991. TEST(NoSSLSupport, SimpleInterface) {
  12992. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12993. }
  12994. #endif
  12995. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12996. TEST(InvalidScheme, SimpleInterface) {
  12997. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12998. }
  12999. #endif
  13000. TEST(NoScheme, SimpleInterface) {
  13001. Client cli("yahoo.com:80");
  13002. ASSERT_TRUE(cli.is_valid());
  13003. }
  13004. TEST(SendAPI, SimpleInterface_Online) {
  13005. Client cli("http://yahoo.com");
  13006. Request req;
  13007. req.method = "GET";
  13008. req.path = "/";
  13009. auto res = cli.send(req);
  13010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13011. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13012. }
  13013. TEST(SendAPI, WithParamsInRequest) {
  13014. Server svr;
  13015. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13016. EXPECT_TRUE(req.has_param("test"));
  13017. EXPECT_EQ("test_value", req.get_param_value("test"));
  13018. });
  13019. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13020. auto se = detail::scope_exit([&] {
  13021. svr.stop();
  13022. t.join();
  13023. ASSERT_FALSE(svr.is_running());
  13024. });
  13025. svr.wait_until_ready();
  13026. Client cli(HOST, PORT);
  13027. {
  13028. Request req;
  13029. req.method = "GET";
  13030. req.path = "/";
  13031. req.params.emplace("test", "test_value");
  13032. auto res = cli.send(req);
  13033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13034. }
  13035. {
  13036. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13038. }
  13039. }
  13040. TEST(ClientImplMethods, GetSocketTest) {
  13041. httplib::Server svr;
  13042. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13043. res.status = StatusCode::OK_200;
  13044. });
  13045. auto port = svr.bind_to_any_port("127.0.0.1");
  13046. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13047. auto se = detail::scope_exit([&] {
  13048. svr.stop();
  13049. thread.join();
  13050. ASSERT_FALSE(svr.is_running());
  13051. });
  13052. svr.wait_until_ready();
  13053. {
  13054. httplib::Client cli("127.0.0.1", port);
  13055. cli.set_keep_alive(true);
  13056. // Use the behavior of cpp-httplib of opening the connection
  13057. // only when the first request happens. If that changes,
  13058. // this test would be obsolete.
  13059. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13060. // This also implicitly tests the server. But other tests would fail much
  13061. // earlier than this one to be considered.
  13062. auto res = cli.Get("/");
  13063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13064. EXPECT_EQ(StatusCode::OK_200, res->status);
  13065. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13066. }
  13067. }
  13068. #ifdef CPPHTTPLIB_SSL_ENABLED
  13069. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13070. Client cli("http://yahoo.com");
  13071. auto res = cli.Get("/");
  13072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13073. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13074. cli.set_follow_location(true);
  13075. res = cli.Get("/");
  13076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13077. EXPECT_EQ(StatusCode::OK_200, res->status);
  13078. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13079. }
  13080. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13081. Client cli("https://yahoo.com");
  13082. auto res = cli.Get("/");
  13083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13084. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13085. cli.set_follow_location(true);
  13086. res = cli.Get("/");
  13087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13088. EXPECT_EQ(StatusCode::OK_200, res->status);
  13089. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13090. }
  13091. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13092. Client cli("https://yahoo.com");
  13093. auto res = cli.Get("/");
  13094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13095. ASSERT_FALSE(!res);
  13096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13097. ASSERT_FALSE(res == nullptr);
  13098. ASSERT_TRUE(res != nullptr);
  13099. EXPECT_EQ(Error::Success, res.error());
  13100. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13101. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13102. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13103. cli.set_follow_location(true);
  13104. res = cli.Get("/");
  13105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13106. EXPECT_EQ(Error::Success, res.error());
  13107. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13108. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13109. EXPECT_EQ(StatusCode::OK_200, res->status);
  13110. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13111. }
  13112. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13113. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13114. Client cli("https://cdnjs.cloudflare.com");
  13115. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13116. Headers{{"Accept-Encoding", "br"}});
  13117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13118. EXPECT_EQ(StatusCode::OK_200, res->status);
  13119. EXPECT_EQ(287630U, res->body.size());
  13120. EXPECT_EQ("application/javascript; charset=utf-8",
  13121. res->get_header_value("Content-Type"));
  13122. }
  13123. #endif
  13124. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13125. #undef REDIR_HOST // Silence compiler warning
  13126. #define REDIR_HOST "https://httpbingo.org"
  13127. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13128. Client cli(REDIR_HOST);
  13129. cli.set_follow_location(true);
  13130. auto res =
  13131. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13133. EXPECT_EQ(StatusCode::OK_200, res->status);
  13134. }
  13135. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13136. Client cli(REDIR_HOST);
  13137. cli.set_follow_location(true);
  13138. Params params;
  13139. params.emplace("url", "http://example.com");
  13140. params.emplace("status_code", "302");
  13141. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13143. EXPECT_EQ(StatusCode::OK_200, res->status);
  13144. }
  13145. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13146. Client cli(REDIR_HOST);
  13147. cli.set_follow_location(true);
  13148. Params params;
  13149. params.emplace("url", "http://example.com");
  13150. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13152. EXPECT_EQ(StatusCode::OK_200, res->status);
  13153. }
  13154. TEST(HttpToHttpsRedirectTest, CertFile) {
  13155. auto ssl_port = PORT + 1;
  13156. Server svr;
  13157. ASSERT_TRUE(svr.is_valid());
  13158. svr.Get("/index", [&](const Request &, Response &res) {
  13159. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13160. "/index");
  13161. svr.stop();
  13162. });
  13163. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13164. ASSERT_TRUE(ssl_svr.is_valid());
  13165. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13166. res.set_content("test", "text/plain");
  13167. ssl_svr.stop();
  13168. });
  13169. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13170. thread t2 =
  13171. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13172. auto se = detail::scope_exit([&] {
  13173. t2.join();
  13174. t.join();
  13175. ASSERT_FALSE(svr.is_running());
  13176. });
  13177. svr.wait_until_ready();
  13178. ssl_svr.wait_until_ready();
  13179. Client cli("127.0.0.1", PORT);
  13180. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13181. cli.enable_server_certificate_verification(true);
  13182. cli.set_follow_location(true);
  13183. cli.set_connection_timeout(30);
  13184. auto res = cli.Get("/index");
  13185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13186. ASSERT_EQ(StatusCode::OK_200, res->status);
  13187. }
  13188. TEST(SSLClientRedirectTest, CertFile) {
  13189. auto ssl_port = PORT + 1;
  13190. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13191. ASSERT_TRUE(ssl_svr1.is_valid());
  13192. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13193. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13194. "/index");
  13195. ssl_svr1.stop();
  13196. });
  13197. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13198. ASSERT_TRUE(ssl_svr2.is_valid());
  13199. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13200. res.set_content("test", "text/plain");
  13201. ssl_svr2.stop();
  13202. });
  13203. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13204. thread t2 =
  13205. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13206. auto se = detail::scope_exit([&] {
  13207. t2.join();
  13208. t.join();
  13209. ASSERT_FALSE(ssl_svr1.is_running());
  13210. });
  13211. ssl_svr1.wait_until_ready();
  13212. ssl_svr2.wait_until_ready();
  13213. SSLClient cli("127.0.0.1", PORT);
  13214. std::string cert;
  13215. read_file(SERVER_CERT2_FILE, cert);
  13216. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13217. cli.enable_server_certificate_verification(true);
  13218. cli.set_follow_location(true);
  13219. cli.set_connection_timeout(30);
  13220. auto res = cli.Get("/index");
  13221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13222. ASSERT_EQ(StatusCode::OK_200, res->status);
  13223. }
  13224. #endif
  13225. #ifdef CPPHTTPLIB_SSL_ENABLED
  13226. // Test that set_ca_cert_store() skips system certs (consistent with
  13227. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13228. // should be trusted - system certs should NOT be loaded.
  13229. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13230. // Load a specific cert that is NOT a system CA cert
  13231. std::string cert;
  13232. read_file(SERVER_CERT2_FILE, cert);
  13233. SSLClient cli("google.com");
  13234. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13235. cli.enable_server_certificate_verification(true);
  13236. // This should FAIL because:
  13237. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13238. // 2. System certs should NOT be loaded when custom store is set
  13239. // If system certs WERE loaded, this would succeed
  13240. auto res = cli.Get("/");
  13241. ASSERT_FALSE(res);
  13242. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13243. }
  13244. // Same as above, but through the native store handle path. Regression test:
  13245. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13246. // merged system certs into the user-provided store.
  13247. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13248. std::string cert;
  13249. read_file(SERVER_CERT2_FILE, cert);
  13250. SSLClient cli("google.com");
  13251. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13252. cli.enable_server_certificate_verification(true);
  13253. auto res = cli.Get("/");
  13254. ASSERT_FALSE(res);
  13255. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13256. }
  13257. // A custom store set via the native handle must still verify a server whose
  13258. // cert it does contain.
  13259. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13260. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13261. ASSERT_TRUE(svr.is_valid());
  13262. svr.Get("/test", [&](const Request &, Response &res) {
  13263. res.set_content("test", "text/plain");
  13264. });
  13265. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13266. auto se = detail::scope_exit([&] {
  13267. svr.stop();
  13268. t.join();
  13269. ASSERT_FALSE(svr.is_running());
  13270. });
  13271. svr.wait_until_ready();
  13272. SSLClient cli("127.0.0.1", PORT);
  13273. std::string cert;
  13274. read_file(SERVER_CERT2_FILE, cert);
  13275. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13276. cli.enable_server_certificate_verification(true);
  13277. cli.set_connection_timeout(30);
  13278. auto res = cli.Get("/test");
  13279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13280. ASSERT_EQ(StatusCode::OK_200, res->status);
  13281. }
  13282. // CA certs loaded through the universal Client must be transferred to the
  13283. // client created internally for following an HTTPS redirect. Regression test:
  13284. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13285. // the CA data for redirect transfer.
  13286. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13287. auto ssl_port = PORT + 1;
  13288. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13289. ASSERT_TRUE(ssl_svr1.is_valid());
  13290. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13291. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13292. "/index");
  13293. });
  13294. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13295. ASSERT_TRUE(ssl_svr2.is_valid());
  13296. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13297. res.set_content("test", "text/plain");
  13298. });
  13299. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13300. thread t2 =
  13301. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13302. auto se = detail::scope_exit([&] {
  13303. ssl_svr2.stop();
  13304. ssl_svr1.stop();
  13305. t2.join();
  13306. t.join();
  13307. ASSERT_FALSE(ssl_svr1.is_running());
  13308. });
  13309. ssl_svr1.wait_until_ready();
  13310. ssl_svr2.wait_until_ready();
  13311. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13312. std::string cert;
  13313. read_file(SERVER_CERT2_FILE, cert);
  13314. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13315. cli.enable_server_certificate_verification(true);
  13316. cli.set_follow_location(true);
  13317. cli.set_connection_timeout(30);
  13318. auto res = cli.Get("/index");
  13319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13320. ASSERT_EQ(StatusCode::OK_200, res->status);
  13321. }
  13322. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13323. // so a host signed by a system CA verifies even though a custom CA is set
  13324. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13325. std::string cert;
  13326. read_file(SERVER_CERT2_FILE, cert);
  13327. SSLClient cli("google.com");
  13328. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13329. cli.enable_system_ca(true);
  13330. cli.enable_server_certificate_verification(true);
  13331. auto res = cli.Get("/");
  13332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13333. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13334. }
  13335. // The custom CA remains effective when combined with the system CA
  13336. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13337. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13338. ASSERT_TRUE(svr.is_valid());
  13339. svr.Get("/test", [&](const Request &, Response &res) {
  13340. res.set_content("test", "text/plain");
  13341. });
  13342. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13343. auto se = detail::scope_exit([&] {
  13344. svr.stop();
  13345. t.join();
  13346. ASSERT_FALSE(svr.is_running());
  13347. });
  13348. svr.wait_until_ready();
  13349. SSLClient cli("127.0.0.1", PORT);
  13350. std::string cert;
  13351. read_file(SERVER_CERT2_FILE, cert);
  13352. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13353. cli.enable_system_ca(true);
  13354. cli.enable_server_certificate_verification(true);
  13355. cli.set_connection_timeout(30);
  13356. auto res = cli.Get("/test");
  13357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13358. ASSERT_EQ(StatusCode::OK_200, res->status);
  13359. }
  13360. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13361. // skip chain verification entirely (only the certificate identity was
  13362. // checked), so a server presenting an untrusted certificate with a matching
  13363. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13364. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13365. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13366. ASSERT_TRUE(svr.is_valid());
  13367. svr.Get("/test", [&](const Request &, Response &res) {
  13368. res.set_content("test", "text/plain");
  13369. });
  13370. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13371. auto se = detail::scope_exit([&] {
  13372. svr.stop();
  13373. t.join();
  13374. ASSERT_FALSE(svr.is_running());
  13375. });
  13376. svr.wait_until_ready();
  13377. SSLClient cli("127.0.0.1", PORT);
  13378. std::string cert;
  13379. // A trusted CA that did not sign the server certificate. The server cert
  13380. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13381. // this connection.
  13382. read_file(CLIENT_CA_CERT_FILE, cert);
  13383. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13384. cli.enable_server_certificate_verification(true);
  13385. cli.set_connection_timeout(30);
  13386. auto res = cli.Get("/test");
  13387. ASSERT_FALSE(res);
  13388. }
  13389. // enable_system_ca(false) prevents system CA loading entirely
  13390. TEST(SSLClientTest, DisableSystemCa_Online) {
  13391. SSLClient cli("google.com");
  13392. cli.enable_system_ca(false);
  13393. cli.enable_server_certificate_verification(true);
  13394. auto res = cli.Get("/");
  13395. ASSERT_FALSE(res);
  13396. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13397. // itself when the CA chain is empty
  13398. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13399. res.error() == Error::SSLConnection);
  13400. }
  13401. // The universal Client forwards enable_system_ca()
  13402. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13403. std::string cert;
  13404. read_file(SERVER_CERT2_FILE, cert);
  13405. Client cli("https://google.com");
  13406. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13407. cli.enable_system_ca(true);
  13408. cli.enable_server_certificate_verification(true);
  13409. auto res = cli.Get("/");
  13410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13411. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13412. }
  13413. // The system CA policy must carry over to the client created internally for
  13414. // following a cross-host HTTPS redirect
  13415. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13416. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13417. ASSERT_TRUE(svr.is_valid());
  13418. svr.Get("/index", [&](const Request &, Response &res) {
  13419. res.set_redirect("https://www.google.com/");
  13420. });
  13421. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13422. auto se = detail::scope_exit([&] {
  13423. svr.stop();
  13424. t.join();
  13425. ASSERT_FALSE(svr.is_running());
  13426. });
  13427. svr.wait_until_ready();
  13428. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13429. std::string cert;
  13430. read_file(SERVER_CERT2_FILE, cert);
  13431. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13432. cli.enable_system_ca(true);
  13433. cli.enable_server_certificate_verification(true);
  13434. cli.set_follow_location(true);
  13435. cli.set_connection_timeout(30);
  13436. // Receiving any response proves the redirect client completed the TLS
  13437. // handshake with a system-CA-signed host
  13438. auto res = cli.Get("/index");
  13439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13440. }
  13441. TEST(MultipartFormDataTest, LargeData) {
  13442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13443. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13444. const ContentReader &content_reader) {
  13445. if (req.is_multipart_form_data()) {
  13446. std::vector<FormData> items;
  13447. content_reader(
  13448. [&](const FormData &file) {
  13449. items.push_back(file);
  13450. return true;
  13451. },
  13452. [&](const char *data, size_t data_length) {
  13453. items.back().content.append(data, data_length);
  13454. return true;
  13455. });
  13456. EXPECT_TRUE(std::string(items[0].name) == "document");
  13457. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13458. EXPECT_TRUE(items[0].filename == "2MB_data");
  13459. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13460. EXPECT_TRUE(items[1].name == "hello");
  13461. EXPECT_TRUE(items[1].content == "world");
  13462. EXPECT_TRUE(items[1].filename == "");
  13463. EXPECT_TRUE(items[1].content_type == "");
  13464. } else {
  13465. std::string body;
  13466. content_reader([&](const char *data, size_t data_length) {
  13467. body.append(data, data_length);
  13468. return true;
  13469. });
  13470. }
  13471. });
  13472. auto port = svr.bind_to_any_port(HOST);
  13473. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13474. auto se = detail::scope_exit([&] {
  13475. svr.stop();
  13476. t.join();
  13477. ASSERT_FALSE(svr.is_running());
  13478. });
  13479. svr.wait_until_ready();
  13480. {
  13481. std::string data(1024 * 1024 * 2, '.');
  13482. std::stringstream buffer;
  13483. buffer << data;
  13484. SSLClient cli(HOST, port);
  13485. cli.enable_server_certificate_verification(false);
  13486. UploadFormDataItems items{
  13487. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13488. {"hello", "world", "", ""},
  13489. };
  13490. auto res = cli.Post("/post", items);
  13491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13492. ASSERT_EQ(StatusCode::OK_200, res->status);
  13493. }
  13494. }
  13495. TEST(MultipartFormDataTest, DataProviderItems) {
  13496. std::random_device seed_gen;
  13497. std::mt19937 random(seed_gen());
  13498. std::string rand1;
  13499. rand1.resize(1000);
  13500. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13501. std::string rand2;
  13502. rand2.resize(3000);
  13503. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13504. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13505. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13506. const ContentReader &content_reader) {
  13507. ASSERT_FALSE(req.is_multipart_form_data());
  13508. std::string body;
  13509. content_reader([&](const char *data, size_t data_length) {
  13510. body.append(data, data_length);
  13511. return true;
  13512. });
  13513. EXPECT_EQ(body, "");
  13514. });
  13515. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13516. const ContentReader &content_reader) {
  13517. ASSERT_TRUE(req.is_multipart_form_data());
  13518. std::vector<FormData> items;
  13519. content_reader(
  13520. [&](const FormData &file) {
  13521. items.push_back(file);
  13522. return true;
  13523. },
  13524. [&](const char *data, size_t data_length) {
  13525. items.back().content.append(data, data_length);
  13526. return true;
  13527. });
  13528. ASSERT_TRUE(items.size() == 2);
  13529. EXPECT_EQ(std::string(items[0].name), "name1");
  13530. EXPECT_EQ(items[0].content, "Testing123");
  13531. EXPECT_EQ(items[0].filename, "filename1");
  13532. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13533. EXPECT_EQ(items[1].name, "name2");
  13534. EXPECT_EQ(items[1].content, "Testing456");
  13535. EXPECT_EQ(items[1].filename, "");
  13536. EXPECT_EQ(items[1].content_type, "");
  13537. });
  13538. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13539. const ContentReader &content_reader) {
  13540. ASSERT_TRUE(req.is_multipart_form_data());
  13541. std::vector<FormData> items;
  13542. content_reader(
  13543. [&](const FormData &file) {
  13544. items.push_back(file);
  13545. return true;
  13546. },
  13547. [&](const char *data, size_t data_length) {
  13548. items.back().content.append(data, data_length);
  13549. return true;
  13550. });
  13551. ASSERT_TRUE(items.size() == 2);
  13552. EXPECT_EQ(items[0].name, "name3");
  13553. EXPECT_EQ(items[0].content, rand1);
  13554. EXPECT_EQ(items[0].filename, "filename3");
  13555. EXPECT_EQ(items[0].content_type, "");
  13556. EXPECT_EQ(items[1].name, "name4");
  13557. EXPECT_EQ(items[1].content, rand2);
  13558. EXPECT_EQ(items[1].filename, "filename4");
  13559. EXPECT_EQ(items[1].content_type, "");
  13560. });
  13561. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13562. const ContentReader &content_reader) {
  13563. ASSERT_TRUE(req.is_multipart_form_data());
  13564. std::vector<FormData> items;
  13565. content_reader(
  13566. [&](const FormData &file) {
  13567. items.push_back(file);
  13568. return true;
  13569. },
  13570. [&](const char *data, size_t data_length) {
  13571. items.back().content.append(data, data_length);
  13572. return true;
  13573. });
  13574. ASSERT_TRUE(items.size() == 4);
  13575. EXPECT_EQ(std::string(items[0].name), "name1");
  13576. EXPECT_EQ(items[0].content, "Testing123");
  13577. EXPECT_EQ(items[0].filename, "filename1");
  13578. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13579. EXPECT_EQ(items[1].name, "name2");
  13580. EXPECT_EQ(items[1].content, "Testing456");
  13581. EXPECT_EQ(items[1].filename, "");
  13582. EXPECT_EQ(items[1].content_type, "");
  13583. EXPECT_EQ(items[2].name, "name3");
  13584. EXPECT_EQ(items[2].content, rand1);
  13585. EXPECT_EQ(items[2].filename, "filename3");
  13586. EXPECT_EQ(items[2].content_type, "");
  13587. EXPECT_EQ(items[3].name, "name4");
  13588. EXPECT_EQ(items[3].content, rand2);
  13589. EXPECT_EQ(items[3].filename, "filename4");
  13590. EXPECT_EQ(items[3].content_type, "");
  13591. });
  13592. auto port = svr.bind_to_any_port("localhost");
  13593. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13594. auto se = detail::scope_exit([&] {
  13595. svr.stop();
  13596. t.join();
  13597. ASSERT_FALSE(svr.is_running());
  13598. });
  13599. svr.wait_until_ready();
  13600. {
  13601. SSLClient cli("localhost", port);
  13602. cli.enable_server_certificate_verification(false);
  13603. UploadFormDataItems items{
  13604. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13605. {"name2", "Testing456", "", ""}, // not a file
  13606. };
  13607. {
  13608. auto res = cli.Post("/post-none", {}, {}, {});
  13609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13610. ASSERT_EQ(StatusCode::OK_200, res->status);
  13611. }
  13612. FormDataProviderItems providers;
  13613. {
  13614. auto res =
  13615. cli.Post("/post-items", {}, items, providers); // empty providers
  13616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13617. ASSERT_EQ(StatusCode::OK_200, res->status);
  13618. }
  13619. providers.push_back({"name3",
  13620. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13621. // test the offset is given correctly at each step
  13622. if (!offset)
  13623. sink.os.write(rand1.data(), 30);
  13624. else if (offset == 30)
  13625. sink.os.write(rand1.data() + 30, 300);
  13626. else if (offset == 330)
  13627. sink.os.write(rand1.data() + 330, 670);
  13628. else if (offset == rand1.size())
  13629. sink.done();
  13630. return true;
  13631. },
  13632. "filename3",
  13633. {}});
  13634. providers.push_back({"name4",
  13635. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13636. // test the offset is given correctly at each step
  13637. if (!offset)
  13638. sink.os.write(rand2.data(), 2000);
  13639. else if (offset == 2000)
  13640. sink.os.write(rand2.data() + 2000, 1);
  13641. else if (offset == 2001)
  13642. sink.os.write(rand2.data() + 2001, 999);
  13643. else if (offset == rand2.size())
  13644. sink.done();
  13645. return true;
  13646. },
  13647. "filename4",
  13648. {}});
  13649. {
  13650. auto res = cli.Post("/post-providers", {}, {}, providers);
  13651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13652. ASSERT_EQ(StatusCode::OK_200, res->status);
  13653. }
  13654. {
  13655. auto res = cli.Post("/post-both", {}, items, providers);
  13656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13657. ASSERT_EQ(StatusCode::OK_200, res->status);
  13658. }
  13659. }
  13660. }
  13661. TEST(MultipartFormDataTest, BadHeader) {
  13662. Server svr;
  13663. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13664. res.set_content("ok", "text/plain");
  13665. });
  13666. thread t = thread([&] { svr.listen(HOST, PORT); });
  13667. auto se = detail::scope_exit([&] {
  13668. svr.stop();
  13669. t.join();
  13670. ASSERT_FALSE(svr.is_running());
  13671. });
  13672. svr.wait_until_ready();
  13673. const std::string body =
  13674. "This is the preamble. It is to be ignored, though it\r\n"
  13675. "is a handy place for composition agents to include an\r\n"
  13676. "explanatory note to non-MIME conformant readers.\r\n"
  13677. "\r\n"
  13678. "\r\n"
  13679. "--simple boundary\r\n"
  13680. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13681. ": BAD...\r\n"
  13682. "\r\n"
  13683. "value1\r\n"
  13684. "--simple boundary\r\n"
  13685. "Content-Disposition: form-data; name=\"field2\"; "
  13686. "filename=\"example.txt\"\r\n"
  13687. "\r\n"
  13688. "value2\r\n"
  13689. "--simple boundary--\r\n"
  13690. "This is the epilogue. It is also to be ignored.\r\n";
  13691. std::string content_type =
  13692. R"(multipart/form-data; boundary="simple boundary")";
  13693. Client cli(HOST, PORT);
  13694. auto res = cli.Post("/post", body, content_type.c_str());
  13695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13696. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13697. }
  13698. TEST(MultipartFormDataTest, WithPreamble) {
  13699. Server svr;
  13700. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13701. res.set_content("ok", "text/plain");
  13702. });
  13703. thread t = thread([&] { svr.listen(HOST, PORT); });
  13704. auto se = detail::scope_exit([&] {
  13705. svr.stop();
  13706. t.join();
  13707. ASSERT_FALSE(svr.is_running());
  13708. });
  13709. svr.wait_until_ready();
  13710. const std::string body =
  13711. "This is the preamble. It is to be ignored, though it\r\n"
  13712. "is a handy place for composition agents to include an\r\n"
  13713. "explanatory note to non-MIME conformant readers.\r\n"
  13714. "\r\n"
  13715. "\r\n"
  13716. "--simple boundary\r\n"
  13717. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13718. "\r\n"
  13719. "value1\r\n"
  13720. "--simple boundary\r\n"
  13721. "Content-Disposition: form-data; name=\"field2\"; "
  13722. "filename=\"example.txt\"\r\n"
  13723. "\r\n"
  13724. "value2\r\n"
  13725. "--simple boundary--\r\n"
  13726. "This is the epilogue. It is also to be ignored.\r\n";
  13727. std::string content_type =
  13728. R"(multipart/form-data; boundary="simple boundary")";
  13729. Client cli(HOST, PORT);
  13730. auto res = cli.Post("/post", body, content_type.c_str());
  13731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13732. EXPECT_EQ(StatusCode::OK_200, res->status);
  13733. }
  13734. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13735. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13736. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13737. const ContentReader &content_reader) {
  13738. if (req.is_multipart_form_data()) {
  13739. std::vector<FormData> items;
  13740. content_reader(
  13741. [&](const FormData &file) {
  13742. items.push_back(file);
  13743. return true;
  13744. },
  13745. [&](const char *data, size_t data_length) {
  13746. items.back().content.append(data, data_length);
  13747. return true;
  13748. });
  13749. EXPECT_TRUE(std::string(items[0].name) == "document");
  13750. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13751. EXPECT_TRUE(items[0].filename == "2MB_data");
  13752. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13753. EXPECT_TRUE(items[1].name == "hello");
  13754. EXPECT_TRUE(items[1].content == "world");
  13755. EXPECT_TRUE(items[1].filename == "");
  13756. EXPECT_TRUE(items[1].content_type == "");
  13757. } else {
  13758. std::string body;
  13759. content_reader([&](const char *data, size_t data_length) {
  13760. body.append(data, data_length);
  13761. return true;
  13762. });
  13763. }
  13764. });
  13765. auto port = svr.bind_to_any_port("localhost");
  13766. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13767. auto se = detail::scope_exit([&] {
  13768. svr.stop();
  13769. t.join();
  13770. ASSERT_FALSE(svr.is_running());
  13771. });
  13772. svr.wait_until_ready();
  13773. {
  13774. std::string data(1024 * 1024 * 2, '.');
  13775. std::stringstream buffer;
  13776. buffer << data;
  13777. SSLClient cli("localhost", port);
  13778. cli.enable_server_certificate_verification(false);
  13779. UploadFormDataItems items{
  13780. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13781. {"hello", "world", "", ""},
  13782. };
  13783. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13785. ASSERT_EQ(StatusCode::OK_200, res->status);
  13786. }
  13787. }
  13788. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13789. std::string data(1024 * 1024 * 2, '&');
  13790. std::stringstream buffer;
  13791. buffer << data;
  13792. Client cli("https://localhost:8080");
  13793. UploadFormDataItems items{
  13794. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13795. {"hello", "world", "", ""},
  13796. };
  13797. for (const char &c : " \t\r\n") {
  13798. auto res =
  13799. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13800. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13801. ASSERT_FALSE(res);
  13802. }
  13803. }
  13804. TEST(MultipartFormDataTest, PutFormData) {
  13805. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13806. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13807. const ContentReader &content_reader) {
  13808. if (req.is_multipart_form_data()) {
  13809. std::vector<FormData> items;
  13810. content_reader(
  13811. [&](const FormData &file) {
  13812. items.push_back(file);
  13813. return true;
  13814. },
  13815. [&](const char *data, size_t data_length) {
  13816. items.back().content.append(data, data_length);
  13817. return true;
  13818. });
  13819. EXPECT_TRUE(std::string(items[0].name) == "document");
  13820. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13821. EXPECT_TRUE(items[0].filename == "2MB_data");
  13822. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13823. EXPECT_TRUE(items[1].name == "hello");
  13824. EXPECT_TRUE(items[1].content == "world");
  13825. EXPECT_TRUE(items[1].filename == "");
  13826. EXPECT_TRUE(items[1].content_type == "");
  13827. } else {
  13828. std::string body;
  13829. content_reader([&](const char *data, size_t data_length) {
  13830. body.append(data, data_length);
  13831. return true;
  13832. });
  13833. }
  13834. });
  13835. auto port = svr.bind_to_any_port("localhost");
  13836. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13837. auto se = detail::scope_exit([&] {
  13838. svr.stop();
  13839. t.join();
  13840. ASSERT_FALSE(svr.is_running());
  13841. });
  13842. svr.wait_until_ready();
  13843. {
  13844. std::string data(1024 * 1024 * 2, '&');
  13845. std::stringstream buffer;
  13846. buffer << data;
  13847. SSLClient cli("localhost", port);
  13848. cli.enable_server_certificate_verification(false);
  13849. UploadFormDataItems items{
  13850. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13851. {"hello", "world", "", ""},
  13852. };
  13853. auto res = cli.Put("/put", items);
  13854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13855. ASSERT_EQ(StatusCode::OK_200, res->status);
  13856. }
  13857. }
  13858. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13859. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13860. svr.Put("/put_customboundary",
  13861. [&](const Request &req, const Response & /*res*/,
  13862. const ContentReader &content_reader) {
  13863. if (req.is_multipart_form_data()) {
  13864. std::vector<FormData> items;
  13865. content_reader(
  13866. [&](const FormData &file) {
  13867. items.push_back(file);
  13868. return true;
  13869. },
  13870. [&](const char *data, size_t data_length) {
  13871. items.back().content.append(data, data_length);
  13872. return true;
  13873. });
  13874. EXPECT_TRUE(std::string(items[0].name) == "document");
  13875. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13876. EXPECT_TRUE(items[0].filename == "2MB_data");
  13877. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13878. EXPECT_TRUE(items[1].name == "hello");
  13879. EXPECT_TRUE(items[1].content == "world");
  13880. EXPECT_TRUE(items[1].filename == "");
  13881. EXPECT_TRUE(items[1].content_type == "");
  13882. } else {
  13883. std::string body;
  13884. content_reader([&](const char *data, size_t data_length) {
  13885. body.append(data, data_length);
  13886. return true;
  13887. });
  13888. }
  13889. });
  13890. auto port = svr.bind_to_any_port("localhost");
  13891. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13892. auto se = detail::scope_exit([&] {
  13893. svr.stop();
  13894. t.join();
  13895. ASSERT_FALSE(svr.is_running());
  13896. });
  13897. svr.wait_until_ready();
  13898. {
  13899. std::string data(1024 * 1024 * 2, '&');
  13900. std::stringstream buffer;
  13901. buffer << data;
  13902. SSLClient cli("localhost", port);
  13903. cli.enable_server_certificate_verification(false);
  13904. UploadFormDataItems items{
  13905. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13906. {"hello", "world", "", ""},
  13907. };
  13908. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13910. ASSERT_EQ(StatusCode::OK_200, res->status);
  13911. }
  13912. }
  13913. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13914. std::string data(1024 * 1024 * 2, '&');
  13915. std::stringstream buffer;
  13916. buffer << data;
  13917. Client cli("https://localhost:8080");
  13918. cli.enable_server_certificate_verification(false);
  13919. UploadFormDataItems items{
  13920. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13921. {"hello", "world", "", ""},
  13922. };
  13923. for (const char &c : " \t\r\n") {
  13924. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13925. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13926. ASSERT_FALSE(res);
  13927. }
  13928. }
  13929. TEST(MultipartFormDataTest, AlternateFilename) {
  13930. auto handled = false;
  13931. Server svr;
  13932. svr.Post("/test", [&](const Request &req, Response &res) {
  13933. ASSERT_EQ(2u, req.form.files.size());
  13934. ASSERT_EQ(1u, req.form.fields.size());
  13935. // Test files
  13936. const auto &file1 = req.form.get_file("file1");
  13937. ASSERT_EQ("file1", file1.name);
  13938. ASSERT_EQ("A.txt", file1.filename);
  13939. ASSERT_EQ("text/plain", file1.content_type);
  13940. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13941. const auto &file2 = req.form.get_file("file2");
  13942. ASSERT_EQ("file2", file2.name);
  13943. ASSERT_EQ("a.html", file2.filename);
  13944. ASSERT_EQ("text/html", file2.content_type);
  13945. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13946. file2.content);
  13947. // Test text field
  13948. const auto &text = req.form.get_field("text");
  13949. ASSERT_EQ("text default", text);
  13950. res.set_content("ok", "text/plain");
  13951. handled = true;
  13952. });
  13953. thread t = thread([&] { svr.listen(HOST, PORT); });
  13954. auto se = detail::scope_exit([&] {
  13955. svr.stop();
  13956. t.join();
  13957. ASSERT_FALSE(svr.is_running());
  13958. ASSERT_TRUE(handled);
  13959. });
  13960. svr.wait_until_ready();
  13961. auto req = "POST /test HTTP/1.1\r\n"
  13962. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13963. "Content-Length: 399\r\n"
  13964. "\r\n"
  13965. "----------\r\n"
  13966. "Content-Disposition: form-data; name=\"text\"\r\n"
  13967. "\r\n"
  13968. "text default\r\n"
  13969. "----------\r\n"
  13970. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13971. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13972. "Content-Type: text/plain\r\n"
  13973. "\r\n"
  13974. "Content of a.txt.\r\n"
  13975. "\r\n"
  13976. "----------\r\n"
  13977. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13978. "\"a.html\"\r\n"
  13979. "Content-Type: text/html\r\n"
  13980. "\r\n"
  13981. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13982. "\r\n"
  13983. "------------\r\n";
  13984. ASSERT_TRUE(send_request(1, req));
  13985. }
  13986. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13987. auto handled = false;
  13988. Server svr;
  13989. svr.Post("/test", [&](const Request &req, Response &res) {
  13990. // Case-insensitive "utf-8''" prefix with a long value
  13991. const auto &file = req.form.get_file("file1");
  13992. ASSERT_EQ("file1", file.name);
  13993. // 8000 chars exercises both the Content-Disposition parser and the
  13994. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13995. // Prior to the fix, std::regex_match on this header would cause O(N)
  13996. // stack recursion in libstdc++, leading to SIGSEGV.
  13997. std::string expected_filename(8000, 'A');
  13998. ASSERT_EQ(expected_filename, file.filename);
  13999. res.set_content("ok", "text/plain");
  14000. handled = true;
  14001. });
  14002. thread t = thread([&] { svr.listen(HOST, PORT); });
  14003. auto se = detail::scope_exit([&] {
  14004. svr.stop();
  14005. t.join();
  14006. ASSERT_FALSE(svr.is_running());
  14007. ASSERT_TRUE(handled);
  14008. });
  14009. svr.wait_until_ready();
  14010. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14011. // Regression test for GHSA-qq6v-r583-3h69
  14012. std::string long_filename(8000, 'A');
  14013. std::string body = "----------\r\n"
  14014. "Content-Disposition: form-data; name=\"file1\"; "
  14015. "filename*=\"Utf-8''" +
  14016. long_filename +
  14017. "\"\r\n"
  14018. "\r\n"
  14019. "hello\r\n"
  14020. "------------\r\n";
  14021. auto req = "POST /test HTTP/1.1\r\n"
  14022. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14023. "Content-Length: " +
  14024. std::to_string(body.size()) + "\r\n\r\n" + body;
  14025. ASSERT_TRUE(send_request(1, req));
  14026. }
  14027. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14028. auto handled = false;
  14029. Server svr;
  14030. svr.Post("/test", [&](const Request &req, Response &) {
  14031. ASSERT_EQ(2u, req.form.fields.size());
  14032. const auto &text1 = req.form.get_field("text1");
  14033. ASSERT_EQ("text1", text1);
  14034. const auto &text2 = req.form.get_field("text2");
  14035. ASSERT_EQ("text2", text2);
  14036. handled = true;
  14037. });
  14038. thread t = thread([&] { svr.listen(HOST, PORT); });
  14039. auto se = detail::scope_exit([&] {
  14040. svr.stop();
  14041. t.join();
  14042. ASSERT_FALSE(svr.is_running());
  14043. ASSERT_TRUE(handled);
  14044. });
  14045. svr.wait_until_ready();
  14046. auto req = "POST /test HTTP/1.1\r\n"
  14047. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14048. "Content-Length: 146\r\n"
  14049. "\r\n----------\r\n"
  14050. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14051. "\r\n"
  14052. "text1"
  14053. "\r\n----------\r\n"
  14054. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14055. "\r\n"
  14056. "text2"
  14057. "\r\n------------";
  14058. std::string response;
  14059. ASSERT_TRUE(send_request(1, req, &response));
  14060. ASSERT_EQ("200", response.substr(9, 3));
  14061. }
  14062. TEST(MultipartFormDataTest, ContentLength) {
  14063. auto handled = false;
  14064. Server svr;
  14065. svr.Post("/test", [&](const Request &req, Response &) {
  14066. ASSERT_EQ(2u, req.form.fields.size());
  14067. const auto &text1 = req.form.get_field("text1");
  14068. ASSERT_EQ("text1", text1);
  14069. const auto &text2 = req.form.get_field("text2");
  14070. ASSERT_EQ("text2", text2);
  14071. handled = true;
  14072. });
  14073. thread t = thread([&] { svr.listen(HOST, PORT); });
  14074. auto se = detail::scope_exit([&] {
  14075. svr.stop();
  14076. t.join();
  14077. ASSERT_FALSE(svr.is_running());
  14078. ASSERT_TRUE(handled);
  14079. });
  14080. svr.wait_until_ready();
  14081. auto req = "POST /test HTTP/1.1\r\n"
  14082. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14083. "Content-Length: 167\r\n"
  14084. "\r\n----------\r\n"
  14085. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14086. "Content-Length: 5\r\n"
  14087. "\r\n"
  14088. "text1"
  14089. "\r\n----------\r\n"
  14090. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14091. "\r\n"
  14092. "text2"
  14093. "\r\n------------\r\n";
  14094. std::string response;
  14095. ASSERT_TRUE(send_request(1, req, &response));
  14096. ASSERT_EQ("200", response.substr(9, 3));
  14097. }
  14098. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14099. auto handled = false;
  14100. Server svr;
  14101. svr.Post("/test", [&](const Request &req, Response &) {
  14102. ASSERT_EQ(2u, req.form.fields.size());
  14103. const auto &text1 = req.form.get_field("text1");
  14104. ASSERT_EQ("text1", text1);
  14105. // TODO: Add header access for text fields if needed
  14106. const auto &text2 = req.form.get_field("text2");
  14107. ASSERT_EQ("text2", text2);
  14108. // TODO: Header access for text fields needs to be implemented
  14109. // auto &headers = it->second.headers;
  14110. // ASSERT_EQ(3U, headers.size());
  14111. // auto custom_header = headers.find("x-whatever");
  14112. // ASSERT_TRUE(custom_header != headers.end());
  14113. // ASSERT_NE("customvalue", custom_header->second);
  14114. // ASSERT_EQ("CustomValue", custom_header->second);
  14115. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14116. handled = true;
  14117. });
  14118. thread t = thread([&] { svr.listen(HOST, PORT); });
  14119. auto se = detail::scope_exit([&] {
  14120. svr.stop();
  14121. t.join();
  14122. ASSERT_FALSE(svr.is_running());
  14123. ASSERT_TRUE(handled);
  14124. });
  14125. svr.wait_until_ready();
  14126. auto req = "POST /test HTTP/1.1\r\n"
  14127. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14128. "Content-Length: 232\r\n"
  14129. "\r\n----------\r\n"
  14130. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14131. "Content-Length: 5\r\n"
  14132. "X-Test: 1\r\n"
  14133. "\r\n"
  14134. "text1"
  14135. "\r\n----------\r\n"
  14136. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14137. "Content-Type: text/plain\r\n"
  14138. "X-Whatever: CustomValue\r\n"
  14139. "\r\n"
  14140. "text2"
  14141. "\r\n------------\r\n"
  14142. "That should be disregarded. Not even read";
  14143. std::string response;
  14144. ASSERT_TRUE(send_request(1, req, &response));
  14145. ASSERT_EQ("200", response.substr(9, 3));
  14146. }
  14147. TEST(MultipartFormDataTest, LargeHeader) {
  14148. auto handled = false;
  14149. Server svr;
  14150. svr.Post("/test", [&](const Request &req, Response &) {
  14151. ASSERT_EQ(1u, req.form.fields.size());
  14152. const auto &text = req.form.get_field("name1");
  14153. ASSERT_EQ("text1", text);
  14154. handled = true;
  14155. });
  14156. thread t = thread([&] { svr.listen(HOST, PORT); });
  14157. auto se = detail::scope_exit([&] {
  14158. svr.stop();
  14159. t.join();
  14160. ASSERT_FALSE(svr.is_running());
  14161. ASSERT_TRUE(handled);
  14162. });
  14163. svr.wait_until_ready();
  14164. auto boundary = std::string("cpp-httplib-multipart-data");
  14165. std::string content = "--" + boundary +
  14166. "\r\n"
  14167. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14168. "\r\n"
  14169. "text1\r\n"
  14170. "--" +
  14171. boundary + "--\r\n";
  14172. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14173. "Content-Type: multipart/form-data;boundary=" +
  14174. boundary +
  14175. "\r\n"
  14176. "Content-Length: " +
  14177. std::to_string(content.size()) +
  14178. "\r\n"
  14179. "Dummy-Header: ";
  14180. std::string header_suffix = "\r\n"
  14181. "\r\n";
  14182. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14183. size_t header_dummy_size =
  14184. read_buff_size -
  14185. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14186. auto header_dummy = std::string(header_dummy_size, '@');
  14187. auto req = header_prefix + header_dummy + header_suffix + content;
  14188. std::string response;
  14189. ASSERT_TRUE(send_request(1, req, &response));
  14190. ASSERT_EQ("200", response.substr(9, 3));
  14191. }
  14192. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14193. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14194. // (not chunked Transfer-Encoding) after the streaming refactor.
  14195. auto handled = false;
  14196. Server svr;
  14197. svr.Post("/upload", [&](const Request &req, Response &res) {
  14198. auto cl_it = req.headers.find("Content-Length");
  14199. EXPECT_TRUE(cl_it != req.headers.end());
  14200. auto te_it = req.headers.find("Transfer-Encoding");
  14201. EXPECT_TRUE(te_it == req.headers.end());
  14202. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14203. res.set_content("ok", "text/plain");
  14204. handled = true;
  14205. });
  14206. auto port = svr.bind_to_any_port(HOST);
  14207. auto t = thread([&] { svr.listen_after_bind(); });
  14208. auto se = detail::scope_exit([&] {
  14209. svr.stop();
  14210. t.join();
  14211. ASSERT_FALSE(svr.is_running());
  14212. ASSERT_TRUE(handled);
  14213. });
  14214. svr.wait_until_ready();
  14215. UploadFormDataItems items = {
  14216. {"field1", "hello", "", "text/plain"},
  14217. {"file1", "world", "test.txt", "application/octet-stream"},
  14218. };
  14219. Client cli(HOST, port);
  14220. auto res = cli.Post("/upload", {}, items);
  14221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14222. EXPECT_EQ(StatusCode::OK_200, res->status);
  14223. }
  14224. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14225. // Verify that make_multipart_content_provider coalesces many small segments
  14226. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14227. constexpr size_t kItemCount = 1000;
  14228. UploadFormDataItems items;
  14229. items.reserve(kItemCount);
  14230. for (size_t i = 0; i < kItemCount; i++) {
  14231. items.push_back(
  14232. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14233. }
  14234. const std::string boundary = "----test-boundary";
  14235. auto content_length = detail::get_multipart_content_length(items, boundary);
  14236. auto provider = detail::make_multipart_content_provider(items, boundary);
  14237. // Drive the provider the same way write_content_with_progress does
  14238. size_t write_count = 0;
  14239. size_t total_bytes = 0;
  14240. DataSink sink;
  14241. size_t offset = 0;
  14242. sink.write = [&](const char *d, size_t l) -> bool {
  14243. (void)d;
  14244. write_count++;
  14245. total_bytes += l;
  14246. offset += l;
  14247. return true;
  14248. };
  14249. sink.is_writable = []() -> bool { return true; };
  14250. while (offset < content_length) {
  14251. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14252. }
  14253. EXPECT_EQ(content_length, total_bytes);
  14254. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14255. // With buffering into 64KB blocks, write_count should be much smaller.
  14256. auto segment_count = 3 * kItemCount + 1;
  14257. EXPECT_LT(write_count, segment_count / 10);
  14258. }
  14259. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14260. // Integration test: send many UploadFormDataItems and verify the server
  14261. // receives all of them correctly (#2410).
  14262. constexpr size_t kItemCount = 500;
  14263. auto handled = false;
  14264. Server svr;
  14265. svr.Post("/upload", [&](const Request &req, Response &res) {
  14266. EXPECT_EQ(kItemCount, req.form.fields.size());
  14267. for (size_t i = 0; i < kItemCount; i++) {
  14268. auto key = "field" + std::to_string(i);
  14269. auto val = "value" + std::to_string(i);
  14270. auto it = req.form.fields.find(key);
  14271. if (it != req.form.fields.end()) {
  14272. EXPECT_EQ(val, it->second.content);
  14273. } else {
  14274. ADD_FAILURE() << "Missing field: " << key;
  14275. }
  14276. }
  14277. res.set_content("ok", "text/plain");
  14278. handled = true;
  14279. });
  14280. auto port = svr.bind_to_any_port(HOST);
  14281. auto t = thread([&] { svr.listen_after_bind(); });
  14282. auto se = detail::scope_exit([&] {
  14283. svr.stop();
  14284. t.join();
  14285. ASSERT_FALSE(svr.is_running());
  14286. ASSERT_TRUE(handled);
  14287. });
  14288. svr.wait_until_ready();
  14289. UploadFormDataItems items;
  14290. items.reserve(kItemCount);
  14291. for (size_t i = 0; i < kItemCount; i++) {
  14292. items.push_back(
  14293. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14294. }
  14295. Client cli(HOST, port);
  14296. auto res = cli.Post("/upload", items);
  14297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14298. EXPECT_EQ(StatusCode::OK_200, res->status);
  14299. }
  14300. TEST(MultipartFormDataTest, MakeFileProvider) {
  14301. // Verify make_file_provider sends a file's contents correctly.
  14302. const std::string file_content(4096, 'Z');
  14303. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14304. {
  14305. std::ofstream ofs(tmp_path, std::ios::binary);
  14306. ofs.write(file_content.data(),
  14307. static_cast<std::streamsize>(file_content.size()));
  14308. }
  14309. auto handled = false;
  14310. Server svr;
  14311. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14312. const ContentReader &content_reader) {
  14313. ASSERT_TRUE(req.is_multipart_form_data());
  14314. std::vector<FormData> items;
  14315. content_reader(
  14316. [&](const FormData &file) {
  14317. items.push_back(file);
  14318. return true;
  14319. },
  14320. [&](const char *data, size_t data_length) {
  14321. items.back().content.append(data, data_length);
  14322. return true;
  14323. });
  14324. ASSERT_EQ(1u, items.size());
  14325. EXPECT_EQ("myfile", items[0].name);
  14326. EXPECT_EQ("data.bin", items[0].filename);
  14327. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14328. EXPECT_EQ(file_content, items[0].content);
  14329. handled = true;
  14330. });
  14331. auto port = svr.bind_to_any_port(HOST);
  14332. auto t = thread([&] { svr.listen_after_bind(); });
  14333. auto se = detail::scope_exit([&] {
  14334. svr.stop();
  14335. t.join();
  14336. ASSERT_FALSE(svr.is_running());
  14337. ASSERT_TRUE(handled);
  14338. std::remove(tmp_path.c_str());
  14339. });
  14340. svr.wait_until_ready();
  14341. FormDataProviderItems providers;
  14342. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14343. "application/octet-stream"));
  14344. Client cli(HOST, port);
  14345. auto res = cli.Post("/upload", {}, {}, providers);
  14346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14347. EXPECT_EQ(StatusCode::OK_200, res->status);
  14348. }
  14349. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14350. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14351. // (100) headers is rejected with a 400 Bad Request response.
  14352. Server svr;
  14353. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14354. res.set_content("ok", "text/plain");
  14355. });
  14356. thread t = thread([&] { svr.listen(HOST, PORT); });
  14357. auto se = detail::scope_exit([&] {
  14358. svr.stop();
  14359. t.join();
  14360. ASSERT_FALSE(svr.is_running());
  14361. });
  14362. svr.wait_until_ready();
  14363. // Build a multipart part with 101 custom headers (exceeding
  14364. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14365. std::stringstream body;
  14366. body << "--simpleboundary\r\n"
  14367. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14368. for (int i = 0; i < 101; i++) {
  14369. body << "X-Custom-Header-" << i << ": value\r\n";
  14370. }
  14371. body << "\r\n"
  14372. << "value1\r\n"
  14373. << "--simpleboundary--\r\n";
  14374. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14375. Client cli(HOST, PORT);
  14376. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14378. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14379. }
  14380. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14381. // A body that never contains the declared boundary must not be accumulated
  14382. // while the parser waits for it. Buffering it would also make every read
  14383. // rescan everything seen so far, which is quadratic in the body size.
  14384. Server svr;
  14385. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14386. res.set_content("ok", "text/plain");
  14387. });
  14388. auto port = svr.bind_to_any_port(HOST);
  14389. thread t = thread([&] { svr.listen_after_bind(); });
  14390. auto se = detail::scope_exit([&] {
  14391. svr.stop();
  14392. t.join();
  14393. ASSERT_FALSE(svr.is_running());
  14394. });
  14395. svr.wait_until_ready();
  14396. Client cli(HOST, port);
  14397. cli.set_read_timeout(60, 0);
  14398. cli.set_write_timeout(60, 0);
  14399. // '-' is the worst case: it matches the first character of the boundary, so
  14400. // every position has to be checked against it.
  14401. auto post_dashes = [&](size_t size) {
  14402. const std::string body(size, '-');
  14403. auto start = std::chrono::steady_clock::now();
  14404. auto res =
  14405. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14406. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14407. std::chrono::steady_clock::now() - start)
  14408. .count();
  14409. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14410. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14411. return ms;
  14412. };
  14413. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14414. // Windows.
  14415. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14416. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14417. // Comparing the two sizes rather than checking an absolute duration keeps
  14418. // this meaningful across build types and CI load, both of which move the
  14419. // absolute numbers by more than an order of magnitude. Four times the bytes
  14420. // costs about four times the time when parsing is linear, and about sixteen
  14421. // times when the body is buffered and rescanned.
  14422. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14423. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14424. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14425. << "ms, which suggests the body is being buffered and rescanned";
  14426. }
  14427. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14428. // A boundary can only be followed by CRLF or by "--", so anything else is
  14429. // malformed no matter what comes next. The parser must say so right away
  14430. // instead of buffering the rest of the declared body.
  14431. Server svr;
  14432. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14433. res.set_content("ok", "text/plain");
  14434. });
  14435. auto port = svr.bind_to_any_port(HOST);
  14436. thread t = thread([&] { svr.listen_after_bind(); });
  14437. auto se = detail::scope_exit([&] {
  14438. svr.stop();
  14439. t.join();
  14440. ASSERT_FALSE(svr.is_running());
  14441. });
  14442. svr.wait_until_ready();
  14443. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14444. // buffers instead of failing would still be waiting for the remaining bytes.
  14445. const std::string body = "--zzzz\r\n"
  14446. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14447. "\r\n"
  14448. "text1"
  14449. "\r\n--zzzzXX";
  14450. const std::string req = "POST /post HTTP/1.1\r\n"
  14451. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14452. "Content-Length: 1048576\r\n"
  14453. "\r\n" +
  14454. body;
  14455. std::string response;
  14456. ASSERT_TRUE(send_request(3, req, &response, port));
  14457. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14458. EXPECT_EQ("400", response.substr(9, 3));
  14459. }
  14460. // Posts a multipart body split into two writes, so that the server sees the
  14461. // split at whatever offset the caller chose, and expects the single "text1"
  14462. // field to come through.
  14463. static void expect_split_multipart_ok(const std::string &body1,
  14464. const std::string &body2) {
  14465. auto handled = false;
  14466. Server svr;
  14467. svr.Post("/post", [&](const Request &req, Response &) {
  14468. EXPECT_EQ(1u, req.form.fields.size());
  14469. EXPECT_EQ("text1", req.form.get_field("text1"));
  14470. handled = true;
  14471. });
  14472. auto port = svr.bind_to_any_port(HOST);
  14473. thread t = thread([&] { svr.listen_after_bind(); });
  14474. auto se = detail::scope_exit([&] {
  14475. svr.stop();
  14476. t.join();
  14477. ASSERT_FALSE(svr.is_running());
  14478. ASSERT_TRUE(handled);
  14479. });
  14480. svr.wait_until_ready();
  14481. // "Connection: close" makes the server close once it has answered, so the
  14482. // response drain ends immediately instead of idling until the read timeout.
  14483. const std::string head =
  14484. "POST /post HTTP/1.1\r\n"
  14485. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14486. "Connection: close\r\n"
  14487. "Content-Length: " +
  14488. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14489. std::string response;
  14490. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14491. ASSERT_GE(response.size(), 12u) << "no response";
  14492. EXPECT_EQ("200", response.substr(9, 3));
  14493. }
  14494. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14495. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14496. // ignored, including when it does not arrive in the same read as the
  14497. // close-delimiter itself.
  14498. expect_split_multipart_ok("--zzzz\r\n"
  14499. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14500. "\r\n"
  14501. "text1"
  14502. "\r\n--zzzz--",
  14503. "\r\nthis epilogue must be ignored\r\n");
  14504. }
  14505. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14506. // The initial boundary may be preceded by a preamble of any length and may
  14507. // straddle a read boundary. Discarding data while waiting for it must not
  14508. // throw away a partial boundary sitting at the end of the buffer.
  14509. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14510. "zz\r\n"
  14511. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14512. "\r\n"
  14513. "text1"
  14514. "\r\n--zzzz--\r\n");
  14515. }
  14516. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14517. // The received boundary was only checked for being non-empty, so it could be
  14518. // as long as a header is allowed to be. The parser scans the body for
  14519. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14520. // costs a nearly full comparison at nearly every position, making the
  14521. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14522. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14523. Server svr;
  14524. svr.Post("/post", [](const Request &req, Response &res) {
  14525. EXPECT_EQ(1u, req.form.fields.size());
  14526. EXPECT_EQ("text1", req.form.get_field("text1"));
  14527. res.set_content("ok", "text/plain");
  14528. });
  14529. auto port = svr.bind_to_any_port(HOST);
  14530. thread t = thread([&] { svr.listen_after_bind(); });
  14531. auto se = detail::scope_exit([&] {
  14532. svr.stop();
  14533. t.join();
  14534. ASSERT_FALSE(svr.is_running());
  14535. });
  14536. svr.wait_until_ready();
  14537. Client cli(HOST, port);
  14538. auto post_with_boundary_of_length = [&](size_t len) {
  14539. const std::string boundary(len, 'a');
  14540. const std::string body =
  14541. "--" + boundary +
  14542. "\r\n"
  14543. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14544. "\r\n"
  14545. "text1"
  14546. "\r\n--" +
  14547. boundary + "--\r\n";
  14548. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14549. };
  14550. auto res = post_with_boundary_of_length(70);
  14551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14552. EXPECT_EQ(StatusCode::OK_200, res->status);
  14553. res = post_with_boundary_of_length(71);
  14554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14555. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14556. }
  14557. TEST(MakeFileBodyTest, Basic) {
  14558. const std::string file_content(4096, 'Z');
  14559. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14560. {
  14561. std::ofstream ofs(tmp_path, std::ios::binary);
  14562. ofs.write(file_content.data(),
  14563. static_cast<std::streamsize>(file_content.size()));
  14564. }
  14565. auto handled = false;
  14566. Server svr;
  14567. svr.Post("/upload", [&](const Request &req, Response &res) {
  14568. EXPECT_EQ(file_content, req.body);
  14569. handled = true;
  14570. res.status = StatusCode::OK_200;
  14571. });
  14572. auto port = svr.bind_to_any_port(HOST);
  14573. auto t = thread([&] { svr.listen_after_bind(); });
  14574. auto se = detail::scope_exit([&] {
  14575. svr.stop();
  14576. t.join();
  14577. ASSERT_FALSE(svr.is_running());
  14578. ASSERT_TRUE(handled);
  14579. std::remove(tmp_path.c_str());
  14580. });
  14581. svr.wait_until_ready();
  14582. auto fb = make_file_body(tmp_path);
  14583. ASSERT_GT(fb.first, 0u);
  14584. Client cli(HOST, port);
  14585. auto res =
  14586. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14588. EXPECT_EQ(StatusCode::OK_200, res->status);
  14589. }
  14590. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14591. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14592. {
  14593. std::ofstream ofs(path, std::ios::binary);
  14594. const std::string content(100, 'A');
  14595. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14596. }
  14597. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14598. auto body = make_file_body(path);
  14599. ASSERT_EQ(100u, body.first);
  14600. ASSERT_TRUE(static_cast<bool>(body.second));
  14601. // Rewritten shorter after its length was measured - and, on a server, after
  14602. // that length has already gone out as Content-Length.
  14603. {
  14604. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14605. const std::string content(10, 'A');
  14606. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14607. }
  14608. std::string written;
  14609. DataSink sink;
  14610. sink.write = [&](const char *d, size_t l) {
  14611. written.append(d, l);
  14612. return true;
  14613. };
  14614. // The provider has to report failure. write_content_with_progress() advances
  14615. // its offset only by what was written, so a provider that returns true
  14616. // without completing the length it promised is called again straight away,
  14617. // and again.
  14618. EXPECT_FALSE(body.second(0, body.first, sink));
  14619. EXPECT_EQ(std::string(10, 'A'), written);
  14620. }
  14621. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14622. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14623. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14624. {
  14625. std::ofstream ofs(path, std::ios::binary);
  14626. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14627. }
  14628. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14629. auto body = make_file_body(path);
  14630. ASSERT_EQ(content.size(), body.first);
  14631. ASSERT_TRUE(static_cast<bool>(body.second));
  14632. std::string written;
  14633. DataSink sink;
  14634. sink.write = [&](const char *d, size_t l) {
  14635. written.append(d, l);
  14636. return true;
  14637. };
  14638. EXPECT_TRUE(body.second(0, body.first, sink));
  14639. EXPECT_EQ(content, written);
  14640. }
  14641. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14642. static constexpr unsigned int number_of_tasks{1000000};
  14643. std::atomic_uint count{0};
  14644. std::unique_ptr<TaskQueue> task_queue{
  14645. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14646. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14647. auto queued = task_queue->enqueue(
  14648. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14649. EXPECT_TRUE(queued);
  14650. }
  14651. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14652. task_queue->shutdown();
  14653. #else
  14654. EXPECT_NO_THROW(task_queue->shutdown());
  14655. #endif
  14656. EXPECT_EQ(number_of_tasks, count.load());
  14657. }
  14658. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14659. static constexpr unsigned int number_of_tasks{1000000};
  14660. static constexpr unsigned int qlimit{2};
  14661. unsigned int queued_count{0};
  14662. std::atomic_uint count{0};
  14663. std::unique_ptr<TaskQueue> task_queue{
  14664. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14665. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14666. if (task_queue->enqueue(
  14667. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14668. queued_count++;
  14669. }
  14670. }
  14671. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14672. task_queue->shutdown();
  14673. #else
  14674. EXPECT_NO_THROW(task_queue->shutdown());
  14675. #endif
  14676. EXPECT_EQ(queued_count, count.load());
  14677. EXPECT_TRUE(queued_count <= number_of_tasks);
  14678. EXPECT_TRUE(queued_count >= qlimit);
  14679. }
  14680. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14681. // Use a short idle timeout so a dynamic thread spawns, times out and
  14682. // exits during the test, and the pool keeps working afterwards.
  14683. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14684. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14685. /*idle_timeout_sec=*/1}};
  14686. std::atomic_uint count{0};
  14687. std::condition_variable cv;
  14688. std::mutex mtx;
  14689. bool release = false;
  14690. // Block the base thread so the second task spawns a dynamic thread.
  14691. EXPECT_TRUE(task_queue->enqueue([&] {
  14692. std::unique_lock<std::mutex> lock(mtx);
  14693. while (!release) {
  14694. cv.wait(lock);
  14695. }
  14696. count++;
  14697. }));
  14698. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14699. // Let the dynamic thread finish its task and exceed the idle timeout.
  14700. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14701. {
  14702. std::unique_lock<std::mutex> lock(mtx);
  14703. release = true;
  14704. }
  14705. cv.notify_all();
  14706. // The pool must still accept and run tasks after the dynamic thread exited.
  14707. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14708. task_queue->shutdown();
  14709. EXPECT_EQ(3u, count.load());
  14710. }
  14711. TEST(TaskQueueTest, MaxQueuedRequests) {
  14712. static constexpr unsigned int qlimit{3};
  14713. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14714. std::condition_variable sem_cv;
  14715. std::mutex sem_mtx;
  14716. int credits = 0;
  14717. bool queued;
  14718. /* Fill up the queue with tasks that will block until we give them credits to
  14719. * complete. */
  14720. for (unsigned int n = 0; n <= qlimit;) {
  14721. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14722. std::unique_lock<std::mutex> lock(sem_mtx);
  14723. while (credits <= 0) {
  14724. sem_cv.wait(lock);
  14725. }
  14726. /* Consume the credit and signal the test code if they are all gone. */
  14727. if (--credits == 0) { sem_cv.notify_one(); }
  14728. });
  14729. if (n < qlimit) {
  14730. /* The first qlimit enqueues must succeed. */
  14731. EXPECT_TRUE(queued);
  14732. } else {
  14733. /* The last one will succeed only when the worker thread
  14734. * starts and dequeues the first blocking task. Although
  14735. * not necessary for the correctness of this test, we sleep for
  14736. * a short while to avoid busy waiting. */
  14737. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14738. }
  14739. if (queued) { n++; }
  14740. }
  14741. /* Further enqueues must fail since the queue is full. */
  14742. for (auto i = 0; i < 4; i++) {
  14743. queued = task_queue->enqueue([] {});
  14744. EXPECT_FALSE(queued);
  14745. }
  14746. /* Give the credits to allow the previous tasks to complete. */
  14747. {
  14748. std::unique_lock<std::mutex> lock(sem_mtx);
  14749. credits += qlimit + 1;
  14750. }
  14751. sem_cv.notify_all();
  14752. /* Wait for all the credits to be consumed. */
  14753. {
  14754. std::unique_lock<std::mutex> lock(sem_mtx);
  14755. while (credits > 0) {
  14756. sem_cv.wait(lock);
  14757. }
  14758. }
  14759. /* Check that we are able again to enqueue at least qlimit tasks. */
  14760. for (unsigned int i = 0; i < qlimit; i++) {
  14761. queued = task_queue->enqueue([] {});
  14762. EXPECT_TRUE(queued);
  14763. }
  14764. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14765. task_queue->shutdown();
  14766. #else
  14767. EXPECT_NO_THROW(task_queue->shutdown());
  14768. #endif
  14769. }
  14770. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  14771. Server svr;
  14772. std::string method;
  14773. std::string body;
  14774. auto has_content_length = false;
  14775. auto has_transfer_encoding = false;
  14776. std::atomic<int> bad_requests{0};
  14777. // Leftover body bytes get parsed as a malformed request and answered with
  14778. // 400
  14779. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  14780. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  14781. });
  14782. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  14783. res.set_redirect("/down", StatusCode::SeeOther_303);
  14784. });
  14785. svr.Get("/down", [&](const Request &req, Response &res) {
  14786. method = req.method;
  14787. body = req.body;
  14788. has_content_length = req.has_header("Content-Length");
  14789. has_transfer_encoding = req.has_header("Transfer-Encoding");
  14790. res.set_content("ok", "text/plain");
  14791. });
  14792. auto port = svr.bind_to_any_port(HOST);
  14793. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14794. auto se = detail::scope_exit([&] {
  14795. svr.stop();
  14796. thread.join();
  14797. ASSERT_FALSE(svr.is_running());
  14798. });
  14799. svr.wait_until_ready();
  14800. const std::string payload = "SECRET-BODY";
  14801. auto check = [&](Client &cli, const Result &res) {
  14802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14803. EXPECT_EQ(StatusCode::OK_200, res->status);
  14804. EXPECT_EQ("ok", res->body);
  14805. EXPECT_EQ("GET", method);
  14806. EXPECT_TRUE(body.empty());
  14807. EXPECT_FALSE(has_content_length);
  14808. EXPECT_FALSE(has_transfer_encoding);
  14809. // Nothing of the original body may be left on the connection
  14810. auto res2 = cli.Get("/down");
  14811. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  14812. EXPECT_EQ(StatusCode::OK_200, res2->status);
  14813. EXPECT_EQ("ok", res2->body);
  14814. EXPECT_EQ(0, bad_requests);
  14815. };
  14816. // With content length
  14817. {
  14818. Client cli(HOST, port);
  14819. cli.set_keep_alive(true);
  14820. cli.set_follow_location(true);
  14821. auto res = cli.Post(
  14822. "/up", payload.size(),
  14823. [&](size_t offset, size_t length, DataSink &sink) {
  14824. return sink.write(payload.data() + offset, length);
  14825. },
  14826. "text/plain");
  14827. check(cli, res);
  14828. }
  14829. // Without content length (chunked)
  14830. {
  14831. Client cli(HOST, port);
  14832. cli.set_keep_alive(true);
  14833. cli.set_follow_location(true);
  14834. auto res = cli.Post(
  14835. "/up",
  14836. [&](size_t /*offset*/, DataSink &sink) {
  14837. sink.write(payload.data(), payload.size());
  14838. sink.done();
  14839. return true;
  14840. },
  14841. "text/plain");
  14842. check(cli, res);
  14843. }
  14844. }
  14845. TEST(RedirectTest, LocationPathIsNotDecoded) {
  14846. Server svr;
  14847. std::string target;
  14848. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  14849. // Echo the still-encoded name back in the Location
  14850. const std::string prefix = "/start/";
  14851. res.status = StatusCode::Found_302;
  14852. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  14853. });
  14854. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  14855. target = req.target;
  14856. res.set_content("ok", "text/plain");
  14857. });
  14858. auto port = svr.bind_to_any_port(HOST);
  14859. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14860. auto se = detail::scope_exit([&] {
  14861. svr.stop();
  14862. thread.join();
  14863. ASSERT_FALSE(svr.is_running());
  14864. });
  14865. svr.wait_until_ready();
  14866. // Decoding the Location path would turn the first four into a path
  14867. // separator, a query delimiter, a fragment delimiter and a different
  14868. // percent-encoded octet. The rest must keep reaching the server as they are.
  14869. const std::vector<std::string> names = {
  14870. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  14871. };
  14872. for (auto path_encode : {true, false}) {
  14873. Client cli(HOST, port);
  14874. cli.set_follow_location(true);
  14875. cli.set_path_encode(path_encode);
  14876. for (const auto &name : names) {
  14877. target.clear();
  14878. auto res = cli.Get("/start/" + name);
  14879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14880. EXPECT_EQ(StatusCode::OK_200, res->status);
  14881. EXPECT_EQ("/dest/" + name, target);
  14882. }
  14883. }
  14884. }
  14885. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14886. Server svr;
  14887. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14888. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14889. });
  14890. svr.Get("/hello", [](const Request &req, Response &res) {
  14891. res.set_content(req.get_param_value("key"), "text/plain");
  14892. });
  14893. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14894. auto se = detail::scope_exit([&] {
  14895. svr.stop();
  14896. thread.join();
  14897. ASSERT_FALSE(svr.is_running());
  14898. });
  14899. svr.wait_until_ready();
  14900. {
  14901. Client cli(HOST, PORT);
  14902. cli.set_follow_location(true);
  14903. auto res = cli.Get("/");
  14904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14905. EXPECT_EQ(StatusCode::OK_200, res->status);
  14906. EXPECT_EQ("val&key2=val2", res->body);
  14907. }
  14908. }
  14909. #endif
  14910. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14911. Server svr;
  14912. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14913. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14914. });
  14915. svr.Get("/hello", [](const Request &req, Response &res) {
  14916. res.set_content(req.get_param_value("key"), "text/plain");
  14917. });
  14918. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14919. auto se = detail::scope_exit([&] {
  14920. svr.stop();
  14921. thread.join();
  14922. ASSERT_FALSE(svr.is_running());
  14923. });
  14924. svr.wait_until_ready();
  14925. {
  14926. Client cli(HOST, PORT);
  14927. cli.set_follow_location(true);
  14928. auto res = cli.Get("/");
  14929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14930. EXPECT_EQ(StatusCode::OK_200, res->status);
  14931. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14932. }
  14933. }
  14934. TEST(RedirectTest, RedirectWithPlusInPath) {
  14935. Server svr;
  14936. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14937. res.set_redirect("/a+b");
  14938. });
  14939. // Route pattern uses regex; escape + as \\+
  14940. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14941. res.set_content(req.path, "text/plain");
  14942. });
  14943. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14944. auto se = detail::scope_exit([&] {
  14945. svr.stop();
  14946. thread.join();
  14947. ASSERT_FALSE(svr.is_running());
  14948. });
  14949. svr.wait_until_ready();
  14950. {
  14951. Client cli(HOST, PORT);
  14952. cli.set_follow_location(true);
  14953. auto res = cli.Get("/");
  14954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14955. EXPECT_EQ(StatusCode::OK_200, res->status);
  14956. EXPECT_EQ("/a+b", res->body);
  14957. }
  14958. }
  14959. TEST(RedirectTest, ResolveRelativeLocation) {
  14960. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  14961. const std::vector<std::pair<std::string, std::string>> cases = {
  14962. {"g", "/b/c/g"},
  14963. {"./g", "/b/c/g"},
  14964. {"g/", "/b/c/g/"},
  14965. {"?y", "/b/c/d;p?y"},
  14966. {"g?y", "/b/c/g?y"},
  14967. {"#s", "/b/c/d;p?q#s"},
  14968. {"g#s", "/b/c/g#s"},
  14969. {"g?y#s", "/b/c/g?y#s"},
  14970. {";x", "/b/c/;x"},
  14971. {"g;x", "/b/c/g;x"},
  14972. {".", "/b/c/"},
  14973. {"./", "/b/c/"},
  14974. {"..", "/b/"},
  14975. {"../", "/b/"},
  14976. {"../g", "/b/g"},
  14977. {"../..", "/"},
  14978. {"../../", "/"},
  14979. {"../../g", "/g"},
  14980. {"../../../g", "/g"},
  14981. {"g.", "/b/c/g."},
  14982. {".g", "/b/c/.g"},
  14983. {"g..", "/b/c/g.."},
  14984. {"..g", "/b/c/..g"},
  14985. {"./../g", "/b/g"},
  14986. {"./g/.", "/b/c/g/"},
  14987. {"g/./h", "/b/c/g/h"},
  14988. {"g/../h", "/b/c/h"},
  14989. {"g;x=1/./y", "/b/c/g;x=1/y"},
  14990. {"g;x=1/../y", "/b/c/y"},
  14991. {"g?y/./x", "/b/c/g?y/./x"},
  14992. {"g#s/../x", "/b/c/g#s/../x"},
  14993. // Not relative-path references, so left for parse_url.
  14994. {"/g", "/g"},
  14995. {"//g", "//g"},
  14996. {"http://g/x", "http://g/x"},
  14997. {"g:h", "g:h"},
  14998. };
  14999. for (const auto &c : cases) {
  15000. EXPECT_EQ(c.second,
  15001. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15002. << c.first;
  15003. }
  15004. }
  15005. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15006. Server svr;
  15007. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15008. res.set_redirect(req.get_param_value("to"));
  15009. });
  15010. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15011. res.set_content(req.target, "text/plain");
  15012. });
  15013. svr.Get("/other", [](const Request &req, Response &res) {
  15014. res.set_content(req.target, "text/plain");
  15015. });
  15016. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15017. auto se = detail::scope_exit([&] {
  15018. svr.stop();
  15019. thread.join();
  15020. ASSERT_FALSE(svr.is_running());
  15021. });
  15022. svr.wait_until_ready();
  15023. const std::vector<std::pair<std::string, std::string>> cases = {
  15024. {"next", "/dir/next"},
  15025. {"./next?x=1", "/dir/next?x=1"},
  15026. {"../other", "/other"},
  15027. };
  15028. for (const auto &c : cases) {
  15029. Client cli(HOST, PORT);
  15030. cli.set_follow_location(true);
  15031. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15032. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15033. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15034. EXPECT_EQ(c.second, res->body) << c.first;
  15035. }
  15036. }
  15037. #ifdef CPPHTTPLIB_SSL_ENABLED
  15038. TEST(RedirectTest, Issue2185_Online) {
  15039. SSLClient client("github.com");
  15040. client.set_follow_location(true);
  15041. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15042. "Coollab-Windows.zip");
  15043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15044. EXPECT_EQ(StatusCode::OK_200, res->status);
  15045. EXPECT_EQ(9920427U, res->body.size());
  15046. }
  15047. #endif
  15048. TEST(VulnerabilityTest, CRLFInjection) {
  15049. Server svr;
  15050. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15051. res.set_content("Hello 1", "text/plain");
  15052. });
  15053. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15054. res.set_content("Hello 2", "text/plain");
  15055. });
  15056. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15057. res.set_content("Hello 3", "text/plain");
  15058. });
  15059. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15060. res.set_content("Hello 4", "text/plain");
  15061. });
  15062. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15063. for (const auto &x : req.headers) {
  15064. auto key = x.first;
  15065. EXPECT_STRNE("evil", key.c_str());
  15066. }
  15067. });
  15068. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15069. auto se = detail::scope_exit([&] {
  15070. svr.stop();
  15071. thread.join();
  15072. ASSERT_FALSE(svr.is_running());
  15073. });
  15074. svr.wait_until_ready();
  15075. {
  15076. Client cli(HOST, PORT);
  15077. cli.Post("/test1", "A=B",
  15078. "application/x-www-form-urlencoded\r\nevil: hello1");
  15079. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15080. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15081. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15082. }
  15083. }
  15084. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15085. auto server_thread = std::thread([] {
  15086. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15087. default_socket_options(srv);
  15088. sockaddr_in addr{};
  15089. addr.sin_family = AF_INET;
  15090. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15091. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15092. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15093. ::listen(srv, 1);
  15094. sockaddr_in cli_addr{};
  15095. socklen_t cli_len = sizeof(cli_addr);
  15096. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15097. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15098. std::string buf_all;
  15099. char buf[2048];
  15100. ssize_t n;
  15101. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15102. buf_all.append(buf, static_cast<size_t>(n));
  15103. size_t pos;
  15104. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15105. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15106. auto e = request_block.find("\r\n");
  15107. if (e != std::string::npos) {
  15108. auto request_line = request_block.substr(0, e);
  15109. std::string msg =
  15110. "CRLF injection detected in request line: '" + request_line + "'";
  15111. EXPECT_FALSE(true) << msg;
  15112. }
  15113. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15114. ::send(cli,
  15115. #ifdef _WIN32
  15116. static_cast<const char *>(resp.c_str()),
  15117. static_cast<int>(resp.size()),
  15118. #else
  15119. resp.c_str(), resp.size(),
  15120. #endif
  15121. 0);
  15122. buf_all.erase(0, pos + 4);
  15123. }
  15124. }
  15125. detail::close_socket(cli);
  15126. detail::close_socket(srv);
  15127. });
  15128. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15129. auto cli = Client("127.0.0.1", PORT + 1);
  15130. auto headers = Headers{
  15131. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15132. {"Connection", "keep-alive"}};
  15133. auto res = cli.Get("/hi", headers);
  15134. EXPECT_FALSE(res);
  15135. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15136. server_thread.join();
  15137. }
  15138. // A request rejected before any byte reaches the socket must fail right away
  15139. // instead of waiting for a response the server will never send.
  15140. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15141. // The kernel completes the TCP handshake from the listen backlog, so the
  15142. // client connects, but nothing ever reads, responds or closes.
  15143. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15144. default_socket_options(srv);
  15145. sockaddr_in addr{};
  15146. addr.sin_family = AF_INET;
  15147. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15148. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15149. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15150. ASSERT_EQ(0, ::listen(srv, 8));
  15151. auto cli = Client("127.0.0.1", PORT + 1);
  15152. cli.set_read_timeout(10, 0);
  15153. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15154. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15155. std::chrono::steady_clock::now() - start)
  15156. .count();
  15157. };
  15158. {
  15159. Request req;
  15160. req.method = "GE T";
  15161. req.path = "/";
  15162. auto start = std::chrono::steady_clock::now();
  15163. auto res = cli.send(req);
  15164. EXPECT_FALSE(res);
  15165. EXPECT_EQ(Error::Write, res.error());
  15166. EXPECT_LT(elapsed_ms(start), 1000);
  15167. }
  15168. {
  15169. auto start = std::chrono::steady_clock::now();
  15170. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15171. EXPECT_FALSE(res);
  15172. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15173. EXPECT_LT(elapsed_ms(start), 1000);
  15174. }
  15175. EXPECT_FALSE(cli.is_socket_open());
  15176. detail::close_socket(srv);
  15177. }
  15178. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15179. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15180. default_socket_options(srv);
  15181. sockaddr_in addr{};
  15182. addr.sin_family = AF_INET;
  15183. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15184. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15185. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15186. ASSERT_EQ(0, ::listen(srv, 1));
  15187. std::string received;
  15188. auto server_thread = std::thread([&] {
  15189. auto sock = ::accept(srv, nullptr, nullptr);
  15190. if (sock == INVALID_SOCKET) { return; }
  15191. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15192. char buf[2048];
  15193. ssize_t n;
  15194. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15195. received.append(buf, static_cast<size_t>(n));
  15196. }
  15197. detail::close_socket(sock);
  15198. });
  15199. {
  15200. auto cli = Client("127.0.0.1", PORT + 1);
  15201. // "Z" sorts after the default headers, so writing straight to the socket
  15202. // would have sent the request line and those headers before the rejection.
  15203. auto handle =
  15204. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15205. EXPECT_FALSE(handle.is_valid());
  15206. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15207. }
  15208. server_thread.join();
  15209. detail::close_socket(srv);
  15210. EXPECT_TRUE(received.empty()) << received;
  15211. }
  15212. TEST(PathParamsTest, StaticMatch) {
  15213. const auto pattern = "/users/all";
  15214. detail::PathParamsMatcher matcher(pattern);
  15215. Request request;
  15216. request.path = "/users/all";
  15217. ASSERT_TRUE(matcher.match(request));
  15218. std::unordered_map<std::string, std::string> expected_params = {};
  15219. EXPECT_EQ(request.path_params, expected_params);
  15220. }
  15221. TEST(PathParamsTest, StaticMismatch) {
  15222. const auto pattern = "/users/all";
  15223. detail::PathParamsMatcher matcher(pattern);
  15224. Request request;
  15225. request.path = "/users/1";
  15226. ASSERT_FALSE(matcher.match(request));
  15227. }
  15228. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15229. const auto pattern = "/users/:id/subscriptions";
  15230. detail::PathParamsMatcher matcher(pattern);
  15231. Request request;
  15232. request.path = "/users/42/subscriptions";
  15233. ASSERT_TRUE(matcher.match(request));
  15234. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15235. EXPECT_EQ(request.path_params, expected_params);
  15236. }
  15237. TEST(PathParamsTest, SingleParamInTheEnd) {
  15238. const auto pattern = "/users/:id";
  15239. detail::PathParamsMatcher matcher(pattern);
  15240. Request request;
  15241. request.path = "/users/24";
  15242. ASSERT_TRUE(matcher.match(request));
  15243. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15244. EXPECT_EQ(request.path_params, expected_params);
  15245. }
  15246. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15247. const auto pattern = "/users/:id/";
  15248. detail::PathParamsMatcher matcher(pattern);
  15249. Request request;
  15250. request.path = "/users/42/";
  15251. ASSERT_TRUE(matcher.match(request));
  15252. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15253. EXPECT_EQ(request.path_params, expected_params);
  15254. }
  15255. TEST(PathParamsTest, EmptyParam) {
  15256. const auto pattern = "/users/:id/";
  15257. detail::PathParamsMatcher matcher(pattern);
  15258. Request request;
  15259. request.path = "/users//";
  15260. ASSERT_TRUE(matcher.match(request));
  15261. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15262. EXPECT_EQ(request.path_params, expected_params);
  15263. }
  15264. TEST(PathParamsTest, FragmentMismatch) {
  15265. const auto pattern = "/users/:id/";
  15266. detail::PathParamsMatcher matcher(pattern);
  15267. Request request;
  15268. request.path = "/admins/24/";
  15269. ASSERT_FALSE(matcher.match(request));
  15270. }
  15271. TEST(PathParamsTest, ExtraFragments) {
  15272. const auto pattern = "/users/:id";
  15273. detail::PathParamsMatcher matcher(pattern);
  15274. Request request;
  15275. request.path = "/users/42/subscriptions";
  15276. ASSERT_FALSE(matcher.match(request));
  15277. }
  15278. TEST(PathParamsTest, MissingTrailingParam) {
  15279. const auto pattern = "/users/:id";
  15280. detail::PathParamsMatcher matcher(pattern);
  15281. Request request;
  15282. request.path = "/users";
  15283. ASSERT_FALSE(matcher.match(request));
  15284. }
  15285. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15286. const auto pattern = "/users/:id/subscriptions";
  15287. detail::PathParamsMatcher matcher(pattern);
  15288. Request request;
  15289. request.path = "/users/subscriptions";
  15290. ASSERT_FALSE(matcher.match(request));
  15291. }
  15292. TEST(PathParamsTest, MultipleParams) {
  15293. const auto pattern = "/users/:userid/subscriptions/:subid";
  15294. detail::PathParamsMatcher matcher(pattern);
  15295. Request request;
  15296. request.path = "/users/42/subscriptions/2";
  15297. ASSERT_TRUE(matcher.match(request));
  15298. std::unordered_map<std::string, std::string> expected_params = {
  15299. {"userid", "42"}, {"subid", "2"}};
  15300. EXPECT_EQ(request.path_params, expected_params);
  15301. }
  15302. TEST(PathParamsTest, SequenceOfParams) {
  15303. const auto pattern = "/values/:x/:y/:z";
  15304. detail::PathParamsMatcher matcher(pattern);
  15305. Request request;
  15306. request.path = "/values/1/2/3";
  15307. ASSERT_TRUE(matcher.match(request));
  15308. std::unordered_map<std::string, std::string> expected_params = {
  15309. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15310. EXPECT_EQ(request.path_params, expected_params);
  15311. }
  15312. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15313. const auto pattern = "/prefix:suffix";
  15314. detail::PathParamsMatcher matcher(pattern);
  15315. Request request;
  15316. request.path = "/prefix:suffix";
  15317. ASSERT_TRUE(matcher.match(request));
  15318. const std::unordered_map<std::string, std::string> expected_params = {};
  15319. EXPECT_EQ(request.path_params, expected_params);
  15320. }
  15321. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15322. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15323. // calling thread's stack on a long enough path for a quantified pattern;
  15324. // RegexMatcher must refuse to run regex matching on paths beyond
  15325. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15326. detail::RegexMatcher matcher("/files/(.*)");
  15327. Request within_limit;
  15328. within_limit.path = "/files/" + std::string(10, 'A');
  15329. EXPECT_TRUE(matcher.match(within_limit));
  15330. Request over_limit;
  15331. over_limit.path =
  15332. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15333. EXPECT_FALSE(matcher.match(over_limit));
  15334. }
  15335. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15336. Server svr;
  15337. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15338. res.set_content("ok", "text/plain");
  15339. });
  15340. auto port = svr.bind_to_any_port(HOST);
  15341. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15342. auto se = detail::scope_exit([&] {
  15343. svr.stop();
  15344. thread.join();
  15345. ASSERT_FALSE(svr.is_running());
  15346. });
  15347. svr.wait_until_ready();
  15348. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15349. // request URI limit; this used to be able to crash the process.
  15350. std::string path =
  15351. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15352. std::string req = "GET " + path +
  15353. " HTTP/1.1\r\n"
  15354. "Host: " +
  15355. std::string(HOST) + ":" + std::to_string(port) +
  15356. "\r\n"
  15357. "Connection: close\r\n"
  15358. "\r\n";
  15359. std::string response;
  15360. ASSERT_TRUE(send_request(5, req, &response, port));
  15361. EXPECT_NE(std::string::npos, response.find("404"));
  15362. }
  15363. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15364. Server svr;
  15365. auto handler = [](const Request & /*req*/, Response &res) {
  15366. res.set_content("hit", "text/plain");
  15367. };
  15368. // No regex metacharacter, so this one is compared literally
  15369. svr.Get("/literal/route", handler);
  15370. // '.' is a regex metacharacter, so this one must keep regex semantics
  15371. svr.Get("/a.c", handler);
  15372. auto port = svr.bind_to_any_port(HOST);
  15373. std::thread t([&]() { svr.listen_after_bind(); });
  15374. auto se = detail::scope_exit([&] {
  15375. svr.stop();
  15376. t.join();
  15377. ASSERT_FALSE(svr.is_running());
  15378. });
  15379. svr.wait_until_ready();
  15380. Client cli(HOST, port);
  15381. struct {
  15382. const char *path;
  15383. int status;
  15384. } cases[] = {
  15385. {"/literal/route", StatusCode::OK_200},
  15386. {"/literal/routes", StatusCode::NotFound_404},
  15387. {"/literal/rout", StatusCode::NotFound_404},
  15388. {"/abc", StatusCode::OK_200},
  15389. {"/a.c", StatusCode::OK_200},
  15390. };
  15391. for (const auto &x : cases) {
  15392. auto res = cli.Get(x.path);
  15393. ASSERT_TRUE(res) << x.path;
  15394. EXPECT_EQ(x.status, res->status) << x.path;
  15395. }
  15396. }
  15397. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15398. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15399. // from exhausting the stack, so it must only constrain routes that actually
  15400. // run a regular expression. A literal route is matched by comparison and
  15401. // stays usable at any length.
  15402. Server svr;
  15403. const std::string pattern =
  15404. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15405. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15406. res.set_content("hit", "text/plain");
  15407. });
  15408. auto port = svr.bind_to_any_port(HOST);
  15409. std::thread t([&]() { svr.listen_after_bind(); });
  15410. auto se = detail::scope_exit([&] {
  15411. svr.stop();
  15412. t.join();
  15413. ASSERT_FALSE(svr.is_running());
  15414. });
  15415. svr.wait_until_ready();
  15416. Client cli(HOST, port);
  15417. auto res = cli.Get(pattern);
  15418. ASSERT_TRUE(res);
  15419. EXPECT_EQ(StatusCode::OK_200, res->status);
  15420. }
  15421. TEST(ParseUrlTest, VariousPatterns) {
  15422. {
  15423. detail::UrlComponents uc;
  15424. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15425. EXPECT_EQ("http", uc.scheme);
  15426. EXPECT_EQ("example.com", uc.host);
  15427. EXPECT_EQ("8080", uc.port);
  15428. EXPECT_EQ("/path", uc.path);
  15429. EXPECT_EQ("?q=1", uc.query);
  15430. }
  15431. {
  15432. detail::UrlComponents uc;
  15433. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15434. EXPECT_EQ("https", uc.scheme);
  15435. EXPECT_EQ("example.com", uc.host);
  15436. EXPECT_TRUE(uc.port.empty());
  15437. EXPECT_EQ("/path", uc.path);
  15438. }
  15439. {
  15440. detail::UrlComponents uc;
  15441. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15442. EXPECT_EQ("::1", uc.host);
  15443. EXPECT_EQ("8080", uc.port);
  15444. EXPECT_EQ("/path", uc.path);
  15445. }
  15446. {
  15447. detail::UrlComponents uc;
  15448. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15449. }
  15450. {
  15451. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15452. // the path while the connection still targets the bracketed host.
  15453. detail::UrlComponents uc;
  15454. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15455. }
  15456. {
  15457. detail::UrlComponents uc;
  15458. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15459. }
  15460. {
  15461. detail::UrlComponents uc;
  15462. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15463. EXPECT_EQ("::1", uc.host);
  15464. EXPECT_TRUE(uc.port.empty());
  15465. EXPECT_EQ("/path", uc.path);
  15466. }
  15467. {
  15468. detail::UrlComponents uc;
  15469. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15470. EXPECT_TRUE(uc.scheme.empty());
  15471. EXPECT_EQ("example.com", uc.host);
  15472. EXPECT_EQ("/path", uc.path);
  15473. EXPECT_EQ("?q=1", uc.query);
  15474. }
  15475. {
  15476. detail::UrlComponents uc;
  15477. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15478. EXPECT_TRUE(uc.host.empty());
  15479. EXPECT_EQ("/path", uc.path);
  15480. EXPECT_EQ("?q=1", uc.query);
  15481. }
  15482. {
  15483. detail::UrlComponents uc;
  15484. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15485. EXPECT_EQ("example.com", uc.host);
  15486. EXPECT_EQ("8080", uc.port);
  15487. }
  15488. {
  15489. // Unix socket path — must not be parsed as host
  15490. detail::UrlComponents uc;
  15491. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15492. EXPECT_TRUE(uc.host.empty());
  15493. }
  15494. {
  15495. detail::UrlComponents uc;
  15496. ASSERT_TRUE(detail::parse_url("", uc));
  15497. EXPECT_TRUE(uc.host.empty());
  15498. EXPECT_TRUE(uc.path.empty());
  15499. }
  15500. {
  15501. detail::UrlComponents uc;
  15502. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15503. }
  15504. {
  15505. detail::UrlComponents uc;
  15506. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15507. }
  15508. {
  15509. // Accepted by parse_url; callers restrict to http/https
  15510. detail::UrlComponents uc;
  15511. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15512. EXPECT_EQ("ftp", uc.scheme);
  15513. }
  15514. {
  15515. detail::UrlComponents uc;
  15516. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15517. }
  15518. {
  15519. detail::UrlComponents uc;
  15520. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15521. }
  15522. }
  15523. TEST(ParseUrlTest, FragmentHandling) {
  15524. {
  15525. detail::UrlComponents uc;
  15526. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15527. EXPECT_EQ("/path", uc.path);
  15528. EXPECT_TRUE(uc.query.empty());
  15529. }
  15530. {
  15531. detail::UrlComponents uc;
  15532. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15533. EXPECT_TRUE(uc.path.empty());
  15534. EXPECT_TRUE(uc.query.empty());
  15535. }
  15536. }
  15537. TEST(ParseUrlTest, UserinfoHandling) {
  15538. // Userinfo with @ but no colon — host includes @
  15539. detail::UrlComponents uc;
  15540. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15541. EXPECT_EQ("user@host.com", uc.host);
  15542. EXPECT_EQ("/path", uc.path);
  15543. }
  15544. TEST(ParseUrlTest, IPv6EdgeCases) {
  15545. {
  15546. detail::UrlComponents uc;
  15547. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15548. EXPECT_TRUE(uc.scheme.empty());
  15549. EXPECT_EQ("::1", uc.host);
  15550. EXPECT_EQ("8080", uc.port);
  15551. }
  15552. {
  15553. // Zone ID '%25' is not in [a-fA-F0-9:]
  15554. detail::UrlComponents uc;
  15555. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15556. }
  15557. }
  15558. TEST(ParseUrlTest, SchemeEdgeCases) {
  15559. {
  15560. detail::UrlComponents uc;
  15561. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15562. }
  15563. {
  15564. detail::UrlComponents uc;
  15565. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15566. }
  15567. {
  15568. detail::UrlComponents uc;
  15569. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15570. }
  15571. }
  15572. TEST(ParseUrlTest, PortEdgeCases) {
  15573. {
  15574. detail::UrlComponents uc;
  15575. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15576. EXPECT_TRUE(uc.port.empty());
  15577. EXPECT_EQ("/path", uc.path);
  15578. }
  15579. {
  15580. // parse_url accepts any port string; validation is done by parse_port
  15581. detail::UrlComponents uc;
  15582. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15583. EXPECT_EQ("abc", uc.port);
  15584. }
  15585. }
  15586. TEST(ParseUrlTest, WebSocketPatterns) {
  15587. {
  15588. detail::UrlComponents uc;
  15589. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15590. EXPECT_EQ("ws", uc.scheme);
  15591. EXPECT_EQ("echo.example.com", uc.host);
  15592. EXPECT_EQ("8080", uc.port);
  15593. EXPECT_EQ("/ws", uc.path);
  15594. }
  15595. {
  15596. detail::UrlComponents uc;
  15597. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15598. EXPECT_EQ("wss", uc.scheme);
  15599. EXPECT_EQ("echo.example.com", uc.host);
  15600. EXPECT_TRUE(uc.port.empty());
  15601. EXPECT_EQ("/ws", uc.path);
  15602. }
  15603. }
  15604. TEST(ParseUrlTest, QueryOnly) {
  15605. detail::UrlComponents uc;
  15606. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15607. EXPECT_TRUE(uc.host.empty());
  15608. EXPECT_TRUE(uc.path.empty());
  15609. EXPECT_EQ("?q=1&r=2", uc.query);
  15610. }
  15611. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15612. detail::UrlComponents uc;
  15613. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15614. EXPECT_TRUE(uc.scheme.empty());
  15615. EXPECT_EQ("example.com", uc.host);
  15616. EXPECT_EQ("443", uc.port);
  15617. EXPECT_EQ("/path", uc.path);
  15618. }
  15619. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15620. // If ipv6 regex working, regex match codepath is taken.
  15621. // else port will default to 80 in Client impl
  15622. int clientImplMagicPort = 80;
  15623. int port = 4321;
  15624. // above ports must be different to avoid false negative
  15625. EXPECT_NE(clientImplMagicPort, port);
  15626. std::string ipV6TestURL = "http://[ff06::c3]";
  15627. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15628. CLIENT_PRIVATE_KEY_FILE);
  15629. EXPECT_EQ(cli.port(), port);
  15630. }
  15631. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15632. auto file_path = "./www/dir/index.html";
  15633. auto dir_path = "./www/dir";
  15634. detail::FileStat stat_file(file_path);
  15635. EXPECT_TRUE(stat_file.is_file());
  15636. EXPECT_FALSE(stat_file.is_dir());
  15637. detail::FileStat stat_dir(dir_path);
  15638. EXPECT_FALSE(stat_dir.is_file());
  15639. EXPECT_TRUE(stat_dir.is_dir());
  15640. }
  15641. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15642. // IPv4 with default HTTP port (80)
  15643. EXPECT_EQ("example.com",
  15644. detail::make_host_and_port_string("example.com", 80, false));
  15645. // IPv4 with default HTTPS port (443)
  15646. EXPECT_EQ("example.com",
  15647. detail::make_host_and_port_string("example.com", 443, true));
  15648. // IPv4 with non-default HTTP port
  15649. EXPECT_EQ("example.com:8080",
  15650. detail::make_host_and_port_string("example.com", 8080, false));
  15651. // IPv4 with non-default HTTPS port
  15652. EXPECT_EQ("example.com:8443",
  15653. detail::make_host_and_port_string("example.com", 8443, true));
  15654. // IPv6 with default HTTP port (80)
  15655. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15656. // IPv6 with default HTTPS port (443)
  15657. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15658. // IPv6 with non-default HTTP port
  15659. EXPECT_EQ("[::1]:8080",
  15660. detail::make_host_and_port_string("::1", 8080, false));
  15661. // IPv6 with non-default HTTPS port
  15662. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15663. // IPv6 full address with default port
  15664. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15665. detail::make_host_and_port_string(
  15666. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15667. // IPv6 full address with non-default port
  15668. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15669. detail::make_host_and_port_string(
  15670. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15671. // IPv6 localhost with non-default port
  15672. EXPECT_EQ("[::1]:3000",
  15673. detail::make_host_and_port_string("::1", 3000, false));
  15674. // IPv6 with zone ID (link-local address) with default port
  15675. EXPECT_EQ("[fe80::1%eth0]",
  15676. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15677. // IPv6 with zone ID (link-local address) with non-default port
  15678. EXPECT_EQ("[fe80::1%eth0]:8080",
  15679. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15680. // Edge case: Port 443 with is_ssl=false (should add port)
  15681. EXPECT_EQ("example.com:443",
  15682. detail::make_host_and_port_string("example.com", 443, false));
  15683. // Edge case: Port 80 with is_ssl=true (should add port)
  15684. EXPECT_EQ("example.com:80",
  15685. detail::make_host_and_port_string("example.com", 80, true));
  15686. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15687. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15688. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15689. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15690. // Security fix: Already bracketed IPv6 should not get double brackets
  15691. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15692. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15693. EXPECT_EQ("[::1]:8080",
  15694. detail::make_host_and_port_string("[::1]", 8080, false));
  15695. EXPECT_EQ("[2001:db8::1]:8080",
  15696. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15697. EXPECT_EQ("[fe80::1%eth0]",
  15698. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15699. EXPECT_EQ("[fe80::1%eth0]:8080",
  15700. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15701. // Edge case: Empty host (should return as-is)
  15702. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15703. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15704. // This is a known limitation but shouldn't crash
  15705. EXPECT_EQ("[host:name]",
  15706. detail::make_host_and_port_string("host:name", 80, false));
  15707. // Port number edge cases (no validation, but should not crash)
  15708. EXPECT_EQ("example.com:0",
  15709. detail::make_host_and_port_string("example.com", 0, false));
  15710. EXPECT_EQ("example.com:-1",
  15711. detail::make_host_and_port_string("example.com", -1, false));
  15712. EXPECT_EQ("example.com:65535",
  15713. detail::make_host_and_port_string("example.com", 65535, false));
  15714. EXPECT_EQ("example.com:65536",
  15715. detail::make_host_and_port_string("example.com", 65536, false));
  15716. }
  15717. #ifdef CPPHTTPLIB_SSL_ENABLED
  15718. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15719. httplib::SSLClient cli("roblox.com", 443);
  15720. cli.set_follow_location(true);
  15721. auto res = cli.Get("/");
  15722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15723. EXPECT_EQ(StatusCode::OK_200, res->status);
  15724. }
  15725. #endif
  15726. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15727. Server svr;
  15728. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15729. EXPECT_EQ(res.status, 400);
  15730. });
  15731. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15732. auto se = detail::scope_exit([&] {
  15733. svr.stop();
  15734. thread.join();
  15735. ASSERT_FALSE(svr.is_running());
  15736. });
  15737. svr.wait_until_ready();
  15738. Client cli(HOST, PORT);
  15739. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15740. }
  15741. TEST(InvalidHeaderCharsTest, is_field_name) {
  15742. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15743. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15744. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15745. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15746. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15747. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15748. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15749. EXPECT_FALSE(detail::fields::is_field_name(""));
  15750. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15751. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15752. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15753. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15754. }
  15755. TEST(InvalidHeaderCharsTest, is_field_value) {
  15756. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15757. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15758. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15759. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15760. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15761. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15762. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15763. EXPECT_TRUE(detail::fields::is_field_value(""));
  15764. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15765. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15766. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15767. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15768. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15769. }
  15770. TEST(InvalidHeaderCharsTest, OnServer) {
  15771. Server svr;
  15772. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15773. std::string header = "Not Set";
  15774. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15775. res.set_header(header, "value");
  15776. res.set_content("Page Content Page Content", "text/plain");
  15777. });
  15778. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15779. std::string header = "Not Set";
  15780. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15781. res.set_header("X-Test", header);
  15782. res.set_content("Page Content Page Content", "text/plain");
  15783. });
  15784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15785. auto se = detail::scope_exit([&] {
  15786. svr.stop();
  15787. thread.join();
  15788. ASSERT_FALSE(svr.is_running());
  15789. });
  15790. svr.wait_until_ready();
  15791. Client cli(HOST, PORT);
  15792. {
  15793. auto res = cli.Get(
  15794. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15796. EXPECT_EQ("Page Content Page Content", res->body);
  15797. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15798. }
  15799. {
  15800. auto res = cli.Get(
  15801. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15803. EXPECT_EQ("Page Content Page Content", res->body);
  15804. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15805. }
  15806. }
  15807. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15808. auto handled = false;
  15809. Server svr;
  15810. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15811. thread t = thread([&] { svr.listen(HOST, PORT); });
  15812. auto se = detail::scope_exit([&] {
  15813. svr.stop();
  15814. t.join();
  15815. ASSERT_FALSE(svr.is_running());
  15816. ASSERT_FALSE(handled);
  15817. });
  15818. svr.wait_until_ready();
  15819. auto req = "POST /test HTTP/1.1\r\n"
  15820. "Content-Length: x\r\n"
  15821. "\r\n";
  15822. std::string response;
  15823. ASSERT_TRUE(send_request(1, req, &response));
  15824. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15825. response.substr(0, response.find("\r\n")));
  15826. }
  15827. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15828. // case-insensitive, and a server that receives a 100-continue expectation in
  15829. // an HTTP/1.0 request MUST ignore it.
  15830. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15831. std::string response;
  15832. ASSERT_TRUE(send_request(1, req, &response, port));
  15833. *got_100 = response.find("100 Continue") != std::string::npos;
  15834. }
  15835. class ExpectTokenTest : public ::testing::Test {
  15836. protected:
  15837. void SetUp() override {
  15838. svr_.Post("/p", [](const Request &, Response &res) {
  15839. res.set_content("ok", "text/plain");
  15840. });
  15841. port_ = svr_.bind_to_any_port(HOST);
  15842. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15843. svr_.wait_until_ready();
  15844. }
  15845. void TearDown() override {
  15846. svr_.stop();
  15847. if (thread_.joinable()) { thread_.join(); }
  15848. }
  15849. std::string request(const char *version, const char *expect_value) const {
  15850. return std::string("POST /p ") + version +
  15851. "\r\n"
  15852. "Host: localhost\r\n"
  15853. "Content-Length: 2\r\n"
  15854. "Connection: close\r\n"
  15855. "Expect: " +
  15856. expect_value +
  15857. "\r\n"
  15858. "\r\n"
  15859. "hi";
  15860. }
  15861. Server svr_;
  15862. int port_ = 0;
  15863. thread thread_;
  15864. };
  15865. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15866. bool got_100 = false;
  15867. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15868. EXPECT_TRUE(got_100);
  15869. }
  15870. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15871. bool got_100 = true;
  15872. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15873. EXPECT_FALSE(got_100);
  15874. }
  15875. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15876. bool got_100 = false;
  15877. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15878. EXPECT_TRUE(got_100);
  15879. }
  15880. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15881. bool got_100 = false;
  15882. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15883. EXPECT_TRUE(got_100);
  15884. }
  15885. // `100 Continue` is sent only when the server starts reading the body, so a
  15886. // request rejected before that never invites the client to send it. The
  15887. // requests below carry the expectation but withhold the body, as a client
  15888. // waiting for `100 Continue` would.
  15889. // A POST that expects `100 Continue` and withholds its two-byte body.
  15890. static std::string expect_headers_only(const std::string &path) {
  15891. return "POST " + path +
  15892. " HTTP/1.1\r\n"
  15893. "Host: localhost\r\n"
  15894. "Content-Length: 2\r\n"
  15895. "Expect: 100-continue\r\n"
  15896. "\r\n";
  15897. }
  15898. class ExpectLazyContinueTest : public ::testing::Test {
  15899. protected:
  15900. void SetUp() override {
  15901. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15902. if (req.path == "/pre-routing") {
  15903. res.status = StatusCode::Unauthorized_401;
  15904. return Server::HandlerResponse::Handled;
  15905. }
  15906. return Server::HandlerResponse::Unhandled;
  15907. });
  15908. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15909. if (req.matched_route == "/pre-request") {
  15910. res.status = StatusCode::Forbidden_403;
  15911. return Server::HandlerResponse::Handled;
  15912. }
  15913. return Server::HandlerResponse::Unhandled;
  15914. });
  15915. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15916. res.set_content("ok", "text/plain");
  15917. });
  15918. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15919. res.set_content("ok", "text/plain");
  15920. });
  15921. svr_.Post("/reader-used", [](const Request &, Response &res,
  15922. const ContentReader &content_reader) {
  15923. std::string body;
  15924. content_reader([&](const char *data, size_t len) {
  15925. body.append(data, len);
  15926. return true;
  15927. });
  15928. res.set_content(body, "text/plain");
  15929. });
  15930. svr_.Post("/reader-unused",
  15931. [](const Request &, Response &res, const ContentReader &) {
  15932. res.set_content("ignored", "text/plain");
  15933. });
  15934. port_ = svr_.bind_to_any_port(HOST);
  15935. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15936. svr_.wait_until_ready();
  15937. }
  15938. void TearDown() override {
  15939. svr_.stop();
  15940. if (thread_.joinable()) { thread_.join(); }
  15941. }
  15942. // Sends `req` and reads until the server closes the connection. Returns
  15943. // false if the read had to wait for the client-side timeout instead.
  15944. bool send_until_closed(const std::string &req, std::string *resp) const {
  15945. auto start = std::chrono::steady_clock::now();
  15946. if (!send_request(3, req, resp, port_)) { return false; }
  15947. auto elapsed = std::chrono::steady_clock::now() - start;
  15948. return elapsed < std::chrono::seconds(2);
  15949. }
  15950. // The final response comes without `100 Continue`, and the server closes
  15951. // the connection since the body may or may not follow.
  15952. void expect_final_without_interim(const std::string &path,
  15953. const char *status_line) const {
  15954. std::string resp;
  15955. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15956. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15957. EXPECT_EQ(0u, resp.find(status_line));
  15958. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15959. }
  15960. Server svr_;
  15961. int port_ = 0;
  15962. thread thread_;
  15963. };
  15964. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15965. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15966. }
  15967. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15968. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15969. }
  15970. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15971. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15972. }
  15973. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15974. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15975. }
  15976. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15977. // The body follows once `100 Continue` has had time to arrive.
  15978. auto req = expect_headers_only("/reader-used");
  15979. req.insert(req.size() - 2, "Connection: close\r\n");
  15980. std::string resp;
  15981. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15982. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15983. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15984. EXPECT_NE(std::string::npos, resp.find("hi"));
  15985. }
  15986. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15987. // Large enough for the client to add `Expect: 100-continue` itself.
  15988. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15989. std::atomic<bool> body_sent{false};
  15990. Client cli(HOST, port_);
  15991. auto res = cli.Post(
  15992. "/pre-request", length,
  15993. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15994. body_sent = true;
  15995. std::string chunk(len, 'x');
  15996. sink.write(chunk.data(), chunk.size());
  15997. return true;
  15998. },
  15999. "application/octet-stream");
  16000. ASSERT_TRUE(res);
  16001. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16002. EXPECT_FALSE(body_sent);
  16003. }
  16004. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16005. Server svr;
  16006. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16007. return StatusCode::ExpectationFailed_417;
  16008. });
  16009. svr.Post("/p", [](const Request &, Response &res) {
  16010. res.set_content("ok", "text/plain");
  16011. });
  16012. auto port = svr.bind_to_any_port(HOST);
  16013. thread t = thread([&] { svr.listen_after_bind(); });
  16014. auto se = detail::scope_exit([&] {
  16015. svr.stop();
  16016. t.join();
  16017. });
  16018. svr.wait_until_ready();
  16019. std::string resp;
  16020. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16021. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16022. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16023. // Exactly one response: the route handler must not run after the 417.
  16024. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16025. }
  16026. #ifndef _WIN32
  16027. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16028. static constexpr char reject[] = "Unauthorized";
  16029. static constexpr char accept[] = "Upload accepted";
  16030. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16031. Server svr;
  16032. svr.set_expect_100_continue_handler(
  16033. [](const Request & /*req*/, Response &res) {
  16034. res.status = StatusCode::Unauthorized_401;
  16035. res.set_content(reject, "text/plain");
  16036. return res.status;
  16037. });
  16038. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16039. res.set_content(accept, "text/plain");
  16040. });
  16041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16042. auto se = detail::scope_exit([&] {
  16043. svr.stop();
  16044. thread.join();
  16045. ASSERT_FALSE(svr.is_running());
  16046. });
  16047. svr.wait_until_ready();
  16048. {
  16049. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16050. curl_easy_init(), &curl_easy_cleanup};
  16051. ASSERT_NE(curl, nullptr);
  16052. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16053. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16054. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16055. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16056. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16057. &curl_slist_free_all};
  16058. ASSERT_NE(list, nullptr);
  16059. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16060. struct read_data {
  16061. size_t read_size;
  16062. size_t total_size;
  16063. } data = {0, total_size};
  16064. using read_callback_t =
  16065. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16066. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16067. void *userdata) -> size_t {
  16068. read_data *d = (read_data *)userdata;
  16069. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16070. std::fill_n(ptr, size * nmemb, 'A');
  16071. d->read_size += size * nmemb;
  16072. return size * nmemb;
  16073. };
  16074. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16075. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16076. std::vector<char> buffer;
  16077. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16078. using write_callback_t =
  16079. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16080. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16081. void *userdata) -> size_t {
  16082. std::vector<char> *buf = (std::vector<char> *)userdata;
  16083. buf->reserve(buf->size() + size * nmemb + 1);
  16084. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16085. return size * nmemb;
  16086. };
  16087. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16088. {
  16089. const auto res = curl_easy_perform(curl.get());
  16090. ASSERT_EQ(res, CURLE_OK);
  16091. }
  16092. {
  16093. auto response_code = long{};
  16094. const auto res =
  16095. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16096. ASSERT_EQ(res, CURLE_OK);
  16097. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16098. }
  16099. {
  16100. auto dl = curl_off_t{};
  16101. const auto res =
  16102. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16103. ASSERT_EQ(res, CURLE_OK);
  16104. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16105. }
  16106. {
  16107. buffer.push_back('\0');
  16108. ASSERT_STRCASEEQ(buffer.data(), reject);
  16109. }
  16110. }
  16111. }
  16112. #endif
  16113. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16114. // Regression test for #2458.
  16115. //
  16116. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16117. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16118. // ticket can make the client socket spuriously readable during the
  16119. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16120. // the client withholds the body and then blocks reading a response that never
  16121. // comes, failing with `Failed to read connection`.
  16122. //
  16123. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16124. // within the timeout. This raw OpenSSL server deliberately never sends
  16125. // `100 Continue`; the client must still deliver the body and receive 200.
  16126. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16127. signal(SIGPIPE, SIG_IGN);
  16128. const auto port = PORT + 4;
  16129. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16130. ASSERT_NE(srv, INVALID_SOCKET);
  16131. int opt = 1;
  16132. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16133. sockaddr_in addr{};
  16134. addr.sin_family = AF_INET;
  16135. addr.sin_port = htons(static_cast<uint16_t>(port));
  16136. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16137. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16138. ASSERT_EQ(0, ::listen(srv, 1));
  16139. std::atomic<size_t> server_body_bytes{0};
  16140. auto server_thread = std::thread([&] {
  16141. sockaddr_in cli_addr{};
  16142. socklen_t cli_len = sizeof(cli_addr);
  16143. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16144. if (cli == INVALID_SOCKET) { return; }
  16145. // Bound the lifetime of the server side so a buggy client (which never
  16146. // sends the body) cannot make this thread block forever on join.
  16147. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16148. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16149. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16150. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16151. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16152. SSL *ssl = SSL_new(ctx);
  16153. SSL_set_fd(ssl, static_cast<int>(cli));
  16154. if (SSL_accept(ssl) > 0) {
  16155. // Read the request headers. Reading here also flushes the TLS 1.3
  16156. // session tickets to the client. Deliberately do NOT send
  16157. // `100 Continue`.
  16158. std::string buf;
  16159. char tmp[1024];
  16160. while (buf.find("\r\n\r\n") == std::string::npos) {
  16161. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16162. if (n <= 0) { break; }
  16163. buf.append(tmp, static_cast<size_t>(n));
  16164. }
  16165. // A correct client sends the body now; count what arrives.
  16166. auto pos = buf.find("\r\n\r\n");
  16167. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16168. while (body < 4096) {
  16169. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16170. if (n <= 0) { break; }
  16171. body += static_cast<size_t>(n);
  16172. }
  16173. server_body_bytes = body;
  16174. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16175. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16176. SSL_shutdown(ssl);
  16177. }
  16178. SSL_free(ssl);
  16179. detail::close_socket(cli);
  16180. SSL_CTX_free(ctx);
  16181. });
  16182. auto se = detail::scope_exit([&] {
  16183. server_thread.join();
  16184. detail::close_socket(srv);
  16185. });
  16186. SSLClient cli("127.0.0.1", port);
  16187. cli.enable_server_certificate_verification(false);
  16188. cli.set_connection_timeout(5, 0);
  16189. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16190. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16191. std::string body(4096, 'A');
  16192. auto res = cli.Put("/api/test", body, "application/json");
  16193. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16194. EXPECT_EQ(StatusCode::OK_200, res->status);
  16195. EXPECT_EQ(body.size(), server_body_bytes.load());
  16196. }
  16197. #endif
  16198. template <typename S, typename C>
  16199. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16200. svr.Get("/stream", [&](const Request &, Response &res) {
  16201. auto data = new std::string("01234567890123456789");
  16202. res.set_content_provider(
  16203. data->size(), "text/plain",
  16204. [&, data](size_t offset, size_t length, DataSink &sink) {
  16205. const size_t DATA_CHUNK_SIZE = 4;
  16206. const auto &d = *data;
  16207. std::this_thread::sleep_for(std::chrono::seconds(1));
  16208. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16209. return true;
  16210. },
  16211. [data](bool success) {
  16212. EXPECT_FALSE(success);
  16213. delete data;
  16214. });
  16215. });
  16216. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16217. auto i = new size_t(0);
  16218. res.set_content_provider(
  16219. "text/plain",
  16220. [i](size_t, DataSink &sink) {
  16221. if (*i < 5) {
  16222. std::this_thread::sleep_for(std::chrono::seconds(1));
  16223. sink.write("abcd", 4);
  16224. (*i)++;
  16225. } else {
  16226. sink.done();
  16227. }
  16228. return true;
  16229. },
  16230. [i](bool success) {
  16231. EXPECT_FALSE(success);
  16232. delete i;
  16233. });
  16234. });
  16235. svr.Get("/chunked", [&](const Request &, Response &res) {
  16236. auto i = new size_t(0);
  16237. res.set_chunked_content_provider(
  16238. "text/plain",
  16239. [i](size_t, DataSink &sink) {
  16240. if (*i < 5) {
  16241. std::this_thread::sleep_for(std::chrono::seconds(1));
  16242. sink.os << "abcd";
  16243. (*i)++;
  16244. } else {
  16245. sink.done();
  16246. }
  16247. return true;
  16248. },
  16249. [i](bool success) {
  16250. EXPECT_FALSE(success);
  16251. delete i;
  16252. });
  16253. });
  16254. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16255. auto se = detail::scope_exit([&] {
  16256. svr.stop();
  16257. listen_thread.join();
  16258. ASSERT_FALSE(svr.is_running());
  16259. });
  16260. svr.wait_until_ready();
  16261. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16262. {
  16263. auto start = std::chrono::steady_clock::now();
  16264. auto res = cli.Get("/stream");
  16265. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16266. std::chrono::steady_clock::now() - start)
  16267. .count();
  16268. ASSERT_FALSE(res);
  16269. EXPECT_EQ(Error::Read, res.error());
  16270. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16271. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16272. }
  16273. {
  16274. auto start = std::chrono::steady_clock::now();
  16275. auto res = cli.Get("/stream_without_length");
  16276. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16277. std::chrono::steady_clock::now() - start)
  16278. .count();
  16279. ASSERT_FALSE(res);
  16280. EXPECT_EQ(Error::Read, res.error());
  16281. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16282. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16283. }
  16284. {
  16285. auto start = std::chrono::steady_clock::now();
  16286. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16287. EXPECT_EQ("abcd", string(data, data_length));
  16288. return true;
  16289. });
  16290. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16291. std::chrono::steady_clock::now() - start)
  16292. .count();
  16293. ASSERT_FALSE(res);
  16294. EXPECT_EQ(Error::Read, res.error());
  16295. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16296. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16297. }
  16298. }
  16299. TEST(MaxTimeoutTest, ContentStream) {
  16300. time_t timeout = 2000;
  16301. time_t threshold = 200;
  16302. Server svr;
  16303. Client cli("localhost", PORT);
  16304. max_timeout_test(svr, cli, timeout, threshold);
  16305. }
  16306. #ifdef CPPHTTPLIB_SSL_ENABLED
  16307. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16308. time_t timeout = 2000;
  16309. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16310. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16311. SSLClient cli("localhost", PORT);
  16312. cli.enable_server_certificate_verification(false);
  16313. max_timeout_test(svr, cli, timeout, threshold);
  16314. }
  16315. #endif
  16316. class EventDispatcher {
  16317. public:
  16318. EventDispatcher() {}
  16319. bool wait_event(DataSink *sink) {
  16320. unique_lock<mutex> lk(m_);
  16321. int id = id_;
  16322. // Wait with timeout to prevent hanging if client disconnects
  16323. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16324. [&] { return cid_ == id; })) {
  16325. return false; // Timeout occurred
  16326. }
  16327. sink->write(message_.data(), message_.size());
  16328. return true;
  16329. }
  16330. void send_event(const string &message) {
  16331. lock_guard<mutex> lk(m_);
  16332. cid_ = id_++;
  16333. message_ = message;
  16334. cv_.notify_all();
  16335. }
  16336. private:
  16337. mutex m_;
  16338. condition_variable cv_;
  16339. atomic_int id_{0};
  16340. atomic_int cid_{-1};
  16341. string message_;
  16342. };
  16343. TEST(ClientInThreadTest, Issue2068) {
  16344. EventDispatcher ed;
  16345. Server svr;
  16346. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16347. res.set_chunked_content_provider("text/event-stream",
  16348. [&](size_t /*offset*/, DataSink &sink) {
  16349. return ed.wait_event(&sink);
  16350. });
  16351. });
  16352. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16353. svr.wait_until_ready();
  16354. thread event_thread([&] {
  16355. int id = 0;
  16356. while (svr.is_running()) {
  16357. this_thread::sleep_for(chrono::milliseconds(500));
  16358. std::stringstream ss;
  16359. ss << "data: " << id << "\n\n";
  16360. ed.send_event(ss.str());
  16361. id++;
  16362. }
  16363. });
  16364. auto se = detail::scope_exit([&] {
  16365. svr.stop();
  16366. listen_thread.join();
  16367. event_thread.join();
  16368. ASSERT_FALSE(svr.is_running());
  16369. });
  16370. {
  16371. auto client = detail::make_unique<Client>(HOST, PORT);
  16372. client->set_read_timeout(std::chrono::minutes(10));
  16373. std::atomic<bool> stop{false};
  16374. std::thread t([&] {
  16375. client->Get("/event1",
  16376. [&](const char *, size_t) -> bool { return !stop; });
  16377. });
  16378. std::this_thread::sleep_for(std::chrono::seconds(2));
  16379. stop = true;
  16380. client->stop();
  16381. t.join();
  16382. // Reset client after thread has finished
  16383. client.reset();
  16384. }
  16385. }
  16386. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16387. auto handled = false;
  16388. Server svr;
  16389. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16390. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16391. auto se = detail::scope_exit([&] {
  16392. svr.stop();
  16393. t.join();
  16394. ASSERT_FALSE(svr.is_running());
  16395. ASSERT_FALSE(handled);
  16396. });
  16397. svr.wait_until_ready();
  16398. // Two Content-Length headers with different values — must be rejected
  16399. auto req = "POST /test HTTP/1.1\r\n"
  16400. "Content-Length: 5\r\n"
  16401. "Content-Length: 10\r\n"
  16402. "\r\n"
  16403. "hello";
  16404. std::string response;
  16405. ASSERT_TRUE(send_request(1, req, &response));
  16406. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16407. response.substr(0, response.find("\r\n")));
  16408. }
  16409. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16410. auto handled = false;
  16411. Server svr;
  16412. svr.Post("/test", [&](const Request &, Response &res) {
  16413. handled = true;
  16414. res.set_content("ok", "text/plain");
  16415. });
  16416. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16417. auto se = detail::scope_exit([&] {
  16418. svr.stop();
  16419. t.join();
  16420. ASSERT_FALSE(svr.is_running());
  16421. ASSERT_TRUE(handled);
  16422. });
  16423. svr.wait_until_ready();
  16424. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16425. auto req = "POST /test HTTP/1.1\r\n"
  16426. "Content-Length: 5\r\n"
  16427. "Content-Length: 5\r\n"
  16428. "\r\n"
  16429. "hello";
  16430. std::string response;
  16431. ASSERT_TRUE(send_request(1, req, &response));
  16432. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16433. }
  16434. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16435. Server svr;
  16436. svr.Get("/", [](const Request &req, Response &res) {
  16437. EXPECT_EQ(2U, req.trailers.size());
  16438. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16439. // Denied
  16440. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16441. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16442. // Accepted
  16443. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16444. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16445. EXPECT_TRUE(req.has_trailer("X-World"));
  16446. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16447. res.set_content("ok", "text/plain");
  16448. });
  16449. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16450. auto se = detail::scope_exit([&] {
  16451. svr.stop();
  16452. t.join();
  16453. ASSERT_FALSE(svr.is_running());
  16454. });
  16455. svr.wait_until_ready();
  16456. const std::string req = "GET / HTTP/1.1\r\n"
  16457. "Transfer-Encoding: chunked\r\n"
  16458. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16459. "\r\n"
  16460. "0\r\n"
  16461. "Content-Length: 10\r\n"
  16462. "Host: internal.local\r\n"
  16463. "Content-Type: malicious/content\r\n"
  16464. "Cookie: any\r\n"
  16465. "Set-Cookie: any\r\n"
  16466. "X-Forwarded-For: attacker.com\r\n"
  16467. "X-Real-Ip: 1.1.1.1\r\n"
  16468. "X-Hello: hello\r\n"
  16469. "X-World: world\r\n"
  16470. "\r\n";
  16471. std::string res;
  16472. ASSERT_TRUE(send_request(1, req, &res));
  16473. }
  16474. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16475. // several field lines, and the combined value is what has to be parsed. A
  16476. // Trailer field split across lines therefore declares every name it lists;
  16477. // reading only the first line silently drops the trailers the later lines
  16478. // declare. The prohibited-trailer filter still applies to every line.
  16479. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16480. Server svr;
  16481. size_t observed_trailer_count = 0;
  16482. std::string observed_hello;
  16483. std::string observed_world;
  16484. bool observed_content_length = true;
  16485. svr.Get("/", [&](const Request &req, Response &res) {
  16486. observed_trailer_count = req.trailers.size();
  16487. observed_hello = req.get_trailer_value("X-Hello");
  16488. observed_world = req.get_trailer_value("X-World");
  16489. observed_content_length = req.has_trailer("Content-Length");
  16490. res.set_content("ok", "text/plain");
  16491. });
  16492. auto port = svr.bind_to_any_port(HOST);
  16493. thread t = thread([&]() { svr.listen_after_bind(); });
  16494. auto se = detail::scope_exit([&] {
  16495. svr.stop();
  16496. t.join();
  16497. ASSERT_FALSE(svr.is_running());
  16498. });
  16499. svr.wait_until_ready();
  16500. const std::string req = "GET / HTTP/1.1\r\n"
  16501. "Transfer-Encoding: chunked\r\n"
  16502. "Trailer: X-Hello\r\n"
  16503. "Trailer: X-World, Content-Length\r\n"
  16504. "\r\n"
  16505. "0\r\n"
  16506. "X-Hello: hello\r\n"
  16507. "X-World: world\r\n"
  16508. "Content-Length: 10\r\n"
  16509. "\r\n";
  16510. std::string res;
  16511. ASSERT_TRUE(send_request(1, req, &res, port));
  16512. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16513. // Accepted: both field lines contribute to the declared set
  16514. EXPECT_EQ(2U, observed_trailer_count);
  16515. EXPECT_EQ(observed_hello, "hello");
  16516. EXPECT_EQ(observed_world, "world");
  16517. // Denied: a prohibited name stays prohibited on a later field line
  16518. EXPECT_FALSE(observed_content_length);
  16519. }
  16520. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16521. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16522. // unbounded run of fields that are never declared, because the counter would
  16523. // only advance for declared fields.
  16524. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16525. Server svr;
  16526. bool handler_called = false;
  16527. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16528. handler_called = true;
  16529. res.set_content("ok", "text/plain");
  16530. });
  16531. auto port = svr.bind_to_any_port(HOST);
  16532. thread t = thread([&]() { svr.listen_after_bind(); });
  16533. auto se = detail::scope_exit([&] {
  16534. svr.stop();
  16535. t.join();
  16536. ASSERT_FALSE(svr.is_running());
  16537. });
  16538. svr.wait_until_ready();
  16539. // Declare nothing, then send far more undeclared trailer fields than the
  16540. // header-count limit. Parsing must stop and reject the request rather than
  16541. // read every line.
  16542. std::string req = "GET / HTTP/1.1\r\n"
  16543. "Transfer-Encoding: chunked\r\n"
  16544. "\r\n"
  16545. "0\r\n";
  16546. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16547. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16548. }
  16549. req += "\r\n";
  16550. std::string res;
  16551. ASSERT_TRUE(send_request(1, req, &res, port));
  16552. // The request is rejected before the handler runs.
  16553. EXPECT_FALSE(handler_called);
  16554. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16555. }
  16556. // The set of declared trailer names is capped so a peer cannot grow it without
  16557. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16558. // declared past the cap is not honored, even if the field is actually sent.
  16559. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16560. Server svr;
  16561. // One name inside the cap and one past it, so the test tracks the cap rather
  16562. // than a fixed count.
  16563. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16564. const std::string within_cap_name = "X-T-0";
  16565. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16566. bool observed_within_cap = false;
  16567. bool observed_past_cap = false;
  16568. svr.Get("/", [&](const Request &req, Response &res) {
  16569. observed_within_cap = req.has_trailer(within_cap_name);
  16570. observed_past_cap = req.has_trailer(past_cap_name);
  16571. res.set_content("ok", "text/plain");
  16572. });
  16573. auto port = svr.bind_to_any_port(HOST);
  16574. thread t = thread([&]() { svr.listen_after_bind(); });
  16575. auto se = detail::scope_exit([&] {
  16576. svr.stop();
  16577. t.join();
  16578. ASSERT_FALSE(svr.is_running());
  16579. });
  16580. svr.wait_until_ready();
  16581. // Declare more trailer names than the cap in a single Trailer field, then
  16582. // actually send the first (within the cap) and the last (past it).
  16583. std::string trailer_decl = "Trailer: ";
  16584. for (int i = 0; i < declared_count; i++) {
  16585. if (i != 0) { trailer_decl += ", "; }
  16586. trailer_decl += "X-T-" + std::to_string(i);
  16587. }
  16588. trailer_decl += "\r\n";
  16589. const std::string req = "GET / HTTP/1.1\r\n"
  16590. "Transfer-Encoding: chunked\r\n" +
  16591. trailer_decl +
  16592. "\r\n"
  16593. "0\r\n" +
  16594. within_cap_name + ": a\r\n" + past_cap_name +
  16595. ": b\r\n"
  16596. "\r\n";
  16597. std::string res;
  16598. ASSERT_TRUE(send_request(1, req, &res, port));
  16599. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16600. // A name within the cap is honored; one declared past the cap is dropped.
  16601. EXPECT_TRUE(observed_within_cap);
  16602. EXPECT_FALSE(observed_past_cap);
  16603. }
  16604. // A direct client that is not listed in trusted_proxies must not be able to
  16605. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16606. // the peer address on the actual TCP connection determines whether the
  16607. // header is honored.
  16608. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16609. Server svr;
  16610. // Deliberately does NOT include the loopback address the test client
  16611. // actually connects from, so the direct connection is not a trusted proxy.
  16612. svr.set_trusted_proxies({"203.0.113.66"});
  16613. std::string observed_remote_addr;
  16614. svr.Get("/ip", [&](const Request &req, Response &res) {
  16615. observed_remote_addr = req.remote_addr;
  16616. res.set_content("ok", "text/plain");
  16617. });
  16618. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16619. auto se = detail::scope_exit([&] {
  16620. svr.stop();
  16621. t.join();
  16622. ASSERT_FALSE(svr.is_running());
  16623. });
  16624. svr.wait_until_ready();
  16625. Client cli(HOST, PORT);
  16626. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16628. EXPECT_EQ(StatusCode::OK_200, res->status);
  16629. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16630. // ignored entirely and the real connection-level address retained.
  16631. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16632. observed_remote_addr == "127.0.0.1");
  16633. }
  16634. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16635. Server svr;
  16636. std::string observed_remote_addr;
  16637. std::string observed_xff;
  16638. svr.Get("/ip", [&](const Request &req, Response &res) {
  16639. observed_remote_addr = req.remote_addr;
  16640. observed_xff = req.get_header_value("X-Forwarded-For");
  16641. res.set_content("ok", "text/plain");
  16642. });
  16643. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16644. auto se = detail::scope_exit([&] {
  16645. svr.stop();
  16646. t.join();
  16647. ASSERT_FALSE(svr.is_running());
  16648. });
  16649. svr.wait_until_ready();
  16650. Client cli(HOST, PORT);
  16651. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16653. EXPECT_EQ(StatusCode::OK_200, res->status);
  16654. EXPECT_EQ(observed_xff, "203.0.113.66");
  16655. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16656. observed_remote_addr == "127.0.0.1");
  16657. }
  16658. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16659. Server svr;
  16660. svr.set_trusted_proxies({"203.0.113.66"});
  16661. std::string observed_remote_addr;
  16662. std::string observed_xff;
  16663. svr.Get("/ip", [&](const Request &req, Response &res) {
  16664. observed_remote_addr = req.remote_addr;
  16665. observed_xff = req.get_header_value("X-Forwarded-For");
  16666. res.set_content("ok", "text/plain");
  16667. });
  16668. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16669. auto se = detail::scope_exit([&] {
  16670. svr.stop();
  16671. t.join();
  16672. ASSERT_FALSE(svr.is_running());
  16673. });
  16674. svr.wait_until_ready();
  16675. Client cli(HOST, PORT);
  16676. auto res = cli.Get("/ip");
  16677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16678. EXPECT_EQ(StatusCode::OK_200, res->status);
  16679. EXPECT_EQ(observed_xff, "");
  16680. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16681. observed_remote_addr == "127.0.0.1");
  16682. }
  16683. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16684. Server svr;
  16685. // Include the loopback address the test client actually connects from, so
  16686. // the direct connection itself is recognized as the trusted proxy hop.
  16687. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16688. std::string observed_remote_addr;
  16689. std::string observed_xff;
  16690. svr.Get("/ip", [&](const Request &req, Response &res) {
  16691. observed_remote_addr = req.remote_addr;
  16692. observed_xff = req.get_header_value("X-Forwarded-For");
  16693. res.set_content("ok", "text/plain");
  16694. });
  16695. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16696. auto se = detail::scope_exit([&] {
  16697. svr.stop();
  16698. t.join();
  16699. ASSERT_FALSE(svr.is_running());
  16700. });
  16701. svr.wait_until_ready();
  16702. Client cli(HOST, PORT);
  16703. auto res = cli.Get(
  16704. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16706. EXPECT_EQ(StatusCode::OK_200, res->status);
  16707. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16708. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16709. }
  16710. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16711. Server svr;
  16712. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16713. std::string observed_remote_addr;
  16714. std::string observed_xff;
  16715. svr.Get("/ip", [&](const Request &req, Response &res) {
  16716. observed_remote_addr = req.remote_addr;
  16717. observed_xff = req.get_header_value("X-Forwarded-For");
  16718. res.set_content("ok", "text/plain");
  16719. });
  16720. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16721. auto se = detail::scope_exit([&] {
  16722. svr.stop();
  16723. t.join();
  16724. ASSERT_FALSE(svr.is_running());
  16725. });
  16726. svr.wait_until_ready();
  16727. Client cli(HOST, PORT);
  16728. auto res = cli.Get(
  16729. "/ip",
  16730. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16732. EXPECT_EQ(StatusCode::OK_200, res->status);
  16733. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16734. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16735. }
  16736. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16737. Server svr;
  16738. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16739. std::string observed_remote_addr;
  16740. std::string observed_xff;
  16741. svr.Get("/ip", [&](const Request &req, Response &res) {
  16742. observed_remote_addr = req.remote_addr;
  16743. observed_xff = req.get_header_value("X-Forwarded-For");
  16744. res.set_content("ok", "text/plain");
  16745. });
  16746. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16747. auto se = detail::scope_exit([&] {
  16748. svr.stop();
  16749. t.join();
  16750. ASSERT_FALSE(svr.is_running());
  16751. });
  16752. svr.wait_until_ready();
  16753. Client cli(HOST, PORT);
  16754. auto res = cli.Get(
  16755. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16757. EXPECT_EQ(StatusCode::OK_200, res->status);
  16758. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16759. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16760. // and must not be selected.
  16761. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16762. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16763. }
  16764. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16765. Server svr;
  16766. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16767. std::string observed_remote_addr;
  16768. svr.Get("/ip", [&](const Request &req, Response &res) {
  16769. observed_remote_addr = req.remote_addr;
  16770. res.set_content("ok", "text/plain");
  16771. });
  16772. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16773. auto se = detail::scope_exit([&] {
  16774. svr.stop();
  16775. t.join();
  16776. ASSERT_FALSE(svr.is_running());
  16777. });
  16778. svr.wait_until_ready();
  16779. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16780. // a forged address and the trusted proxy's own address; the forged value must
  16781. // not win over the address the trusted proxy actually recorded.
  16782. Client cli(HOST, PORT);
  16783. auto res = cli.Get(
  16784. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16786. EXPECT_EQ(StatusCode::OK_200, res->status);
  16787. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16788. }
  16789. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16790. Server svr;
  16791. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16792. std::string observed_remote_addr;
  16793. std::string observed_xff;
  16794. svr.Get("/ip", [&](const Request &req, Response &res) {
  16795. observed_remote_addr = req.remote_addr;
  16796. observed_xff = req.get_header_value("X-Forwarded-For");
  16797. res.set_content("ok", "text/plain");
  16798. });
  16799. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16800. auto se = detail::scope_exit([&] {
  16801. svr.stop();
  16802. t.join();
  16803. ASSERT_FALSE(svr.is_running());
  16804. });
  16805. svr.wait_until_ready();
  16806. Client cli(HOST, PORT);
  16807. auto res = cli.Get(
  16808. "/ip",
  16809. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16811. EXPECT_EQ(StatusCode::OK_200, res->status);
  16812. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16813. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16814. }
  16815. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16816. Server svr;
  16817. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16818. std::string observed_remote_addr;
  16819. std::string observed_xff;
  16820. svr.Get("/ip", [&](const Request &req, Response &res) {
  16821. observed_remote_addr = req.remote_addr;
  16822. observed_xff = req.get_header_value("X-Forwarded-For");
  16823. res.set_content("ok", "text/plain");
  16824. });
  16825. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16826. auto se = detail::scope_exit([&] {
  16827. svr.stop();
  16828. t.join();
  16829. ASSERT_FALSE(svr.is_running());
  16830. });
  16831. svr.wait_until_ready();
  16832. std::string raw_req =
  16833. "GET /ip HTTP/1.1\r\n"
  16834. "Host: localhost\r\n"
  16835. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16836. "Connection: close\r\n"
  16837. "\r\n";
  16838. std::string out;
  16839. ASSERT_TRUE(send_request(5, raw_req, &out));
  16840. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16841. // Header parser trims surrounding whitespace of the header value
  16842. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16843. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16844. }
  16845. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16846. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16847. // their own X-Forwarded-For as a separate field line rather than extending the
  16848. // one the client sent, so every occurrence has to be taken into account.
  16849. // Reading only the first one hands back the address the client chose.
  16850. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16851. Server svr;
  16852. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16853. std::string observed_remote_addr;
  16854. size_t observed_xff_count = 0;
  16855. svr.Get("/ip", [&](const Request &req, Response &res) {
  16856. observed_remote_addr = req.remote_addr;
  16857. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16858. res.set_content("ok", "text/plain");
  16859. });
  16860. auto port = svr.bind_to_any_port(HOST);
  16861. thread t = thread([&]() { svr.listen_after_bind(); });
  16862. auto se = detail::scope_exit([&] {
  16863. svr.stop();
  16864. t.join();
  16865. ASSERT_FALSE(svr.is_running());
  16866. });
  16867. svr.wait_until_ready();
  16868. // The client supplies the first field line; the trusted proxy appends the
  16869. // address it observed as a second one.
  16870. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16871. "Host: localhost\r\n"
  16872. "X-Forwarded-For: 1.2.3.4\r\n"
  16873. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16874. "Connection: close\r\n"
  16875. "\r\n";
  16876. std::string out;
  16877. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16878. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16879. EXPECT_EQ(observed_xff_count, 2U);
  16880. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16881. // The same chain spread over one field line per hop derives the same client
  16882. // address, i.e. the split and the comma-joined representations agree.
  16883. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16884. "Host: localhost\r\n"
  16885. "X-Forwarded-For: 1.2.3.4\r\n"
  16886. "X-Forwarded-For: 198.51.100.23\r\n"
  16887. "X-Forwarded-For: 192.0.2.45\r\n"
  16888. "Connection: close\r\n"
  16889. "\r\n";
  16890. out.clear();
  16891. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16892. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16893. EXPECT_EQ(observed_xff_count, 3U);
  16894. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16895. }
  16896. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16897. // crash the server (it used to call front() on an empty vector inside
  16898. // get_client_ip). The connection-level remote address must be retained instead.
  16899. static void run_malformed_xff_test(const std::string &xff_value) {
  16900. Server svr;
  16901. svr.set_trusted_proxies({"192.0.2.45"});
  16902. std::string observed_remote_addr;
  16903. svr.Get("/ip", [&](const Request &req, Response &res) {
  16904. observed_remote_addr = req.remote_addr;
  16905. res.set_content("ok", "text/plain");
  16906. });
  16907. int port = 0;
  16908. thread t = thread([&]() {
  16909. port = svr.bind_to_any_port(HOST);
  16910. svr.listen_after_bind();
  16911. });
  16912. auto se = detail::scope_exit([&] {
  16913. svr.stop();
  16914. t.join();
  16915. ASSERT_FALSE(svr.is_running());
  16916. });
  16917. svr.wait_until_ready();
  16918. Client cli(HOST, port);
  16919. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16921. EXPECT_EQ(StatusCode::OK_200, res->status);
  16922. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16923. observed_remote_addr == "127.0.0.1");
  16924. }
  16925. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16926. run_malformed_xff_test("");
  16927. }
  16928. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16929. run_malformed_xff_test(",");
  16930. }
  16931. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16932. run_malformed_xff_test(", , ,");
  16933. }
  16934. // The same rule applies to Accept: a request whose acceptable types are spread
  16935. // over several field lines must be negotiated against all of them.
  16936. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16937. // case-insensitive connection options. Comparing the whole field value against
  16938. // one option misses a client that sends several of them, and misses every
  16939. // casing but the one written in the comparison.
  16940. //
  16941. // Sends req, reads the response, then reuses the same socket for a second
  16942. // request to find out whether the server kept the connection.
  16943. static void probe_connection_reuse(int port, const std::string &req,
  16944. bool *announced_close, bool *reusable) {
  16945. auto error = Error::Success;
  16946. auto sock = detail::create_client_socket(
  16947. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16948. /*connection_timeout_sec=*/5, 0,
  16949. /*read_timeout_sec=*/1, 0,
  16950. /*write_timeout_sec=*/5, 0, std::string(), error);
  16951. ASSERT_NE(sock, INVALID_SOCKET);
  16952. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16953. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16954. "Host: localhost\r\n"
  16955. "Connection: close\r\n"
  16956. "\r\n";
  16957. std::string first_response;
  16958. std::string second_response;
  16959. detail::process_client_socket(
  16960. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16961. [&](Stream &strm) {
  16962. if (strm.write(req.data(), req.size()) !=
  16963. static_cast<ssize_t>(req.size())) {
  16964. return false;
  16965. }
  16966. char buf[512];
  16967. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16968. // Headers plus the two-byte body of the handler below
  16969. while (reader.getline()) {
  16970. first_response += reader.ptr();
  16971. if (first_response.find("ok") != std::string::npos) { break; }
  16972. }
  16973. if (strm.write(second.data(), second.size()) !=
  16974. static_cast<ssize_t>(second.size())) {
  16975. return true;
  16976. }
  16977. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16978. while (reader2.getline()) {
  16979. second_response += reader2.ptr();
  16980. if (second_response.find("ok") != std::string::npos) { break; }
  16981. }
  16982. return true;
  16983. });
  16984. *announced_close =
  16985. first_response.find("Connection: close") != std::string::npos;
  16986. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16987. }
  16988. class ConnectionTokenTest : public ::testing::Test {
  16989. protected:
  16990. void SetUp() override {
  16991. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16992. res.set_content("ok", "text/plain");
  16993. });
  16994. port_ = svr_.bind_to_any_port(HOST);
  16995. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16996. svr_.wait_until_ready();
  16997. }
  16998. void TearDown() override {
  16999. svr_.stop();
  17000. if (thread_.joinable()) { thread_.join(); }
  17001. }
  17002. Server svr_;
  17003. int port_ = 0;
  17004. thread thread_;
  17005. };
  17006. // "close" alongside another option still closes the connection, and the
  17007. // response says so rather than leaving the peer to discover it.
  17008. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17009. bool announced_close = false;
  17010. bool reusable = true;
  17011. probe_connection_reuse(port_,
  17012. "GET /keepalive HTTP/1.1\r\n"
  17013. "Host: localhost\r\n"
  17014. "Connection: keep-alive, close\r\n"
  17015. "\r\n",
  17016. &announced_close, &reusable);
  17017. EXPECT_TRUE(announced_close);
  17018. EXPECT_FALSE(reusable);
  17019. }
  17020. // "close" split over two field lines is the same list, so it is honored too.
  17021. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17022. bool announced_close = false;
  17023. bool reusable = true;
  17024. probe_connection_reuse(port_,
  17025. "GET /keepalive HTTP/1.1\r\n"
  17026. "Host: localhost\r\n"
  17027. "Connection: keep-alive\r\n"
  17028. "Connection: close\r\n"
  17029. "\r\n",
  17030. &announced_close, &reusable);
  17031. EXPECT_TRUE(announced_close);
  17032. EXPECT_FALSE(reusable);
  17033. }
  17034. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17035. // keep-alive in the spelling everyone actually sends keeps its connection.
  17036. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17037. bool announced_close = false;
  17038. bool reusable = false;
  17039. probe_connection_reuse(port_,
  17040. "GET /keepalive HTTP/1.0\r\n"
  17041. "Host: localhost\r\n"
  17042. "Connection: keep-alive\r\n"
  17043. "\r\n",
  17044. &announced_close, &reusable);
  17045. EXPECT_FALSE(announced_close);
  17046. EXPECT_TRUE(reusable);
  17047. }
  17048. // A token the value merely contains is not the token itself.
  17049. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17050. bool announced_close = false;
  17051. bool reusable = false;
  17052. probe_connection_reuse(port_,
  17053. "GET /keepalive HTTP/1.1\r\n"
  17054. "Host: localhost\r\n"
  17055. "Connection: notclose\r\n"
  17056. "\r\n",
  17057. &announced_close, &reusable);
  17058. EXPECT_FALSE(announced_close);
  17059. EXPECT_TRUE(reusable);
  17060. }
  17061. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17062. Server svr;
  17063. std::vector<std::string> observed_types;
  17064. svr.Get("/", [&](const Request &req, Response &res) {
  17065. observed_types = req.accept_content_types;
  17066. res.set_content("ok", "text/plain");
  17067. });
  17068. auto port = svr.bind_to_any_port(HOST);
  17069. thread t = thread([&]() { svr.listen_after_bind(); });
  17070. auto se = detail::scope_exit([&] {
  17071. svr.stop();
  17072. t.join();
  17073. ASSERT_FALSE(svr.is_running());
  17074. });
  17075. svr.wait_until_ready();
  17076. Client cli(HOST, port);
  17077. Headers headers;
  17078. headers.emplace("Accept", "text/plain;q=0.5");
  17079. headers.emplace("Accept", "application/json");
  17080. auto res = cli.Get("/", headers);
  17081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17082. EXPECT_EQ(StatusCode::OK_200, res->status);
  17083. // Sorted by q-value, so the second field line's type comes first
  17084. ASSERT_EQ(2U, observed_types.size());
  17085. EXPECT_EQ("application/json", observed_types[0]);
  17086. EXPECT_EQ("text/plain", observed_types[1]);
  17087. }
  17088. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17089. // empty field line must not contribute a bare comma to the combined value.
  17090. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17091. Server svr;
  17092. std::vector<std::string> observed_types;
  17093. svr.Get("/", [&](const Request &req, Response &res) {
  17094. observed_types = req.accept_content_types;
  17095. res.set_content("ok", "text/plain");
  17096. });
  17097. auto port = svr.bind_to_any_port(HOST);
  17098. thread t = thread([&]() { svr.listen_after_bind(); });
  17099. auto se = detail::scope_exit([&] {
  17100. svr.stop();
  17101. t.join();
  17102. ASSERT_FALSE(svr.is_running());
  17103. });
  17104. svr.wait_until_ready();
  17105. // Empty first field line, then a real one
  17106. std::string raw_req = "GET / HTTP/1.1\r\n"
  17107. "Host: localhost\r\n"
  17108. "Accept:\r\n"
  17109. "Accept: application/json\r\n"
  17110. "Connection: close\r\n"
  17111. "\r\n";
  17112. std::string out;
  17113. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17114. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17115. ASSERT_EQ(1U, observed_types.size());
  17116. EXPECT_EQ("application/json", observed_types[0]);
  17117. }
  17118. // The skip in get_combined_header_value() is what keeps an empty field line
  17119. // from contributing a bare comma. Only a trailing empty field line exercises
  17120. // it: a leading one is already covered by the "combined is still empty" check,
  17121. // and parse_accept_header() now ignores the empty element either way, so the
  17122. // request-level test above can no longer tell the two apart.
  17123. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17124. Headers headers;
  17125. headers.emplace("Accept", "text/html");
  17126. headers.emplace("Accept", "");
  17127. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17128. headers.clear();
  17129. headers.emplace("Accept", "");
  17130. headers.emplace("Accept", "application/json");
  17131. EXPECT_EQ("application/json",
  17132. detail::get_combined_header_value(headers, "Accept"));
  17133. }
  17134. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17135. // An encoding offered on a later Accept-Encoding field line is still offered.
  17136. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17137. Server svr;
  17138. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17139. res.set_content(std::string(1024, 'x'), "text/plain");
  17140. });
  17141. auto port = svr.bind_to_any_port(HOST);
  17142. thread t = thread([&]() { svr.listen_after_bind(); });
  17143. auto se = detail::scope_exit([&] {
  17144. svr.stop();
  17145. t.join();
  17146. ASSERT_FALSE(svr.is_running());
  17147. });
  17148. svr.wait_until_ready();
  17149. Client cli(HOST, port);
  17150. cli.set_decompress(false);
  17151. Headers headers;
  17152. headers.emplace("Accept-Encoding", "identity");
  17153. headers.emplace("Accept-Encoding", "gzip");
  17154. auto res = cli.Get("/", headers);
  17155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17156. EXPECT_EQ(StatusCode::OK_200, res->status);
  17157. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17158. }
  17159. #endif
  17160. #ifndef _WIN32
  17161. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17162. Server svr;
  17163. svr.Post("/post", [&](const Request &req, Response &res) {
  17164. res.set_content(req.body, "text/plain");
  17165. });
  17166. svr.Put("/put", [&](const Request &req, Response &res) {
  17167. res.set_content(req.body, "text/plain");
  17168. });
  17169. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17170. res.set_content(req.body, "text/plain");
  17171. });
  17172. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17173. res.set_content(req.body, "text/plain");
  17174. });
  17175. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17176. auto se = detail::scope_exit([&] {
  17177. svr.stop();
  17178. t.join();
  17179. ASSERT_FALSE(svr.is_running());
  17180. });
  17181. svr.wait_until_ready();
  17182. std::string resp;
  17183. // POST without Content-Length
  17184. ASSERT_TRUE(send_request(5,
  17185. "POST /post HTTP/1.1\r\n"
  17186. "Host: localhost\r\n"
  17187. "Connection: close\r\n"
  17188. "\r\n",
  17189. &resp));
  17190. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17191. // PUT without Content-Length
  17192. resp.clear();
  17193. ASSERT_TRUE(send_request(5,
  17194. "PUT /put HTTP/1.1\r\n"
  17195. "Host: localhost\r\n"
  17196. "Connection: close\r\n"
  17197. "\r\n",
  17198. &resp));
  17199. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17200. // PATCH without Content-Length
  17201. resp.clear();
  17202. ASSERT_TRUE(send_request(5,
  17203. "PATCH /patch HTTP/1.1\r\n"
  17204. "Host: localhost\r\n"
  17205. "Connection: close\r\n"
  17206. "\r\n",
  17207. &resp));
  17208. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17209. // DELETE without Content-Length
  17210. resp.clear();
  17211. ASSERT_TRUE(send_request(5,
  17212. "DELETE /delete HTTP/1.1\r\n"
  17213. "Host: localhost\r\n"
  17214. "Connection: close\r\n"
  17215. "\r\n",
  17216. &resp));
  17217. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17218. }
  17219. #endif
  17220. //==============================================================================
  17221. // open_stream() Tests
  17222. //==============================================================================
  17223. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17224. std::string result;
  17225. char buf[8192];
  17226. ssize_t n;
  17227. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17228. result.append(buf, static_cast<size_t>(n));
  17229. }
  17230. return result;
  17231. }
  17232. // Mock stream for unit tests
  17233. class MockStream : public Stream {
  17234. public:
  17235. std::string data;
  17236. size_t pos = 0;
  17237. ssize_t error_after = -1; // -1 = no error
  17238. explicit MockStream(const std::string &d, ssize_t err = -1)
  17239. : data(d), error_after(err) {}
  17240. bool is_readable() const override { return true; }
  17241. bool wait_readable() const override { return true; }
  17242. bool wait_writable() const override { return true; }
  17243. ssize_t read(char *ptr, size_t size) override {
  17244. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17245. if (pos >= data.size()) return 0;
  17246. size_t limit =
  17247. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17248. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17249. std::memcpy(ptr, data.data() + pos, to_read);
  17250. pos += to_read;
  17251. return static_cast<ssize_t>(to_read);
  17252. }
  17253. ssize_t write(const char *, size_t) override { return -1; }
  17254. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17255. ip = "127.0.0.1";
  17256. port = 0;
  17257. }
  17258. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17259. ip = "127.0.0.1";
  17260. port = 0;
  17261. }
  17262. socket_t socket() const override { return INVALID_SOCKET; }
  17263. time_t duration() const override { return 0; }
  17264. };
  17265. TEST(StreamHandleTest, Basic) {
  17266. ClientImpl::StreamHandle handle;
  17267. EXPECT_FALSE(handle.is_valid());
  17268. handle.response = detail::make_unique<Response>();
  17269. handle.error = Error::Connection;
  17270. EXPECT_FALSE(handle.is_valid());
  17271. handle.error = Error::Success;
  17272. EXPECT_TRUE(handle.is_valid());
  17273. }
  17274. TEST(BodyReaderTest, Basic) {
  17275. MockStream stream("Hello, World!");
  17276. detail::BodyReader reader;
  17277. reader.stream = &stream;
  17278. reader.content_length = 13;
  17279. char buf[32];
  17280. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17281. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17282. EXPECT_TRUE(reader.eof);
  17283. }
  17284. TEST(BodyReaderTest, NoStream) {
  17285. detail::BodyReader reader;
  17286. char buf[32];
  17287. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17288. EXPECT_EQ(Error::Connection, reader.last_error);
  17289. }
  17290. TEST(BodyReaderTest, Error) {
  17291. MockStream stream("Hello, World!", 5);
  17292. detail::BodyReader reader;
  17293. reader.stream = &stream;
  17294. reader.content_length = 13;
  17295. char buf[32];
  17296. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17297. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17298. EXPECT_EQ(Error::Read, reader.last_error);
  17299. }
  17300. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17301. // Mock-based StreamHandle tests relying on private internals are removed.
  17302. class OpenStreamTest : public ::testing::Test {
  17303. protected:
  17304. void SetUp() override {
  17305. svr_.Get("/hello", [](const Request &, Response &res) {
  17306. res.set_content("Hello World!", "text/plain");
  17307. });
  17308. svr_.Get("/large", [](const Request &, Response &res) {
  17309. res.set_content(std::string(10000, 'X'), "text/plain");
  17310. });
  17311. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17312. res.set_content("Hello World!", "image/jpeg");
  17313. res.set_header("Content-Encoding", "UTF-8");
  17314. });
  17315. svr_.Get("/chunked", [](const Request &, Response &res) {
  17316. res.set_chunked_content_provider("text/plain",
  17317. [](size_t offset, DataSink &sink) {
  17318. if (offset < 15) {
  17319. sink.write("chunk", 5);
  17320. return true;
  17321. }
  17322. sink.done();
  17323. return true;
  17324. });
  17325. });
  17326. svr_.Get("/compressible", [](const Request &, Response &res) {
  17327. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17328. DataSink &sink) {
  17329. if (offset < 100 * 1024) {
  17330. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17331. sink.write(chunk.data(), chunk.size());
  17332. return true;
  17333. }
  17334. sink.done();
  17335. return true;
  17336. });
  17337. });
  17338. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17339. [](const Request & /*req*/, Response &res) {
  17340. auto i = new int(0);
  17341. res.set_header("Trailer", "Content-Length, X-Allowed");
  17342. res.set_chunked_content_provider(
  17343. "text/plain",
  17344. [i](size_t /*offset*/, DataSink &sink) {
  17345. switch (*i) {
  17346. case 0: sink.os << "123"; break;
  17347. case 1: sink.os << "456"; break;
  17348. case 2: sink.os << "789"; break;
  17349. case 3: {
  17350. sink.done_with_trailer(
  17351. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17352. } break;
  17353. }
  17354. (*i)++;
  17355. return true;
  17356. },
  17357. [i](bool success) {
  17358. EXPECT_TRUE(success);
  17359. delete i;
  17360. });
  17361. });
  17362. // Echo headers endpoint for header-related tests
  17363. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17364. std::string body;
  17365. for (const auto &h : req.headers) {
  17366. body.append(h.first);
  17367. body.push_back(':');
  17368. body.append(h.second);
  17369. body.push_back('\n');
  17370. }
  17371. res.set_content(body, "text/plain");
  17372. });
  17373. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17374. std::string body;
  17375. for (const auto &h : req.headers) {
  17376. body.append(h.first);
  17377. body.push_back(':');
  17378. body.append(h.second);
  17379. body.push_back('\n');
  17380. }
  17381. res.set_content(body, "text/plain");
  17382. });
  17383. port_ = svr_.bind_to_any_port("127.0.0.1");
  17384. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17385. svr_.wait_until_ready();
  17386. }
  17387. void TearDown() override {
  17388. svr_.stop();
  17389. if (thread_.joinable()) thread_.join();
  17390. }
  17391. Server svr_;
  17392. std::thread thread_;
  17393. int port_ = 0;
  17394. };
  17395. TEST_F(OpenStreamTest, Basic) {
  17396. Client cli("127.0.0.1", port_);
  17397. auto handle = cli.open_stream("GET", "/hello");
  17398. EXPECT_TRUE(handle.is_valid());
  17399. EXPECT_EQ("Hello World!", read_all(handle));
  17400. }
  17401. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17402. Client cli("127.0.0.1", port_);
  17403. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17404. ASSERT_TRUE(handle.is_valid());
  17405. EXPECT_EQ("Hello World!", read_all(handle));
  17406. }
  17407. TEST_F(OpenStreamTest, SmallBuffer) {
  17408. Client cli("127.0.0.1", port_);
  17409. auto handle = cli.open_stream("GET", "/hello");
  17410. std::string result;
  17411. char buf[4];
  17412. ssize_t n;
  17413. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17414. result.append(buf, static_cast<size_t>(n));
  17415. EXPECT_EQ("Hello World!", result);
  17416. }
  17417. TEST_F(OpenStreamTest, DefaultHeaders) {
  17418. Client cli("127.0.0.1", port_);
  17419. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17420. {
  17421. auto handle = cli.open_stream("GET", "/echo-headers");
  17422. ASSERT_TRUE(handle.is_valid());
  17423. auto body = read_all(handle);
  17424. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17425. std::string::npos);
  17426. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17427. std::string::npos);
  17428. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17429. }
  17430. // open_stream POST with body and no explicit content_type should NOT add
  17431. // text/plain Content-Type (behavior differs from non-streaming path), but
  17432. // should include Content-Length
  17433. {
  17434. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17435. ASSERT_TRUE(handle.is_valid());
  17436. auto body = read_all(handle);
  17437. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17438. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17439. }
  17440. // open_stream POST with explicit Content-Type should preserve it
  17441. {
  17442. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17443. {{"Content-Type", "application/custom"}},
  17444. "{}", "application/custom");
  17445. ASSERT_TRUE(handle.is_valid());
  17446. auto body = read_all(handle);
  17447. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17448. }
  17449. // User-specified User-Agent must not be overwritten for stream API
  17450. {
  17451. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17452. {{"User-Agent", "MyAgent/1.2"}});
  17453. ASSERT_TRUE(handle.is_valid());
  17454. auto body = read_all(handle);
  17455. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17456. }
  17457. }
  17458. TEST_F(OpenStreamTest, Large) {
  17459. Client cli("127.0.0.1", port_);
  17460. auto handle = cli.open_stream("GET", "/large");
  17461. EXPECT_EQ(10000u, read_all(handle).size());
  17462. }
  17463. TEST_F(OpenStreamTest, ConnectionError) {
  17464. Client cli("127.0.0.1", 9999);
  17465. auto handle = cli.open_stream("GET", "/hello");
  17466. EXPECT_FALSE(handle.is_valid());
  17467. }
  17468. TEST_F(OpenStreamTest, Chunked) {
  17469. Client cli("127.0.0.1", port_);
  17470. auto handle = cli.open_stream("GET", "/chunked");
  17471. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17472. "Transfer-Encoding") == "chunked");
  17473. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17474. }
  17475. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17476. Client cli("127.0.0.1", port_);
  17477. auto handle =
  17478. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17479. ASSERT_TRUE(handle.is_valid());
  17480. // Consume body to allow trailers to be received/parsed
  17481. auto body = read_all(handle);
  17482. // Explicitly parse trailers (ensure trailers are available for assertion)
  17483. handle.parse_trailers_if_needed();
  17484. EXPECT_EQ(std::string("123456789"), body);
  17485. // The response should include a Trailer header declaring both names
  17486. ASSERT_TRUE(handle.response);
  17487. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17488. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17489. handle.response->get_header_value("Trailer"));
  17490. // Prohibited trailer must not be present
  17491. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17492. // Allowed trailer should be present
  17493. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17494. EXPECT_EQ(std::string("yes"),
  17495. handle.response->get_trailer_value("X-Allowed"));
  17496. // Verify trailers are NOT present as regular headers
  17497. EXPECT_EQ(std::string(""),
  17498. handle.response->get_header_value("Content-Length"));
  17499. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17500. }
  17501. static std::thread serve_single_response(std::promise<int> &port_promise,
  17502. const std::string &response) {
  17503. return std::thread([&port_promise, response] {
  17504. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17505. default_socket_options(srv);
  17506. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17507. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17508. sockaddr_in addr{};
  17509. addr.sin_family = AF_INET;
  17510. addr.sin_port = htons(0); // Let OS assign a free port
  17511. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17512. int opt = 1;
  17513. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17514. #ifdef _WIN32
  17515. reinterpret_cast<const char *>(&opt),
  17516. #else
  17517. &opt,
  17518. #endif
  17519. sizeof(opt));
  17520. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17521. ::listen(srv, 1) != 0) {
  17522. port_promise.set_value(-1);
  17523. detail::close_socket(srv);
  17524. return;
  17525. }
  17526. socklen_t addr_len = sizeof(addr);
  17527. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17528. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17529. sockaddr_in cli_addr{};
  17530. socklen_t cli_len = sizeof(cli_addr);
  17531. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17532. if (cli != INVALID_SOCKET) {
  17533. // Read the complete HTTP request (until the blank line that terminates
  17534. // headers) before sending the response. If the server closes the socket
  17535. // while the client's request data is still unread in the kernel receive
  17536. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17537. // connection on both sides: it discards the client's receive buffer
  17538. // (which already holds our response) and causes any in-progress write on
  17539. // the client to fail with ECONNRESET. Reading all request data first
  17540. // ensures close() emits a graceful FIN.
  17541. {
  17542. char rbuf[256];
  17543. std::string req;
  17544. while (req.find("\r\n\r\n") == std::string::npos) {
  17545. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17546. if (n <= 0) { break; }
  17547. req.append(rbuf, static_cast<size_t>(n));
  17548. }
  17549. }
  17550. ::send(cli,
  17551. #ifdef _WIN32
  17552. static_cast<const char *>(response.c_str()),
  17553. static_cast<int>(response.size()),
  17554. #else
  17555. response.c_str(), response.size(),
  17556. #endif
  17557. 0);
  17558. detail::close_socket(cli);
  17559. }
  17560. detail::close_socket(srv);
  17561. });
  17562. }
  17563. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17564. #ifndef _WIN32
  17565. signal(SIGPIPE, SIG_IGN);
  17566. #endif
  17567. std::promise<int> port_promise;
  17568. auto port_future = port_promise.get_future();
  17569. auto server_thread =
  17570. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17571. "Content-Type: text/plain\r\n"
  17572. "Content-Length: not-a-number\r\n"
  17573. "Connection: close\r\n"
  17574. "\r\n"
  17575. "hello");
  17576. auto port = port_future.get();
  17577. ASSERT_GT(port, 0);
  17578. Client cli("127.0.0.1", port);
  17579. auto handle = cli.open_stream("GET", "/");
  17580. EXPECT_FALSE(handle.is_valid());
  17581. server_thread.join();
  17582. }
  17583. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17584. #ifndef _WIN32
  17585. signal(SIGPIPE, SIG_IGN);
  17586. #endif
  17587. std::promise<int> port_promise;
  17588. auto port_future = port_promise.get_future();
  17589. auto server_thread = serve_single_response(
  17590. port_promise, "HTTP/1.1 200 OK\r\n"
  17591. "Content-Type: text/plain\r\n"
  17592. "Content-Length: 99999999999999999999999999\r\n"
  17593. "Connection: close\r\n"
  17594. "\r\n"
  17595. "hello");
  17596. auto port = port_future.get();
  17597. ASSERT_GT(port, 0);
  17598. // Historically std::stoull would throw std::out_of_range here and crash
  17599. // the process, then parsing silently clamped to a bogus framing length and
  17600. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17601. // so the stream fails to open, matching the not-a-number case above. The
  17602. // process still must NOT terminate.
  17603. Client cli("127.0.0.1", port);
  17604. auto handle = cli.open_stream("GET", "/");
  17605. EXPECT_FALSE(handle.is_valid());
  17606. server_thread.join();
  17607. }
  17608. // Serves `response` to the single request `fn` makes with a fresh client.
  17609. template <typename Fn>
  17610. static void with_single_response(const std::string &response, Fn fn) {
  17611. #ifndef _WIN32
  17612. signal(SIGPIPE, SIG_IGN);
  17613. #endif
  17614. std::promise<int> port_promise;
  17615. auto port_future = port_promise.get_future();
  17616. auto server_thread = serve_single_response(port_promise, response);
  17617. auto se = detail::scope_exit([&] { server_thread.join(); });
  17618. auto port = port_future.get();
  17619. ASSERT_GT(port, 0);
  17620. Client cli("127.0.0.1", port);
  17621. fn(cli);
  17622. }
  17623. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17624. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17625. // the chunked coding and drop Content-Length, so a front-end that trusts
  17626. // Content-Length would disagree about where the body ends (response
  17627. // smuggling). The client must reject such a response.
  17628. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17629. for (const char *te : {"chunked", "gzip, chunked"}) {
  17630. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17631. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17632. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17633. "5\r\nhello\r\n0\r\n\r\n";
  17634. with_single_response(response, [&](Client &cli) {
  17635. auto res = cli.Get("/");
  17636. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17637. EXPECT_EQ(Error::Read, res.error()) << te;
  17638. });
  17639. with_single_response(response, [&](Client &cli) {
  17640. auto handle = cli.open_stream("GET", "/");
  17641. EXPECT_FALSE(handle.is_valid()) << te;
  17642. EXPECT_EQ(Error::Read, handle.error) << te;
  17643. });
  17644. }
  17645. }
  17646. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17647. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17648. // closing the connection (unlike a request, which must be rejected).
  17649. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17650. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17651. "Transfer-Encoding: chunked\r\n"
  17652. "Connection: close\r\n"
  17653. "\r\n"
  17654. "5\r\nhello\r\n0\r\n\r\n",
  17655. "HTTP/1.1 200 OK\r\n"
  17656. "Transfer-Encoding: gzip\r\n"
  17657. "Connection: close\r\n"
  17658. "\r\n"
  17659. "hello"}) {
  17660. with_single_response(response, [&](Client &cli) {
  17661. auto res = cli.Get("/");
  17662. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17663. EXPECT_EQ("hello", res->body);
  17664. });
  17665. with_single_response(response, [&](Client &cli) {
  17666. auto handle = cli.open_stream("GET", "/");
  17667. ASSERT_TRUE(handle.is_valid()) << response;
  17668. EXPECT_EQ("hello", read_all(handle));
  17669. });
  17670. }
  17671. }
  17672. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17673. // framing headers describe nothing to read and must not be rejected.
  17674. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17675. const std::string framing = "Content-Length: 5\r\n"
  17676. "Transfer-Encoding: chunked\r\n"
  17677. "Connection: close\r\n"
  17678. "\r\n";
  17679. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17680. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17681. });
  17682. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17683. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17684. });
  17685. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17686. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17687. with_single_response(response, [&](Client &cli) {
  17688. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17689. });
  17690. with_single_response(response, [&](Client &cli) {
  17691. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17692. });
  17693. }
  17694. }
  17695. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17696. TEST_F(OpenStreamTest, Gzip) {
  17697. Client cli("127.0.0.1", port_);
  17698. auto handle = cli.open_stream("GET", "/compressible", {},
  17699. {{"Accept-Encoding", "gzip"}});
  17700. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17701. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17702. }
  17703. #endif
  17704. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17705. TEST_F(OpenStreamTest, Brotli) {
  17706. Client cli("127.0.0.1", port_);
  17707. auto handle =
  17708. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17709. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17710. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17711. }
  17712. #endif
  17713. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17714. TEST_F(OpenStreamTest, Zstd) {
  17715. Client cli("127.0.0.1", port_);
  17716. auto handle = cli.open_stream("GET", "/compressible", {},
  17717. {{"Accept-Encoding", "zstd"}});
  17718. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17719. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17720. }
  17721. #endif
  17722. #ifdef CPPHTTPLIB_SSL_ENABLED
  17723. class SSLOpenStreamTest : public ::testing::Test {
  17724. protected:
  17725. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17726. void SetUp() override {
  17727. svr_.Get("/hello", [](const Request &, Response &res) {
  17728. res.set_content("Hello SSL World!", "text/plain");
  17729. });
  17730. svr_.Get("/chunked", [](const Request &, Response &res) {
  17731. res.set_chunked_content_provider("text/plain",
  17732. [](size_t offset, DataSink &sink) {
  17733. if (offset < 15) {
  17734. sink.write("chunk", 5);
  17735. return true;
  17736. }
  17737. sink.done();
  17738. return true;
  17739. });
  17740. });
  17741. svr_.Post("/echo", [](const Request &req, Response &res) {
  17742. res.set_content(req.body, req.get_header_value("Content-Type"));
  17743. });
  17744. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17745. std::string body = req.body;
  17746. res.set_chunked_content_provider(
  17747. "text/plain", [body](size_t offset, DataSink &sink) {
  17748. if (offset < body.size()) {
  17749. sink.write(body.data() + offset, body.size() - offset);
  17750. }
  17751. sink.done();
  17752. return true;
  17753. });
  17754. });
  17755. port_ = svr_.bind_to_any_port("127.0.0.1");
  17756. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17757. svr_.wait_until_ready();
  17758. }
  17759. void TearDown() override {
  17760. svr_.stop();
  17761. if (thread_.joinable()) thread_.join();
  17762. }
  17763. SSLServer svr_;
  17764. std::thread thread_;
  17765. int port_ = 0;
  17766. };
  17767. TEST_F(SSLOpenStreamTest, Basic) {
  17768. SSLClient cli("127.0.0.1", port_);
  17769. cli.enable_server_certificate_verification(false);
  17770. auto handle = cli.open_stream("GET", "/hello");
  17771. ASSERT_TRUE(handle.is_valid());
  17772. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17773. }
  17774. TEST_F(SSLOpenStreamTest, Chunked) {
  17775. SSLClient cli("127.0.0.1", port_);
  17776. cli.enable_server_certificate_verification(false);
  17777. auto handle = cli.open_stream("GET", "/chunked");
  17778. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17779. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17780. "Transfer-Encoding") == "chunked");
  17781. auto body = read_all(handle);
  17782. EXPECT_EQ("chunkchunkchunk", body);
  17783. }
  17784. TEST_F(SSLOpenStreamTest, Post) {
  17785. SSLClient cli("127.0.0.1", port_);
  17786. cli.enable_server_certificate_verification(false);
  17787. auto handle =
  17788. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17789. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17790. EXPECT_EQ(200, handle.response->status);
  17791. auto body = read_all(handle);
  17792. EXPECT_EQ("Hello SSL POST", body);
  17793. }
  17794. TEST_F(SSLOpenStreamTest, PostChunked) {
  17795. SSLClient cli("127.0.0.1", port_);
  17796. cli.enable_server_certificate_verification(false);
  17797. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17798. "Chunked SSL Data", "text/plain");
  17799. ASSERT_TRUE(handle.is_valid());
  17800. EXPECT_EQ(200, handle.response->status);
  17801. auto body = read_all(handle);
  17802. EXPECT_EQ("Chunked SSL Data", body);
  17803. }
  17804. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17805. // Content-Length is terminated by the server closing the connection. When the
  17806. // SSL peer sends a close_notify after the body, the client must treat it as a
  17807. // clean EOF and return a successful response rather than an error.
  17808. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17809. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17810. ASSERT_TRUE(svr.is_valid());
  17811. svr.set_keep_alive_max_count(1);
  17812. const std::string expected_body = "Hello from connection-close response!";
  17813. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17814. res.set_content_provider("text/plain",
  17815. [&](size_t offset, DataSink &sink) -> bool {
  17816. if (offset < expected_body.size()) {
  17817. sink.write(expected_body.data() + offset,
  17818. expected_body.size() - offset);
  17819. }
  17820. sink.done();
  17821. return true;
  17822. });
  17823. });
  17824. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17825. auto se = detail::scope_exit([&] {
  17826. svr.stop();
  17827. listen_thread.join();
  17828. ASSERT_FALSE(svr.is_running());
  17829. });
  17830. svr.wait_until_ready();
  17831. SSLClient cli(HOST, PORT);
  17832. cli.enable_server_certificate_verification(false);
  17833. auto res = cli.Get("/no-content-length");
  17834. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17835. EXPECT_EQ(StatusCode::OK_200, res->status);
  17836. EXPECT_EQ(expected_body, res->body);
  17837. }
  17838. #endif // CPPHTTPLIB_SSL_ENABLED
  17839. //==============================================================================
  17840. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17841. // results for various scenarios.
  17842. //==============================================================================
  17843. TEST(ParityTest, GetVsOpenStream) {
  17844. Server svr;
  17845. const std::string path = "/parity";
  17846. const std::string content = "Parity test content: hello world";
  17847. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17848. res.set_content(content, "text/plain");
  17849. });
  17850. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17851. auto se = detail::scope_exit([&] {
  17852. svr.stop();
  17853. t.join();
  17854. ASSERT_FALSE(svr.is_running());
  17855. });
  17856. svr.wait_until_ready();
  17857. Client cli(HOST, PORT);
  17858. // Non-stream path
  17859. auto r1 = cli.Get(path);
  17860. ASSERT_TRUE(r1);
  17861. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17862. // Stream path
  17863. auto h = cli.open_stream("GET", path);
  17864. ASSERT_TRUE(h.is_valid());
  17865. EXPECT_EQ(r1->body, read_all(h));
  17866. }
  17867. // Helper to compress data with provided compressor type T
  17868. template <typename Compressor>
  17869. static std::string compress_payload_for_parity(const std::string &in) {
  17870. std::string out;
  17871. Compressor compressor;
  17872. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17873. [&](const char *data, size_t n) {
  17874. out.append(data, n);
  17875. return true;
  17876. });
  17877. EXPECT_TRUE(ok);
  17878. return out;
  17879. }
  17880. // Helper function for compression parity tests
  17881. template <typename Compressor>
  17882. static void test_compression_parity(const std::string &original,
  17883. const std::string &path,
  17884. const std::string &encoding) {
  17885. const std::string compressed =
  17886. compress_payload_for_parity<Compressor>(original);
  17887. Server svr;
  17888. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17889. res.set_content(compressed, "application/octet-stream");
  17890. res.set_header("Content-Encoding", encoding);
  17891. });
  17892. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17893. auto se = detail::scope_exit([&] {
  17894. svr.stop();
  17895. t.join();
  17896. ASSERT_FALSE(svr.is_running());
  17897. });
  17898. svr.wait_until_ready();
  17899. Client cli(HOST, PORT);
  17900. // Non-streaming
  17901. {
  17902. auto res = cli.Get(path);
  17903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17904. EXPECT_EQ(StatusCode::OK_200, res->status);
  17905. EXPECT_EQ(original, res->body);
  17906. }
  17907. // Streaming
  17908. {
  17909. auto h = cli.open_stream("GET", path);
  17910. ASSERT_TRUE(h.is_valid());
  17911. EXPECT_EQ(original, read_all(h));
  17912. }
  17913. }
  17914. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17915. TEST(ParityTest, Gzip) {
  17916. test_compression_parity<detail::gzip_compressor>(
  17917. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17918. }
  17919. #endif
  17920. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17921. TEST(ParityTest, Brotli) {
  17922. test_compression_parity<detail::brotli_compressor>(
  17923. "Hello, brotli parity test payload", "/parity-br", "br");
  17924. }
  17925. #endif
  17926. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17927. TEST(ParityTest, Zstd) {
  17928. test_compression_parity<detail::zstd_compressor>(
  17929. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17930. }
  17931. #endif
  17932. //==============================================================================
  17933. // New Stream API Tests
  17934. //==============================================================================
  17935. inline std::string read_body(httplib::stream::Result &result) {
  17936. std::string body;
  17937. while (result.next()) {
  17938. body.append(result.data(), result.size());
  17939. }
  17940. return body;
  17941. }
  17942. TEST(ClientConnectionTest, Basic) {
  17943. httplib::ClientConnection conn;
  17944. EXPECT_FALSE(conn.is_open());
  17945. conn.sock = 1;
  17946. EXPECT_TRUE(conn.is_open());
  17947. httplib::ClientConnection conn2(std::move(conn));
  17948. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17949. conn2.sock = INVALID_SOCKET;
  17950. }
  17951. // Unified test server for all stream::* tests
  17952. class StreamApiTest : public ::testing::Test {
  17953. protected:
  17954. void SetUp() override {
  17955. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17956. res.set_content("Hello World!", "text/plain");
  17957. });
  17958. svr_.Get("/echo-params",
  17959. [](const httplib::Request &req, httplib::Response &res) {
  17960. std::string r;
  17961. for (const auto &p : req.params) {
  17962. if (!r.empty()) r += "&";
  17963. r += p.first + "=" + p.second;
  17964. }
  17965. res.set_content(r, "text/plain");
  17966. });
  17967. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17968. res.set_content(req.body, req.get_header_value("Content-Type"));
  17969. });
  17970. svr_.Post("/echo-headers",
  17971. [](const httplib::Request &req, httplib::Response &res) {
  17972. std::string r;
  17973. for (const auto &h : req.headers)
  17974. r += h.first + ": " + h.second + "\n";
  17975. res.set_content(r, "text/plain");
  17976. });
  17977. svr_.Post("/echo-params",
  17978. [](const httplib::Request &req, httplib::Response &res) {
  17979. std::string r = "params:";
  17980. for (const auto &p : req.params)
  17981. r += p.first + "=" + p.second + ";";
  17982. res.set_content(r + " body:" + req.body, "text/plain");
  17983. });
  17984. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17985. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17986. });
  17987. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17988. res.set_content("PUT:" + req.body, "text/plain");
  17989. });
  17990. svr_.Patch("/echo",
  17991. [](const httplib::Request &req, httplib::Response &res) {
  17992. res.set_content("PATCH:" + req.body, "text/plain");
  17993. });
  17994. svr_.Delete(
  17995. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17996. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17997. "text/plain");
  17998. });
  17999. svr_.Get("/head-test",
  18000. [](const httplib::Request &, httplib::Response &res) {
  18001. res.set_content("body for HEAD", "text/plain");
  18002. });
  18003. svr_.Options("/options",
  18004. [](const httplib::Request &, httplib::Response &res) {
  18005. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18006. });
  18007. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18008. svr_.wait_until_ready();
  18009. }
  18010. void TearDown() override {
  18011. svr_.stop();
  18012. if (thread_.joinable()) thread_.join();
  18013. }
  18014. httplib::Server svr_;
  18015. std::thread thread_;
  18016. };
  18017. // stream::Get tests
  18018. TEST_F(StreamApiTest, GetBasic) {
  18019. httplib::Client cli(HOST, PORT);
  18020. auto result = httplib::stream::Get(cli, "/hello");
  18021. ASSERT_TRUE(result.is_valid());
  18022. EXPECT_EQ(200, result.status());
  18023. EXPECT_EQ("Hello World!", read_body(result));
  18024. }
  18025. TEST_F(StreamApiTest, GetWithParams) {
  18026. httplib::Client cli(HOST, PORT);
  18027. httplib::Params params{{"foo", "bar"}};
  18028. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18029. ASSERT_TRUE(result.is_valid());
  18030. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18031. }
  18032. TEST_F(StreamApiTest, GetConnectionError) {
  18033. httplib::Client cli(HOST, 9999);
  18034. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18035. }
  18036. TEST_F(StreamApiTest, Get404) {
  18037. httplib::Client cli(HOST, PORT);
  18038. auto result = httplib::stream::Get(cli, "/nonexistent");
  18039. EXPECT_TRUE(result.is_valid());
  18040. EXPECT_EQ(404, result.status());
  18041. }
  18042. // stream::Post tests
  18043. TEST_F(StreamApiTest, PostBasic) {
  18044. httplib::Client cli(HOST, PORT);
  18045. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18046. "application/json");
  18047. ASSERT_TRUE(result.is_valid());
  18048. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18049. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18050. }
  18051. TEST_F(StreamApiTest, PostWithHeaders) {
  18052. httplib::Client cli(HOST, PORT);
  18053. httplib::Headers headers{{"X-Custom", "value"}};
  18054. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18055. "text/plain");
  18056. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18057. }
  18058. TEST_F(StreamApiTest, PostWithParams) {
  18059. httplib::Client cli(HOST, PORT);
  18060. httplib::Params params{{"k", "v"}};
  18061. auto result =
  18062. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18063. auto body = read_body(result);
  18064. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18065. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18066. }
  18067. TEST_F(StreamApiTest, PostLarge) {
  18068. httplib::Client cli(HOST, PORT);
  18069. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18070. size_t total = 0;
  18071. while (result.next()) {
  18072. total += result.size();
  18073. }
  18074. EXPECT_EQ(100u * 1024u, total);
  18075. }
  18076. // stream::Put/Patch tests
  18077. TEST_F(StreamApiTest, PutAndPatch) {
  18078. httplib::Client cli(HOST, PORT);
  18079. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18080. EXPECT_EQ("PUT:test", read_body(put));
  18081. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18082. EXPECT_EQ("PATCH:test", read_body(patch));
  18083. }
  18084. // stream::Delete tests
  18085. TEST_F(StreamApiTest, Delete) {
  18086. httplib::Client cli(HOST, PORT);
  18087. auto del1 = httplib::stream::Delete(cli, "/resource");
  18088. EXPECT_EQ("Deleted", read_body(del1));
  18089. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18090. EXPECT_EQ("Deleted:data", read_body(del2));
  18091. }
  18092. // stream::Head/Options tests
  18093. TEST_F(StreamApiTest, HeadAndOptions) {
  18094. httplib::Client cli(HOST, PORT);
  18095. auto head = httplib::stream::Head(cli, "/head-test");
  18096. EXPECT_TRUE(head.is_valid());
  18097. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18098. auto opts = httplib::stream::Options(cli, "/options");
  18099. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18100. }
  18101. // SSL stream::* tests
  18102. #ifdef CPPHTTPLIB_SSL_ENABLED
  18103. class SSLStreamApiTest : public ::testing::Test {
  18104. protected:
  18105. void SetUp() override {
  18106. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18107. res.set_content("Hello SSL!", "text/plain");
  18108. });
  18109. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18110. res.set_content(req.body, "text/plain");
  18111. });
  18112. port_ = svr_.bind_to_any_port("127.0.0.1");
  18113. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18114. svr_.wait_until_ready();
  18115. }
  18116. void TearDown() override {
  18117. svr_.stop();
  18118. if (thread_.joinable()) thread_.join();
  18119. }
  18120. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18121. std::thread thread_;
  18122. int port_ = 0;
  18123. };
  18124. TEST_F(SSLStreamApiTest, GetAndPost) {
  18125. httplib::SSLClient cli("127.0.0.1", port_);
  18126. cli.enable_server_certificate_verification(false);
  18127. auto get = httplib::stream::Get(cli, "/hello");
  18128. EXPECT_EQ("Hello SSL!", read_body(get));
  18129. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18130. EXPECT_EQ("test", read_body(post));
  18131. }
  18132. #endif
  18133. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18134. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18135. // BodyReader
  18136. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18137. // Test that read timeout during streaming is detected
  18138. // Use a large content-length response where server delays mid-stream
  18139. Server svr;
  18140. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18141. // Send a large response with delay in the middle
  18142. res.set_content_provider(
  18143. 1000, // content_length
  18144. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18145. if (offset < 100) {
  18146. // Send first 100 bytes immediately
  18147. std::string data(100, 'A');
  18148. sink.write(data.c_str(), data.size());
  18149. return true;
  18150. }
  18151. // Then delay longer than client timeout
  18152. std::this_thread::sleep_for(std::chrono::seconds(3));
  18153. std::string data(900, 'B');
  18154. sink.write(data.c_str(), data.size());
  18155. return true;
  18156. });
  18157. });
  18158. auto port = 8091;
  18159. std::thread t([&]() { svr.listen("localhost", port); });
  18160. svr.wait_until_ready();
  18161. Client cli("localhost", port);
  18162. cli.set_read_timeout(1, 0); // 1 second timeout
  18163. auto handle = cli.open_stream("GET", "/slow-stream");
  18164. ASSERT_TRUE(handle.is_valid());
  18165. char buf[256];
  18166. ssize_t total = 0;
  18167. ssize_t n;
  18168. bool got_error = false;
  18169. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18170. total += n;
  18171. }
  18172. if (n < 0) {
  18173. got_error = true;
  18174. // Should be timeout or read error
  18175. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18176. handle.get_read_error() == Error::Read)
  18177. << "Actual error: " << to_string(handle.get_read_error());
  18178. }
  18179. // Either we got an error, or we got less data than expected
  18180. EXPECT_TRUE(got_error || total < 1000)
  18181. << "Expected timeout but got all " << total << " bytes";
  18182. svr.stop();
  18183. t.join();
  18184. }
  18185. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18186. // Test connection closed detection via BodyReader
  18187. Server svr;
  18188. std::atomic<bool> close_now{false};
  18189. svr.Get("/will-close", [&](const Request &, Response &res) {
  18190. res.set_content_provider(
  18191. 10000, // Large content_length that we won't fully send
  18192. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18193. if (offset < 100) {
  18194. std::string data(100, 'X');
  18195. sink.write(data.c_str(), data.size());
  18196. return true;
  18197. }
  18198. // Wait for signal then abort
  18199. while (!close_now) {
  18200. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18201. }
  18202. return false; // Abort - server will close connection
  18203. });
  18204. });
  18205. auto port = 8092;
  18206. std::thread t([&]() { svr.listen("localhost", port); });
  18207. svr.wait_until_ready();
  18208. Client cli("localhost", port);
  18209. auto handle = cli.open_stream("GET", "/will-close");
  18210. ASSERT_TRUE(handle.is_valid());
  18211. char buf[256];
  18212. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18213. EXPECT_GT(n, 0) << "First read should succeed";
  18214. // Signal server to close
  18215. close_now = true;
  18216. // Keep reading until error or EOF
  18217. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18218. // Keep reading
  18219. }
  18220. // Should get an error since content_length wasn't satisfied
  18221. if (n < 0) {
  18222. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18223. handle.get_read_error() == Error::Read)
  18224. << "Actual error: " << to_string(handle.get_read_error());
  18225. }
  18226. svr.stop();
  18227. t.join();
  18228. }
  18229. #ifdef CPPHTTPLIB_SSL_ENABLED
  18230. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18231. // Test that read timeout during SSL streaming is detected
  18232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18233. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18234. res.set_content_provider(
  18235. 1000, "text/plain",
  18236. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18237. if (offset < 100) {
  18238. std::string data(100, 'A');
  18239. sink.write(data.c_str(), data.size());
  18240. return true;
  18241. }
  18242. std::this_thread::sleep_for(std::chrono::seconds(3));
  18243. std::string data(900, 'B');
  18244. sink.write(data.c_str(), data.size());
  18245. return true;
  18246. });
  18247. });
  18248. auto port = 8093;
  18249. std::thread t([&]() { svr.listen("localhost", port); });
  18250. svr.wait_until_ready();
  18251. SSLClient cli("localhost", port);
  18252. cli.enable_server_certificate_verification(false);
  18253. cli.set_read_timeout(1, 0); // 1 second timeout
  18254. auto handle = cli.open_stream("GET", "/slow-stream");
  18255. ASSERT_TRUE(handle.is_valid());
  18256. char buf[256];
  18257. ssize_t total = 0;
  18258. ssize_t n;
  18259. bool got_error = false;
  18260. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18261. total += n;
  18262. }
  18263. if (n < 0) {
  18264. got_error = true;
  18265. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18266. handle.get_read_error() == Error::Read)
  18267. << "Actual error: " << to_string(handle.get_read_error());
  18268. }
  18269. EXPECT_TRUE(got_error || total < 1000)
  18270. << "Expected timeout but got all " << total << " bytes";
  18271. svr.stop();
  18272. t.join();
  18273. }
  18274. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18275. // Test SSL connection closed detection
  18276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18277. std::atomic<bool> close_now{false};
  18278. svr.Get("/will-close", [&](const Request &, Response &res) {
  18279. res.set_content_provider(
  18280. 10000, "text/plain",
  18281. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18282. if (offset < 100) {
  18283. std::string data(100, 'X');
  18284. sink.write(data.c_str(), data.size());
  18285. return true;
  18286. }
  18287. while (!close_now) {
  18288. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18289. }
  18290. return false;
  18291. });
  18292. });
  18293. auto port = 8094;
  18294. std::thread t([&]() { svr.listen("localhost", port); });
  18295. svr.wait_until_ready();
  18296. SSLClient cli("localhost", port);
  18297. cli.enable_server_certificate_verification(false);
  18298. auto handle = cli.open_stream("GET", "/will-close");
  18299. ASSERT_TRUE(handle.is_valid());
  18300. char buf[256];
  18301. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18302. EXPECT_GT(n, 0);
  18303. // Signal server to close
  18304. close_now = true;
  18305. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18306. // Keep reading
  18307. }
  18308. if (n < 0) {
  18309. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18310. handle.get_read_error() == Error::Read)
  18311. << "Actual error: " << to_string(handle.get_read_error());
  18312. }
  18313. svr.stop();
  18314. t.join();
  18315. }
  18316. #endif
  18317. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18318. using namespace httplib;
  18319. // Create a test file
  18320. const char *fname = "etag_testfile.txt";
  18321. const char *content = "etag-content";
  18322. {
  18323. std::ofstream ofs(fname);
  18324. ofs << content;
  18325. ASSERT_TRUE(ofs.good());
  18326. }
  18327. Server svr;
  18328. svr.set_mount_point("/static", ".");
  18329. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18330. svr.wait_until_ready();
  18331. Client cli(HOST, PORT);
  18332. // First request: should get 200 with ETag header
  18333. auto res1 = cli.Get("/static/etag_testfile.txt");
  18334. ASSERT_TRUE(res1);
  18335. ASSERT_EQ(200, res1->status);
  18336. ASSERT_TRUE(res1->has_header("ETag"));
  18337. std::string etag = res1->get_header_value("ETag");
  18338. EXPECT_FALSE(etag.empty());
  18339. // Verify ETag format: W/"hex-hex"
  18340. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18341. EXPECT_EQ('W', etag[0]);
  18342. EXPECT_EQ('/', etag[1]);
  18343. EXPECT_EQ('"', etag[2]);
  18344. EXPECT_EQ('"', etag.back());
  18345. // Exact match: expect 304 Not Modified
  18346. Headers h2 = {{"If-None-Match", etag}};
  18347. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18348. ASSERT_TRUE(res2);
  18349. EXPECT_EQ(304, res2->status);
  18350. // Wildcard match: expect 304 Not Modified
  18351. Headers h3 = {{"If-None-Match", "*"}};
  18352. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18353. ASSERT_TRUE(res3);
  18354. EXPECT_EQ(304, res3->status);
  18355. // Non-matching ETag: expect 200
  18356. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18357. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18358. ASSERT_TRUE(res4);
  18359. EXPECT_EQ(200, res4->status);
  18360. // Multiple ETags with one matching: expect 304
  18361. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18362. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18363. ASSERT_TRUE(res5);
  18364. EXPECT_EQ(304, res5->status);
  18365. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18366. // that equivalent to the single comma-separated list above, so the match on
  18367. // the second line must still be found.
  18368. Headers h6;
  18369. h6.emplace("If-None-Match", "W/\"other\"");
  18370. h6.emplace("If-None-Match", etag);
  18371. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18372. ASSERT_TRUE(res6);
  18373. EXPECT_EQ(304, res6->status);
  18374. svr.stop();
  18375. t.join();
  18376. std::remove(fname);
  18377. }
  18378. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18379. using namespace httplib;
  18380. Server svr;
  18381. svr.set_mount_point("/static", ".");
  18382. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18383. svr.wait_until_ready();
  18384. Client cli(HOST, PORT);
  18385. // Send If-None-Match: * to a non-existent file
  18386. Headers h = {{"If-None-Match", "*"}};
  18387. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18389. EXPECT_EQ(404, res->status);
  18390. svr.stop();
  18391. t.join();
  18392. }
  18393. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18394. using namespace httplib;
  18395. // Create a test file
  18396. const char *fname = "etag_boundary_testfile.txt";
  18397. const char *content = "boundary-test";
  18398. {
  18399. std::ofstream ofs(fname);
  18400. ofs << content;
  18401. ASSERT_TRUE(ofs.good());
  18402. }
  18403. Server svr;
  18404. svr.set_mount_point("/static", ".");
  18405. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18406. svr.wait_until_ready();
  18407. Client cli(HOST, PORT);
  18408. // Get the actual ETag
  18409. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18410. ASSERT_TRUE(res1);
  18411. ASSERT_EQ(200, res1->status);
  18412. ASSERT_TRUE(res1->has_header("ETag"));
  18413. std::string etag = res1->get_header_value("ETag");
  18414. // Test 1: Very long ETag value (longer than actual ETag)
  18415. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18416. Headers h1 = {{"If-None-Match", "W/"
  18417. "\"very-long-etag-value-that-is-much-longer-"
  18418. "than-the-actual-etag-value\""}};
  18419. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18420. ASSERT_TRUE(res2);
  18421. EXPECT_EQ(200, res2->status); // Should not match
  18422. // Test 2: Long string followed by wildcard
  18423. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18424. // string)
  18425. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18426. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18427. ASSERT_TRUE(res3);
  18428. EXPECT_EQ(304, res3->status); // Should match on "*"
  18429. // Test 3: Wildcard followed by long string
  18430. // Should match on "*" immediately and return 304
  18431. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18432. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18433. ASSERT_TRUE(res4);
  18434. EXPECT_EQ(304, res4->status); // Should match on "*"
  18435. // Test 4: Multiple long non-matching values
  18436. // Should NOT match and return 200 (test that all comparisons are safe)
  18437. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18438. "W/\"second-long-non-matching-value\", "
  18439. "W/\"third-long-non-matching-value\""}};
  18440. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18441. ASSERT_TRUE(res5);
  18442. EXPECT_EQ(200, res5->status); // Should not match
  18443. // Test 5: Single character that is not "*" (edge case)
  18444. Headers h5 = {{"If-None-Match", "X"}};
  18445. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18446. ASSERT_TRUE(res6);
  18447. EXPECT_EQ(200, res6->status); // Should not match
  18448. svr.stop();
  18449. t.join();
  18450. std::remove(fname);
  18451. }
  18452. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18453. using namespace httplib;
  18454. // Create a test file
  18455. const char *fname = "ims_testfile.txt";
  18456. const char *content = "if-modified-since-test";
  18457. {
  18458. std::ofstream ofs(fname);
  18459. ofs << content;
  18460. ASSERT_TRUE(ofs.good());
  18461. }
  18462. Server svr;
  18463. svr.set_mount_point("/static", ".");
  18464. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18465. svr.wait_until_ready();
  18466. Client cli(HOST, PORT);
  18467. // First request: should get 200 with Last-Modified header
  18468. auto res1 = cli.Get("/static/ims_testfile.txt");
  18469. ASSERT_TRUE(res1);
  18470. ASSERT_EQ(200, res1->status);
  18471. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18472. std::string last_modified = res1->get_header_value("Last-Modified");
  18473. EXPECT_FALSE(last_modified.empty());
  18474. // If-Modified-Since with same time: expect 304
  18475. Headers h2 = {{"If-Modified-Since", last_modified}};
  18476. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18477. ASSERT_TRUE(res2);
  18478. EXPECT_EQ(304, res2->status);
  18479. // If-Modified-Since with future time: expect 304
  18480. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18481. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18482. ASSERT_TRUE(res3);
  18483. EXPECT_EQ(304, res3->status);
  18484. // If-Modified-Since with past time: expect 200
  18485. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18486. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18487. ASSERT_TRUE(res4);
  18488. EXPECT_EQ(200, res4->status);
  18489. // If-None-Match takes precedence over If-Modified-Since
  18490. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18491. ASSERT_TRUE(res1->has_header("ETag"));
  18492. std::string etag = res1->get_header_value("ETag");
  18493. Headers h5 = {{"If-None-Match", etag},
  18494. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18495. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18496. ASSERT_TRUE(res5);
  18497. EXPECT_EQ(304, res5->status);
  18498. svr.stop();
  18499. t.join();
  18500. std::remove(fname);
  18501. }
  18502. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18503. using namespace httplib;
  18504. Server svr;
  18505. // Endpoint that returns compressible content
  18506. svr.Get("/compressible", [](const Request &, Response &res) {
  18507. // Return a large enough body to trigger compression
  18508. std::string body(1000, 'a');
  18509. res.set_content(body, "text/plain");
  18510. });
  18511. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18512. svr.wait_until_ready();
  18513. Client cli(HOST, PORT);
  18514. // Request with gzip support: should get Vary header when compressed
  18515. cli.set_compress(true);
  18516. auto res1 = cli.Get("/compressible");
  18517. ASSERT_TRUE(res1);
  18518. EXPECT_EQ(200, res1->status);
  18519. // If Content-Encoding is set, Vary should also be set
  18520. if (res1->has_header("Content-Encoding")) {
  18521. EXPECT_TRUE(res1->has_header("Vary"));
  18522. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18523. }
  18524. // Request without Accept-Encoding header: should not have compression
  18525. Headers h_no_compress;
  18526. auto res2 = cli.Get("/compressible", h_no_compress);
  18527. ASSERT_TRUE(res2);
  18528. EXPECT_EQ(200, res2->status);
  18529. // Verify Vary header is present when compression is applied
  18530. // (the exact behavior depends on server configuration)
  18531. svr.stop();
  18532. t.join();
  18533. }
  18534. TEST(ETagTest, IfRangeWithETag) {
  18535. using namespace httplib;
  18536. // Create a test file with known content
  18537. const char *fname = "if_range_testfile.txt";
  18538. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18539. {
  18540. std::ofstream ofs(fname);
  18541. ofs << content;
  18542. ASSERT_TRUE(ofs.good());
  18543. }
  18544. Server svr;
  18545. svr.set_mount_point("/static", ".");
  18546. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18547. svr.wait_until_ready();
  18548. Client cli(HOST, PORT);
  18549. // First request: get ETag
  18550. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18551. ASSERT_TRUE(res1);
  18552. ASSERT_EQ(200, res1->status);
  18553. ASSERT_TRUE(res1->has_header("ETag"));
  18554. std::string etag = res1->get_header_value("ETag");
  18555. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18556. // Since our server generates weak ETags (W/"..."), If-Range with our
  18557. // ETag should NOT result in partial content - it should return full content.
  18558. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18559. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18560. ASSERT_TRUE(res2);
  18561. // Weak ETag in If-Range -> full content (200), not partial (206)
  18562. EXPECT_EQ(200, res2->status);
  18563. EXPECT_EQ(content, res2->body);
  18564. EXPECT_FALSE(res2->has_header("Content-Range"));
  18565. // Range request with non-matching If-Range (ETag): should get 200 (full
  18566. // content)
  18567. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18568. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18569. ASSERT_TRUE(res3);
  18570. EXPECT_EQ(200, res3->status);
  18571. EXPECT_EQ(content, res3->body);
  18572. EXPECT_FALSE(res3->has_header("Content-Range"));
  18573. // Range request with strong ETag (hypothetical - our server doesn't generate
  18574. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18575. // should return full content)
  18576. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18577. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18578. ASSERT_TRUE(res4);
  18579. EXPECT_EQ(200, res4->status);
  18580. EXPECT_EQ(content, res4->body);
  18581. EXPECT_FALSE(res4->has_header("Content-Range"));
  18582. svr.stop();
  18583. t.join();
  18584. std::remove(fname);
  18585. }
  18586. TEST(ETagTest, IfRangeWithDate) {
  18587. using namespace httplib;
  18588. // Create a test file
  18589. const char *fname = "if_range_date_testfile.txt";
  18590. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18591. {
  18592. std::ofstream ofs(fname);
  18593. ofs << content;
  18594. ASSERT_TRUE(ofs.good());
  18595. }
  18596. Server svr;
  18597. svr.set_mount_point("/static", ".");
  18598. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18599. svr.wait_until_ready();
  18600. Client cli(HOST, PORT);
  18601. // First request: get Last-Modified
  18602. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18603. ASSERT_TRUE(res1);
  18604. ASSERT_EQ(200, res1->status);
  18605. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18606. std::string last_modified = res1->get_header_value("Last-Modified");
  18607. // Range request with matching If-Range (date): should get 206
  18608. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18609. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18610. ASSERT_TRUE(res2);
  18611. EXPECT_EQ(206, res2->status);
  18612. EXPECT_EQ("FGHIJ", res2->body);
  18613. // Range request with old If-Range date: should get 200 (full content)
  18614. Headers h3 = {{"Range", "bytes=5-9"},
  18615. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18616. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18617. ASSERT_TRUE(res3);
  18618. EXPECT_EQ(200, res3->status);
  18619. EXPECT_EQ(content, res3->body);
  18620. // Range request with future If-Range date: should get 206
  18621. Headers h4 = {{"Range", "bytes=0-4"},
  18622. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18623. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18624. ASSERT_TRUE(res4);
  18625. EXPECT_EQ(206, res4->status);
  18626. EXPECT_EQ("ABCDE", res4->body);
  18627. svr.stop();
  18628. t.join();
  18629. std::remove(fname);
  18630. }
  18631. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18632. using namespace httplib;
  18633. const char *fname = "etag_malformed.txt";
  18634. const char *content = "malformed-etag";
  18635. {
  18636. std::ofstream ofs(fname);
  18637. ofs << content;
  18638. ASSERT_TRUE(ofs.good());
  18639. }
  18640. Server svr;
  18641. svr.set_mount_point("/static", ".");
  18642. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18643. svr.wait_until_ready();
  18644. Client cli(HOST, PORT);
  18645. // baseline: should get 200 and an ETag
  18646. auto res1 = cli.Get("/static/etag_malformed.txt");
  18647. ASSERT_TRUE(res1);
  18648. ASSERT_EQ(200, res1->status);
  18649. ASSERT_TRUE(res1->has_header("ETag"));
  18650. // Malformed ETag value (missing quotes) should be treated as non-matching
  18651. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18652. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18653. ASSERT_TRUE(res_bad);
  18654. EXPECT_EQ(200, res_bad->status);
  18655. // Whitespace-only header value should be considered invalid / non-matching
  18656. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18657. "Host: localhost\r\n"
  18658. "If-None-Match: \r\n"
  18659. "Connection: close\r\n"
  18660. "\r\n";
  18661. std::string out;
  18662. ASSERT_TRUE(send_request(5, raw_req, &out));
  18663. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18664. svr.stop();
  18665. t.join();
  18666. std::remove(fname);
  18667. }
  18668. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18669. using namespace httplib;
  18670. const char *fname = "ims_invalid_format.txt";
  18671. const char *content = "ims-bad-format";
  18672. {
  18673. std::ofstream ofs(fname);
  18674. ofs << content;
  18675. ASSERT_TRUE(ofs.good());
  18676. }
  18677. Server svr;
  18678. svr.set_mount_point("/static", ".");
  18679. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18680. svr.wait_until_ready();
  18681. Client cli(HOST, PORT);
  18682. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18683. ASSERT_TRUE(res1);
  18684. ASSERT_EQ(200, res1->status);
  18685. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18686. // If-Modified-Since with invalid format should not result in 304
  18687. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18688. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18689. ASSERT_TRUE(res_bad);
  18690. EXPECT_EQ(200, res_bad->status);
  18691. // If-Range with invalid date format should be treated as mismatch -> full
  18692. // content (200)
  18693. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18694. {"If-Range", "invalid-date"}};
  18695. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18696. ASSERT_TRUE(res_ifrange);
  18697. EXPECT_EQ(200, res_ifrange->status);
  18698. svr.stop();
  18699. t.join();
  18700. std::remove(fname);
  18701. }
  18702. TEST(ETagTest, IfRangeWithMalformedETag) {
  18703. using namespace httplib;
  18704. const char *fname = "ifrange_malformed.txt";
  18705. const std::string content = "0123456789";
  18706. {
  18707. std::ofstream ofs(fname);
  18708. ofs << content;
  18709. ASSERT_TRUE(ofs.good());
  18710. }
  18711. Server svr;
  18712. svr.set_mount_point("/static", ".");
  18713. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18714. svr.wait_until_ready();
  18715. Client cli(HOST, PORT);
  18716. // First request: get ETag
  18717. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18718. ASSERT_TRUE(res1);
  18719. ASSERT_EQ(200, res1->status);
  18720. ASSERT_TRUE(res1->has_header("ETag"));
  18721. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18722. // full content (200)
  18723. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18724. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18725. ASSERT_TRUE(res2);
  18726. EXPECT_EQ(200, res2->status);
  18727. EXPECT_EQ(content, res2->body);
  18728. svr.stop();
  18729. t.join();
  18730. std::remove(fname);
  18731. }
  18732. TEST(ETagTest, ExtremeLargeDateValues) {
  18733. using namespace httplib;
  18734. const char *fname = "ims_extreme_date.txt";
  18735. const char *content = "ims-extreme-date";
  18736. {
  18737. std::ofstream ofs(fname);
  18738. ofs << content;
  18739. ASSERT_TRUE(ofs.good());
  18740. }
  18741. Server svr;
  18742. svr.set_mount_point("/static", ".");
  18743. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18744. svr.wait_until_ready();
  18745. Client cli(HOST, PORT);
  18746. auto res1 = cli.Get(std::string("/static/") + fname);
  18747. ASSERT_TRUE(res1);
  18748. ASSERT_EQ(200, res1->status);
  18749. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18750. // Extremely large year that may overflow date parsing routines.
  18751. Headers h_large_date = {
  18752. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18753. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18754. ASSERT_TRUE(res_bad);
  18755. // Expect server to treat this as invalid/mismatch and return full content
  18756. EXPECT_EQ(200, res_bad->status);
  18757. // If-Range with extremely large date should be treated as mismatch -> full
  18758. // content (200)
  18759. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18760. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18761. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18762. ASSERT_TRUE(res_ifrange);
  18763. EXPECT_EQ(200, res_ifrange->status);
  18764. svr.stop();
  18765. t.join();
  18766. std::remove(fname);
  18767. }
  18768. TEST(ETagTest, NegativeFileModificationTime) {
  18769. using namespace httplib;
  18770. const char *fname = "ims_negative_mtime.txt";
  18771. const std::string content = "negative-mtime";
  18772. {
  18773. std::ofstream ofs(fname);
  18774. ofs << content;
  18775. ASSERT_TRUE(ofs.good());
  18776. }
  18777. // Try to set file mtime to a negative value. This may fail on some
  18778. // platforms/filesystems; if it fails, the test will still verify server
  18779. // behaves safely by performing a regular conditional request.
  18780. #if defined(__APPLE__) || defined(__linux__)
  18781. bool set_negative = false;
  18782. do {
  18783. struct timeval times[2];
  18784. // access time: now
  18785. times[0].tv_sec = time(nullptr);
  18786. times[0].tv_usec = 0;
  18787. // modification time: negative (e.g., -1)
  18788. times[1].tv_sec = -1;
  18789. times[1].tv_usec = 0;
  18790. if (utimes(fname, times) == 0) { set_negative = true; }
  18791. } while (0);
  18792. #else
  18793. bool set_negative = false;
  18794. #endif
  18795. Server svr;
  18796. svr.set_mount_point("/static", ".");
  18797. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18798. svr.wait_until_ready();
  18799. Client cli(HOST, PORT);
  18800. auto res1 = cli.Get(std::string("/static/") + fname);
  18801. ASSERT_TRUE(res1);
  18802. ASSERT_EQ(200, res1->status);
  18803. bool has_last_modified = res1->has_header("Last-Modified");
  18804. std::string last_modified;
  18805. if (has_last_modified) {
  18806. last_modified = res1->get_header_value("Last-Modified");
  18807. }
  18808. if (set_negative) {
  18809. // If we successfully set a negative mtime, ensure server returns a
  18810. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18811. // with an old date and ensure server handles it without crash.
  18812. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18813. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18814. ASSERT_TRUE(res2);
  18815. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18816. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18817. } else {
  18818. // Could not set negative mtime on this platform; fall back to verifying
  18819. // that normal invalid/malformed dates are treated safely (non-304).
  18820. Headers h_bad_date = {
  18821. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18822. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18823. ASSERT_TRUE(res_bad);
  18824. EXPECT_EQ(200, res_bad->status);
  18825. }
  18826. svr.stop();
  18827. t.join();
  18828. std::remove(fname);
  18829. }
  18830. //==============================================================================
  18831. // Integration Tests with Server
  18832. //==============================================================================
  18833. class SSEIntegrationTest : public ::testing::Test {
  18834. protected:
  18835. void SetUp() override {
  18836. stop_server_.store(false);
  18837. events_.clear();
  18838. server_ = httplib::detail::make_unique<Server>();
  18839. setup_server();
  18840. start_server();
  18841. }
  18842. void TearDown() override {
  18843. stop_server_.store(true);
  18844. event_cv_.notify_all();
  18845. server_->stop();
  18846. if (server_thread_.joinable()) { server_thread_.join(); }
  18847. }
  18848. void setup_server() {
  18849. // Simple SSE endpoint
  18850. server_->Get("/events", [this](const Request &req, Response &res) {
  18851. auto last_id = req.get_header_value("Last-Event-ID");
  18852. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18853. res.set_chunked_content_provider(
  18854. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18855. std::unique_lock<std::mutex> lock(event_mutex_);
  18856. if (event_cv_.wait_for(
  18857. lock, std::chrono::milliseconds(200), [this] {
  18858. return !events_.empty() || stop_server_.load();
  18859. })) {
  18860. if (stop_server_.load()) { return false; }
  18861. if (!events_.empty()) {
  18862. std::string event = events_.front();
  18863. events_.erase(events_.begin());
  18864. sink.write(event.data(), event.size());
  18865. return true;
  18866. }
  18867. }
  18868. return !stop_server_.load();
  18869. });
  18870. });
  18871. // Endpoint that returns error
  18872. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18873. res.status = 500;
  18874. res.set_content("Internal Server Error", "text/plain");
  18875. });
  18876. // Endpoint for custom event types
  18877. server_->Get("/custom-events", [](const Request &, Response &res) {
  18878. res.set_chunked_content_provider(
  18879. "text/event-stream", [](size_t offset, DataSink &sink) {
  18880. if (offset == 0) {
  18881. std::string event = "event: update\ndata: updated\n\n"
  18882. "event: delete\ndata: deleted\n\n";
  18883. sink.write(event.data(), event.size());
  18884. }
  18885. return false; // End stream after sending
  18886. });
  18887. });
  18888. }
  18889. void start_server() {
  18890. port_ = server_->bind_to_any_port(HOST);
  18891. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18892. // Wait for server to start
  18893. while (!server_->is_running()) {
  18894. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18895. }
  18896. }
  18897. int get_port() const { return port_; }
  18898. void send_event(const std::string &event) {
  18899. std::lock_guard<std::mutex> lock(event_mutex_);
  18900. events_.push_back(event);
  18901. event_cv_.notify_all();
  18902. }
  18903. std::unique_ptr<Server> server_;
  18904. std::thread server_thread_;
  18905. std::mutex event_mutex_;
  18906. std::condition_variable event_cv_;
  18907. std::vector<std::string> events_;
  18908. std::atomic<bool> stop_server_{false};
  18909. std::string last_received_event_id_;
  18910. int port_ = 0;
  18911. };
  18912. //==============================================================================
  18913. // SSE Parsing Tests
  18914. //==============================================================================
  18915. class SSEParsingTest : public SSEIntegrationTest {
  18916. protected:
  18917. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  18918. // A trailing sentinel event tells when the whole stream has been parsed.
  18919. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  18920. auto body = stream + "event: end\ndata: end\n\n";
  18921. server_->Get("/parse", [body](const Request &, Response &res) {
  18922. res.set_content(body, "text/event-stream");
  18923. });
  18924. return collect("/parse");
  18925. }
  18926. // Runs SSEClient against path until an "end" event arrives and returns the
  18927. // messages dispatched before it
  18928. std::vector<sse::SSEMessage> collect(const std::string &path) {
  18929. Client client(HOST, get_port());
  18930. sse::SSEClient sse(client, path);
  18931. std::mutex mutex;
  18932. std::condition_variable cv;
  18933. std::vector<sse::SSEMessage> messages;
  18934. auto done = false;
  18935. sse.on_message([&](const sse::SSEMessage &msg) {
  18936. std::lock_guard<std::mutex> lock(mutex);
  18937. // Ignore a replay from a reconnect that races with stop()
  18938. if (!done) { messages.push_back(msg); }
  18939. });
  18940. sse.on_event("end", [&](const sse::SSEMessage &) {
  18941. std::lock_guard<std::mutex> lock(mutex);
  18942. done = true;
  18943. cv.notify_all();
  18944. });
  18945. sse.set_reconnect_interval(100);
  18946. sse.start_async();
  18947. {
  18948. std::unique_lock<std::mutex> lock(mutex);
  18949. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  18950. }
  18951. sse.stop();
  18952. EXPECT_TRUE(done);
  18953. return messages;
  18954. }
  18955. };
  18956. TEST_F(SSEParsingTest, SingleLineData) {
  18957. auto msgs = parse("data: hello\n\n");
  18958. ASSERT_EQ(msgs.size(), 1u);
  18959. EXPECT_EQ(msgs[0].data, "hello");
  18960. EXPECT_EQ(msgs[0].event, "message");
  18961. }
  18962. TEST_F(SSEParsingTest, MultiLineData) {
  18963. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  18964. ASSERT_EQ(msgs.size(), 1u);
  18965. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  18966. }
  18967. TEST_F(SSEParsingTest, CustomEventType) {
  18968. auto msgs = parse("event: update\ndata: payload\n\n");
  18969. ASSERT_EQ(msgs.size(), 1u);
  18970. EXPECT_EQ(msgs[0].event, "update");
  18971. EXPECT_EQ(msgs[0].data, "payload");
  18972. }
  18973. TEST_F(SSEParsingTest, EventIdHandling) {
  18974. auto msgs = parse("id: 12345\ndata: test\n\n");
  18975. ASSERT_EQ(msgs.size(), 1u);
  18976. EXPECT_EQ(msgs[0].id, "12345");
  18977. }
  18978. TEST_F(SSEParsingTest, EmptyEventId) {
  18979. auto msgs = parse("id:\ndata: test\n\n");
  18980. ASSERT_EQ(msgs.size(), 1u);
  18981. EXPECT_EQ(msgs[0].id, "");
  18982. }
  18983. TEST_F(SSEParsingTest, CommentsIgnored) {
  18984. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  18985. ASSERT_EQ(msgs.size(), 1u);
  18986. EXPECT_EQ(msgs[0].data, "hello");
  18987. EXPECT_EQ(msgs[0].event, "message");
  18988. }
  18989. TEST_F(SSEParsingTest, ColonInValue) {
  18990. auto msgs = parse("data: hello:world:test\n\n");
  18991. ASSERT_EQ(msgs.size(), 1u);
  18992. EXPECT_EQ(msgs[0].data, "hello:world:test");
  18993. }
  18994. TEST_F(SSEParsingTest, FieldNameOnly) {
  18995. // A line without a colon is a field name with an empty value
  18996. auto msgs = parse("data\n\n");
  18997. ASSERT_EQ(msgs.size(), 1u);
  18998. EXPECT_EQ(msgs[0].data, "");
  18999. }
  19000. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19001. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19002. ASSERT_EQ(msgs.size(), 1u);
  19003. EXPECT_EQ(msgs[0].event, "update");
  19004. EXPECT_EQ(msgs[0].data, "hello");
  19005. }
  19006. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19007. auto msgs = parse("data\r\n\r\n");
  19008. ASSERT_EQ(msgs.size(), 1u);
  19009. EXPECT_EQ(msgs[0].data, "");
  19010. }
  19011. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19012. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19013. ASSERT_EQ(msgs.size(), 1u);
  19014. EXPECT_EQ(msgs[0].data, "hello");
  19015. EXPECT_EQ(msgs[0].event, "message");
  19016. }
  19017. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19018. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19019. ASSERT_EQ(msgs.size(), 2u);
  19020. EXPECT_EQ(msgs[0].data, "hello");
  19021. EXPECT_EQ(msgs[1].data, "hello");
  19022. }
  19023. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19024. // An event without data is not dispatched, and its type must not leak
  19025. // into the next event
  19026. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19027. ASSERT_EQ(msgs.size(), 1u);
  19028. EXPECT_EQ(msgs[0].event, "message");
  19029. EXPECT_EQ(msgs[0].data, "hello");
  19030. }
  19031. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19032. // The first connection sends only an id; the second echoes back the
  19033. // Last-Event-ID it was reconnected with
  19034. std::atomic<int> connection_count{0};
  19035. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19036. if (connection_count++ == 0) {
  19037. res.set_content("id: 42\n\n", "text/event-stream");
  19038. } else {
  19039. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19040. "\n\nevent: end\ndata: end\n\n",
  19041. "text/event-stream");
  19042. }
  19043. });
  19044. auto msgs = collect("/id-only");
  19045. ASSERT_EQ(msgs.size(), 1u);
  19046. EXPECT_EQ(msgs[0].data, "42");
  19047. }
  19048. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19049. // The first connection sets an id and then clears it with an empty one; the
  19050. // second reports whether it was reconnected with a Last-Event-ID
  19051. std::atomic<int> connection_count{0};
  19052. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19053. if (connection_count++ == 0) {
  19054. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19055. "text/event-stream");
  19056. } else {
  19057. res.set_content(
  19058. std::string("data: ") +
  19059. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19060. "\n\nevent: end\ndata: end\n\n",
  19061. "text/event-stream");
  19062. }
  19063. });
  19064. auto msgs = collect("/id-clear");
  19065. ASSERT_EQ(msgs.size(), 3u);
  19066. EXPECT_EQ(msgs[0].id, "1");
  19067. EXPECT_EQ(msgs[1].id, "");
  19068. EXPECT_EQ(msgs[2].data, "not sent");
  19069. }
  19070. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19071. auto msgs = parse("event: notification\nid: evt-42\n"
  19072. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19073. ASSERT_EQ(msgs.size(), 1u);
  19074. EXPECT_EQ(msgs[0].event, "notification");
  19075. EXPECT_EQ(msgs[0].id, "evt-42");
  19076. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19077. }
  19078. TEST(SSEMessageTest, Clear) {
  19079. sse::SSEMessage msg;
  19080. msg.event = "custom";
  19081. msg.data = "some data";
  19082. msg.id = "123";
  19083. msg.clear();
  19084. EXPECT_EQ(msg.event, "message");
  19085. EXPECT_EQ(msg.data, "");
  19086. EXPECT_EQ(msg.id, "");
  19087. }
  19088. //==============================================================================
  19089. // SSE Integration Tests
  19090. //==============================================================================
  19091. // Test: Successful connection and on_open callback
  19092. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19093. // Add a simple endpoint that sends one event and closes
  19094. server_->Get("/simple-event", [](const Request &, Response &res) {
  19095. res.set_chunked_content_provider(
  19096. "text/event-stream", [](size_t offset, DataSink &sink) {
  19097. if (offset == 0) {
  19098. std::string event = "data: hello\n\n";
  19099. sink.write(event.data(), event.size());
  19100. }
  19101. return false; // Close stream after sending
  19102. });
  19103. });
  19104. Client client("localhost", get_port());
  19105. sse::SSEClient sse(client, "/simple-event");
  19106. std::atomic<bool> open_called{false};
  19107. std::atomic<bool> message_received{false};
  19108. sse.on_open([&open_called]() { open_called.store(true); });
  19109. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19110. if (msg.data == "hello") { message_received.store(true); }
  19111. });
  19112. sse.set_reconnect_interval(100);
  19113. sse.set_max_reconnect_attempts(1);
  19114. // Start async
  19115. sse.start_async();
  19116. // Wait for message to be processed
  19117. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19118. sse.stop();
  19119. EXPECT_TRUE(open_called.load());
  19120. EXPECT_TRUE(message_received.load());
  19121. }
  19122. // Test: on_message callback
  19123. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19124. // Endpoint that sends multiple events then closes
  19125. server_->Get("/multi-event", [](const Request &, Response &res) {
  19126. res.set_chunked_content_provider(
  19127. "text/event-stream", [](size_t offset, DataSink &sink) {
  19128. if (offset == 0) {
  19129. std::string events = "data: message1\n\ndata: message2\n\n";
  19130. sink.write(events.data(), events.size());
  19131. }
  19132. return false;
  19133. });
  19134. });
  19135. Client client("localhost", get_port());
  19136. sse::SSEClient sse(client, "/multi-event");
  19137. std::vector<std::string> received_messages;
  19138. std::mutex messages_mutex;
  19139. sse.on_message([&](const sse::SSEMessage &msg) {
  19140. std::lock_guard<std::mutex> lock(messages_mutex);
  19141. received_messages.push_back(msg.data);
  19142. });
  19143. sse.set_reconnect_interval(100);
  19144. sse.set_max_reconnect_attempts(1);
  19145. sse.start_async();
  19146. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19147. sse.stop();
  19148. std::lock_guard<std::mutex> lock(messages_mutex);
  19149. EXPECT_GE(received_messages.size(), 2u);
  19150. if (received_messages.size() >= 2) {
  19151. EXPECT_EQ(received_messages[0], "message1");
  19152. EXPECT_EQ(received_messages[1], "message2");
  19153. }
  19154. }
  19155. // Test: on_event for specific types
  19156. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19157. Client client("localhost", get_port());
  19158. sse::SSEClient sse(client, "/custom-events");
  19159. std::atomic<bool> update_received{false};
  19160. std::atomic<bool> delete_received{false};
  19161. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19162. if (msg.data == "updated") { update_received.store(true); }
  19163. });
  19164. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19165. if (msg.data == "deleted") { delete_received.store(true); }
  19166. });
  19167. sse.set_max_reconnect_attempts(1);
  19168. sse.start_async();
  19169. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19170. sse.stop();
  19171. EXPECT_TRUE(update_received.load());
  19172. EXPECT_TRUE(delete_received.load());
  19173. }
  19174. // Test: on_error callback on connection failure
  19175. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19176. // Connect to a non-existent port
  19177. Client client("localhost", 59999);
  19178. sse::SSEClient sse(client, "/events");
  19179. std::atomic<bool> error_called{false};
  19180. Error received_error = Error::Success;
  19181. sse.on_error([&](Error err) {
  19182. error_called.store(true);
  19183. received_error = err;
  19184. });
  19185. sse.set_reconnect_interval(50);
  19186. sse.set_max_reconnect_attempts(1);
  19187. sse.start_async();
  19188. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19189. sse.stop();
  19190. EXPECT_TRUE(error_called.load());
  19191. EXPECT_NE(received_error, Error::Success);
  19192. }
  19193. // Test: Last-Event-ID header sent on reconnect
  19194. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19195. // Endpoint that sends event with ID
  19196. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19197. res.set_chunked_content_provider(
  19198. "text/event-stream", [](size_t offset, DataSink &sink) {
  19199. if (offset == 0) {
  19200. std::string event = "id: evt-123\ndata: test\n\n";
  19201. sink.write(event.data(), event.size());
  19202. }
  19203. return false;
  19204. });
  19205. });
  19206. Client client("localhost", get_port());
  19207. sse::SSEClient sse(client, "/event-with-id");
  19208. std::atomic<bool> id_received{false};
  19209. sse.on_message([&](const sse::SSEMessage &msg) {
  19210. if (!msg.id.empty()) { id_received.store(true); }
  19211. });
  19212. sse.set_reconnect_interval(100);
  19213. sse.set_max_reconnect_attempts(1);
  19214. sse.start_async();
  19215. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19216. sse.stop();
  19217. EXPECT_TRUE(id_received.load());
  19218. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19219. }
  19220. // Test: Manual stop
  19221. TEST_F(SSEIntegrationTest, ManualStop) {
  19222. // Endpoint that sends one event and stays open briefly
  19223. std::atomic<bool> handler_running{true};
  19224. server_->Get("/stay-open", [&handler_running](const Request &,
  19225. Response &res) {
  19226. res.set_chunked_content_provider(
  19227. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19228. if (offset == 0) {
  19229. std::string event = "data: connected\n\n";
  19230. sink.write(event.data(), event.size());
  19231. }
  19232. // Keep connection open while handler_running is true
  19233. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19234. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19235. }
  19236. return false;
  19237. });
  19238. });
  19239. Client client("localhost", get_port());
  19240. sse::SSEClient sse(client, "/stay-open");
  19241. std::atomic<bool> connected{false};
  19242. sse.on_open([&connected]() { connected.store(true); });
  19243. sse.set_reconnect_interval(100);
  19244. sse.set_max_reconnect_attempts(1);
  19245. sse.start_async();
  19246. // Wait for connection to establish
  19247. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19248. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19249. }
  19250. EXPECT_TRUE(connected.load());
  19251. EXPECT_TRUE(sse.is_connected());
  19252. // Signal handler to stop
  19253. handler_running.store(false);
  19254. // Stop SSE client
  19255. sse.stop();
  19256. EXPECT_FALSE(sse.is_connected());
  19257. }
  19258. // Test: SSEClient with custom headers
  19259. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19260. // Setup a server endpoint that checks for custom header
  19261. std::atomic<bool> header_received{false};
  19262. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19263. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19264. header_received.store(true);
  19265. }
  19266. res.set_chunked_content_provider("text/event-stream",
  19267. [](size_t, DataSink &) { return false; });
  19268. });
  19269. Client client("localhost", get_port());
  19270. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19271. sse::SSEClient sse(client, "/header-check", headers);
  19272. sse.set_max_reconnect_attempts(1);
  19273. sse.start_async();
  19274. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19275. sse.stop();
  19276. EXPECT_TRUE(header_received.load());
  19277. }
  19278. // Test: Reconnect interval configuration
  19279. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19280. Client client("localhost", get_port());
  19281. sse::SSEClient sse(client, "/events");
  19282. auto &result = sse.set_reconnect_interval(500);
  19283. // Builder pattern should return reference to self
  19284. EXPECT_EQ(&result, &sse);
  19285. }
  19286. // Test: Max reconnect attempts
  19287. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19288. // Connect to non-existent port to force reconnects
  19289. Client client("localhost", 59998);
  19290. sse::SSEClient sse(client, "/events");
  19291. std::atomic<int> error_count{0};
  19292. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19293. sse.set_reconnect_interval(50);
  19294. sse.set_max_reconnect_attempts(2);
  19295. auto start = std::chrono::steady_clock::now();
  19296. sse.start(); // Blocking call
  19297. auto end = std::chrono::steady_clock::now();
  19298. // Should have stopped after 2 failed attempts
  19299. EXPECT_GE(error_count.load(), 2);
  19300. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19301. auto duration =
  19302. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19303. #ifdef _WIN32
  19304. // Windows is much slower for socket connection failures
  19305. EXPECT_LT(duration.count(), 7000);
  19306. #else
  19307. EXPECT_LT(duration.count(), 1000);
  19308. #endif
  19309. }
  19310. // Test: Multi-line data in integration
  19311. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19312. // Endpoint with multi-line data
  19313. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19314. res.set_chunked_content_provider(
  19315. "text/event-stream", [](size_t offset, DataSink &sink) {
  19316. if (offset == 0) {
  19317. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19318. sink.write(event.data(), event.size());
  19319. }
  19320. return false;
  19321. });
  19322. });
  19323. Client client("localhost", get_port());
  19324. sse::SSEClient sse(client, "/multiline-data");
  19325. std::string received_data;
  19326. std::mutex data_mutex;
  19327. sse.on_message([&](const sse::SSEMessage &msg) {
  19328. std::lock_guard<std::mutex> lock(data_mutex);
  19329. received_data = msg.data;
  19330. });
  19331. sse.set_reconnect_interval(100);
  19332. sse.set_max_reconnect_attempts(1);
  19333. sse.start_async();
  19334. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19335. sse.stop();
  19336. std::lock_guard<std::mutex> lock(data_mutex);
  19337. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19338. }
  19339. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19340. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19341. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19342. DataSink &sink) {
  19343. if (offset == 0) {
  19344. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19345. sink.write(events.data(), events.size());
  19346. }
  19347. return false;
  19348. });
  19349. });
  19350. Client client("localhost", get_port());
  19351. sse::SSEClient sse(client, "/empty-data-lines");
  19352. std::mutex mutex;
  19353. std::condition_variable cv;
  19354. std::vector<std::string> received;
  19355. sse.on_message([&](const sse::SSEMessage &msg) {
  19356. std::lock_guard<std::mutex> lock(mutex);
  19357. received.push_back(msg.data);
  19358. cv.notify_all();
  19359. });
  19360. sse.set_max_reconnect_attempts(1);
  19361. sse.start_async();
  19362. {
  19363. std::unique_lock<std::mutex> lock(mutex);
  19364. cv.wait_for(lock, std::chrono::seconds(2),
  19365. [&] { return received.size() >= 3; });
  19366. }
  19367. sse.stop();
  19368. ASSERT_GE(received.size(), 3u);
  19369. EXPECT_EQ(received[0], "");
  19370. EXPECT_EQ(received[1], "\nhello");
  19371. EXPECT_EQ(received[2], "");
  19372. }
  19373. // Test: Auto-reconnect after server disconnection
  19374. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19375. std::atomic<int> connection_count{0};
  19376. std::atomic<int> message_count{0};
  19377. // Endpoint that sends one event and closes, forcing reconnect
  19378. server_->Get("/reconnect-test",
  19379. [&connection_count](const Request &, Response &res) {
  19380. connection_count.fetch_add(1);
  19381. res.set_chunked_content_provider(
  19382. "text/event-stream", [](size_t offset, DataSink &sink) {
  19383. if (offset == 0) {
  19384. std::string event = "data: hello\n\n";
  19385. sink.write(event.data(), event.size());
  19386. }
  19387. return false; // Close connection after sending
  19388. });
  19389. });
  19390. Client client("localhost", get_port());
  19391. sse::SSEClient sse(client, "/reconnect-test");
  19392. sse.on_message([&message_count](const sse::SSEMessage &) {
  19393. message_count.fetch_add(1);
  19394. });
  19395. sse.set_reconnect_interval(100);
  19396. sse.set_max_reconnect_attempts(3);
  19397. sse.start_async();
  19398. // Wait long enough for multiple reconnects
  19399. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19400. sse.stop();
  19401. // Should have connected multiple times (initial + reconnects)
  19402. EXPECT_GE(connection_count.load(), 2);
  19403. // Should have received messages from multiple connections
  19404. EXPECT_GE(message_count.load(), 2);
  19405. }
  19406. // Test: A retry field that is not all ASCII digits is ignored
  19407. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19408. std::atomic<int> connection_count{0};
  19409. server_->Get("/bad-retry",
  19410. [&connection_count](const Request &, Response &res) {
  19411. connection_count.fetch_add(1);
  19412. res.set_chunked_content_provider(
  19413. "text/event-stream", [](size_t offset, DataSink &sink) {
  19414. if (offset == 0) {
  19415. std::string event = "retry: -1\ndata: hello\n\n";
  19416. sink.write(event.data(), event.size());
  19417. }
  19418. return false;
  19419. });
  19420. });
  19421. Client client("localhost", get_port());
  19422. sse::SSEClient sse(client, "/bad-retry");
  19423. sse.set_reconnect_interval(10000);
  19424. sse.start_async();
  19425. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19426. sse.stop();
  19427. EXPECT_EQ(connection_count.load(), 1);
  19428. }
  19429. // Test: A retry field of all ASCII digits sets the reconnection time
  19430. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19431. std::atomic<int> connection_count{0};
  19432. server_->Get("/zero-retry",
  19433. [&connection_count](const Request &, Response &res) {
  19434. connection_count.fetch_add(1);
  19435. res.set_chunked_content_provider(
  19436. "text/event-stream", [](size_t offset, DataSink &sink) {
  19437. if (offset == 0) {
  19438. std::string event = "retry: 0\ndata: hello\n\n";
  19439. sink.write(event.data(), event.size());
  19440. }
  19441. return false;
  19442. });
  19443. });
  19444. Client client("localhost", get_port());
  19445. sse::SSEClient sse(client, "/zero-retry");
  19446. sse.set_reconnect_interval(10000);
  19447. sse.start_async();
  19448. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19449. sse.stop();
  19450. // The server-supplied interval is applied, but never below 100ms, so
  19451. // "retry: 0" does not cause a busy reconnect loop
  19452. EXPECT_GE(connection_count.load(), 2);
  19453. EXPECT_LE(connection_count.load(), 10);
  19454. }
  19455. // Test: Last-Event-ID sent on reconnect
  19456. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19457. std::atomic<int> connection_count{0};
  19458. std::vector<std::string> received_last_event_ids;
  19459. std::mutex id_mutex;
  19460. // Endpoint that checks Last-Event-ID header and sends event with ID
  19461. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19462. int conn = connection_count.fetch_add(1);
  19463. // Capture the Last-Event-ID header from each connection
  19464. {
  19465. std::lock_guard<std::mutex> lock(id_mutex);
  19466. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19467. }
  19468. res.set_chunked_content_provider(
  19469. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19470. if (offset == 0) {
  19471. std::string event =
  19472. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19473. sink.write(event.data(), event.size());
  19474. }
  19475. return false;
  19476. });
  19477. });
  19478. Client client("localhost", get_port());
  19479. sse::SSEClient sse(client, "/reconnect-with-id");
  19480. sse.set_reconnect_interval(100);
  19481. sse.set_max_reconnect_attempts(3);
  19482. sse.start_async();
  19483. // Wait for at least 2 connections
  19484. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19485. sse.stop();
  19486. // Verify behavior
  19487. std::lock_guard<std::mutex> lock(id_mutex);
  19488. EXPECT_GE(received_last_event_ids.size(), 2u);
  19489. // First connection should have no Last-Event-ID
  19490. if (!received_last_event_ids.empty()) {
  19491. EXPECT_EQ(received_last_event_ids[0], "");
  19492. }
  19493. // Second connection should have Last-Event-ID from first connection
  19494. if (received_last_event_ids.size() >= 2) {
  19495. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19496. }
  19497. }
  19498. // Test: set_headers updates headers used on reconnect
  19499. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19500. std::vector<std::string> received_tokens;
  19501. std::mutex token_mutex;
  19502. // Endpoint that captures Authorization header
  19503. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19504. {
  19505. std::lock_guard<std::mutex> lock(token_mutex);
  19506. received_tokens.push_back(req.get_header_value("Authorization"));
  19507. }
  19508. res.set_chunked_content_provider(
  19509. "text/event-stream", [](size_t offset, DataSink &sink) {
  19510. if (offset == 0) {
  19511. std::string event = "data: hello\n\n";
  19512. sink.write(event.data(), event.size());
  19513. }
  19514. return false; // Close connection to trigger reconnect
  19515. });
  19516. });
  19517. Client client("localhost", get_port());
  19518. Headers headers = {{"Authorization", "Bearer old-token"}};
  19519. sse::SSEClient sse(client, "/auth-check", headers);
  19520. // Update headers on each successful connection
  19521. sse.on_open(
  19522. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19523. sse.set_reconnect_interval(100);
  19524. sse.set_max_reconnect_attempts(3);
  19525. sse.start_async();
  19526. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19527. sse.stop();
  19528. std::lock_guard<std::mutex> lock(token_mutex);
  19529. ASSERT_GE(received_tokens.size(), 2u);
  19530. // First connection uses original header
  19531. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19532. // Second connection uses updated header from set_headers
  19533. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  19534. }
  19535. // Test: 401 allows reconnection (so on_error can refresh headers)
  19536. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  19537. std::atomic<int> connection_count{0};
  19538. // Endpoint: returns 401 on first attempt, 200 on second
  19539. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  19540. int conn = connection_count.fetch_add(1);
  19541. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19542. res.status = StatusCode::Unauthorized_401;
  19543. res.set_content("Unauthorized", "text/plain");
  19544. return;
  19545. }
  19546. res.set_chunked_content_provider(
  19547. "text/event-stream", [](size_t offset, DataSink &sink) {
  19548. if (offset == 0) {
  19549. std::string event = "data: authenticated\n\n";
  19550. sink.write(event.data(), event.size());
  19551. }
  19552. return false;
  19553. });
  19554. });
  19555. Client client("localhost", get_port());
  19556. Headers headers = {{"Authorization", "Bearer expired"}};
  19557. sse::SSEClient sse(client, "/auth-retry", headers);
  19558. std::atomic<bool> message_received{false};
  19559. // Refresh token on error
  19560. sse.on_error(
  19561. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19562. sse.on_message([&](const sse::SSEMessage &msg) {
  19563. if (msg.data == "authenticated") { message_received.store(true); }
  19564. });
  19565. sse.set_reconnect_interval(100);
  19566. sse.set_max_reconnect_attempts(3);
  19567. sse.start_async();
  19568. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19569. sse.stop();
  19570. // Should have reconnected after 401 and succeeded with new token
  19571. EXPECT_GE(connection_count.load(), 2);
  19572. EXPECT_TRUE(message_received.load());
  19573. }
  19574. TEST(Issue2318Test, EmptyHostString) {
  19575. {
  19576. httplib::Client cli_empty("", PORT);
  19577. auto res = cli_empty.Get("/");
  19578. ASSERT_FALSE(res);
  19579. EXPECT_EQ(httplib::Error::Connection, res.error());
  19580. }
  19581. {
  19582. httplib::Client cli(" ", PORT);
  19583. auto res = cli.Get("/");
  19584. ASSERT_FALSE(res);
  19585. EXPECT_EQ(httplib::Error::Connection, res.error());
  19586. }
  19587. }
  19588. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19589. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19590. Server svr;
  19591. // Set a small payload limit (1KB)
  19592. svr.set_payload_max_length(1024);
  19593. svr.Post("/test", [&](const Request &req, Response &res) {
  19594. res.set_content("Body size: " + std::to_string(req.body.size()),
  19595. "text/plain");
  19596. });
  19597. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19598. auto se = detail::scope_exit([&] {
  19599. svr.stop();
  19600. listen_thread.join();
  19601. });
  19602. svr.wait_until_ready();
  19603. // Create data that compresses well but exceeds limit when decompressed
  19604. // 8KB of repeated null bytes compresses to a very small size
  19605. std::string original_data(8 * 1024, '\0');
  19606. // Compress the data using gzip
  19607. std::string compressed_data;
  19608. detail::gzip_compressor compressor;
  19609. compressor.compress(original_data.data(), original_data.size(), true,
  19610. [&](const char *data, size_t size) {
  19611. compressed_data.append(data, size);
  19612. return true;
  19613. });
  19614. // Verify compression worked (compressed should be much smaller)
  19615. ASSERT_LT(compressed_data.size(), original_data.size());
  19616. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19617. // Send compressed data with Content-Encoding: gzip
  19618. Client cli(HOST, PORT);
  19619. Headers headers = {{"Content-Encoding", "gzip"}};
  19620. auto res =
  19621. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19622. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19624. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19625. }
  19626. #endif
  19627. // ============================================================================
  19628. // OpenSSL-Specific Tests
  19629. // ============================================================================
  19630. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19631. X509 *readCertificate(const std::string &strFileName) {
  19632. std::ifstream inStream(strFileName);
  19633. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19634. std::istreambuf_iterator<char>());
  19635. if (strCertPEM.empty()) return (nullptr);
  19636. BIO *pbCert = BIO_new(BIO_s_mem());
  19637. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19638. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19639. BIO_free(pbCert);
  19640. return (pCert);
  19641. }
  19642. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19643. std::ifstream inStream(strFileName);
  19644. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19645. std::istreambuf_iterator<char>());
  19646. if (strPrivateKeyPEM.empty()) return (nullptr);
  19647. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19648. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19649. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19650. BIO_free(pbPrivKey);
  19651. return (pPrivateKey);
  19652. }
  19653. TEST(BindServerTest, UpdateCerts) {
  19654. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19655. int port = svr.bind_to_any_port("0.0.0.0");
  19656. ASSERT_TRUE(svr.is_valid());
  19657. ASSERT_TRUE(port > 0);
  19658. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19659. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19660. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19661. ASSERT_TRUE(cert != nullptr);
  19662. ASSERT_TRUE(ca_cert != nullptr);
  19663. ASSERT_TRUE(key != nullptr);
  19664. X509_STORE *cert_store = X509_STORE_new();
  19665. X509_STORE_add_cert(cert_store, ca_cert);
  19666. // svr.update_certs(cert, key, cert_store); // deprecated
  19667. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19668. CLIENT_CA_CERT_FILE);
  19669. ASSERT_TRUE(svr.is_valid());
  19670. svr.stop();
  19671. X509_STORE_free(cert_store);
  19672. X509_free(cert);
  19673. X509_free(ca_cert);
  19674. EVP_PKEY_free(key);
  19675. }
  19676. // Test that update_certs() updates client CA list correctly
  19677. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19678. // Start with file-based constructor
  19679. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19680. ASSERT_TRUE(svr.is_valid());
  19681. // Initially no client CA list should be set
  19682. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19683. ASSERT_TRUE(ssl_ctx != nullptr);
  19684. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19685. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19686. EXPECT_EQ(0, count_before);
  19687. // Now update with client CA (PEM string)
  19688. std::string cert_pem, key_pem, ca_pem;
  19689. read_file(SERVER_CERT_FILE, cert_pem);
  19690. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19691. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19692. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19693. ASSERT_TRUE(svr.is_valid());
  19694. // Now client CA list should be set
  19695. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19696. ASSERT_TRUE(ca_list_after != nullptr);
  19697. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19698. }
  19699. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19700. // Test that the file-path SSLServer constructor properly sets the client CA
  19701. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19702. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19703. ASSERT_TRUE(svr.is_valid());
  19704. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19705. ASSERT_TRUE(ssl_ctx != nullptr);
  19706. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19707. ASSERT_TRUE(ca_list != nullptr);
  19708. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19709. }
  19710. #endif
  19711. // ============================================================================
  19712. // MbedTLS-Specific Tests
  19713. // ============================================================================
  19714. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19715. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19716. using namespace httplib::tls;
  19717. // Track if callback was invoked
  19718. bool callback_invoked = false;
  19719. // The callback receives void* ctx which is actually MbedTlsContext*
  19720. // We can access the mbedtls_ssl_config via the context
  19721. auto setup_callback = [&callback_invoked](void *ctx) {
  19722. callback_invoked = true;
  19723. // Cast to MbedTlsContext* to access the ssl config
  19724. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19725. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19726. // Use static variables to hold certificate data (simplified for test)
  19727. static mbedtls_x509_crt own_cert;
  19728. static mbedtls_pk_context own_key;
  19729. static mbedtls_x509_crt ca_chain;
  19730. static bool initialized = false;
  19731. if (!initialized) {
  19732. mbedtls_x509_crt_init(&own_cert);
  19733. mbedtls_pk_init(&own_key);
  19734. mbedtls_x509_crt_init(&ca_chain);
  19735. // Load server certificate
  19736. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19737. return false;
  19738. }
  19739. // Load server private key.
  19740. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19741. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19742. #if MBEDTLS_VERSION_MAJOR == 3
  19743. ,
  19744. mbedtls_ctr_drbg_random, nullptr
  19745. #endif
  19746. ) != 0) {
  19747. return false;
  19748. }
  19749. // Load CA chain for client verification
  19750. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19751. return false;
  19752. }
  19753. initialized = true;
  19754. }
  19755. // Configure the SSL config
  19756. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19757. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19758. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19759. // Set minimum TLS version using mbedTLS native API
  19760. #if MBEDTLS_VERSION_MAJOR >= 3
  19761. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19762. #else
  19763. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19764. MBEDTLS_SSL_MINOR_VERSION_3);
  19765. #endif
  19766. return true;
  19767. };
  19768. SSLServer svr(setup_callback);
  19769. ASSERT_TRUE(svr.is_valid());
  19770. ASSERT_TRUE(callback_invoked);
  19771. svr.Get("/test", [&](const Request &req, Response &res) {
  19772. res.set_content("test", "text/plain");
  19773. auto cert = req.peer_cert();
  19774. ASSERT_TRUE(static_cast<bool>(cert));
  19775. auto common_name = cert.subject_cn();
  19776. EXPECT_EQ("Common Name", common_name);
  19777. });
  19778. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19779. auto se = detail::scope_exit([&] {
  19780. svr.stop();
  19781. t.join();
  19782. ASSERT_FALSE(svr.is_running());
  19783. });
  19784. svr.wait_until_ready();
  19785. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19786. cli.enable_server_certificate_verification(false);
  19787. cli.set_connection_timeout(30);
  19788. auto res = cli.Get("/test");
  19789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19790. ASSERT_EQ(StatusCode::OK_200, res->status);
  19791. }
  19792. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19793. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19794. // keep-alive SSL session, which reads through that config in
  19795. // mbedtls_ssl_close_notify.
  19796. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19797. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19798. ASSERT_TRUE(svr.is_valid());
  19799. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19800. res.set_content("test", "text/plain");
  19801. });
  19802. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19803. auto se = detail::scope_exit([&] {
  19804. svr.stop();
  19805. t.join();
  19806. ASSERT_FALSE(svr.is_running());
  19807. });
  19808. svr.wait_until_ready();
  19809. {
  19810. SSLClient cli(HOST, PORT);
  19811. cli.enable_server_certificate_verification(false);
  19812. cli.set_keep_alive(true);
  19813. auto res = cli.Get("/test");
  19814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19815. ASSERT_EQ(StatusCode::OK_200, res->status);
  19816. // cli is destructed here with the keep-alive SSL session still open.
  19817. }
  19818. }
  19819. #endif
  19820. // WebSocket Tests
  19821. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19822. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19823. // defining the meaning of these bits has been negotiated.
  19824. auto make_frame = [](uint8_t first_byte) {
  19825. std::string frame;
  19826. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19827. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19828. frame += "Hello";
  19829. return frame;
  19830. };
  19831. // RSV1 set (0x40)
  19832. {
  19833. detail::BufferStream strm;
  19834. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19835. ws::Opcode opcode;
  19836. std::string payload;
  19837. bool fin;
  19838. EXPECT_EQ(
  19839. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19840. ws::impl::FrameRead::Fail);
  19841. }
  19842. // RSV2 set (0x20)
  19843. {
  19844. detail::BufferStream strm;
  19845. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19846. ws::Opcode opcode;
  19847. std::string payload;
  19848. bool fin;
  19849. EXPECT_EQ(
  19850. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19851. ws::impl::FrameRead::Fail);
  19852. }
  19853. // RSV3 set (0x10)
  19854. {
  19855. detail::BufferStream strm;
  19856. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19857. ws::Opcode opcode;
  19858. std::string payload;
  19859. bool fin;
  19860. EXPECT_EQ(
  19861. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19862. ws::impl::FrameRead::Fail);
  19863. }
  19864. // No RSV bits set - should succeed
  19865. {
  19866. detail::BufferStream strm;
  19867. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19868. ws::Opcode opcode;
  19869. std::string payload;
  19870. bool fin;
  19871. EXPECT_EQ(
  19872. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19873. ws::impl::FrameRead::Ok);
  19874. EXPECT_EQ(ws::Opcode::Text, opcode);
  19875. EXPECT_EQ("Hello", payload);
  19876. EXPECT_TRUE(fin);
  19877. }
  19878. }
  19879. TEST(WebSocketTest, ControlFrameValidation) {
  19880. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19881. // payload length <= 125.
  19882. // Ping with FIN=0 - must be rejected
  19883. {
  19884. detail::BufferStream strm;
  19885. std::string frame;
  19886. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19887. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19888. strm.write(frame.data(), frame.size());
  19889. ws::Opcode opcode;
  19890. std::string payload;
  19891. bool fin;
  19892. EXPECT_EQ(
  19893. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19894. ws::impl::FrameRead::Fail);
  19895. }
  19896. // Close with FIN=0 - must be rejected
  19897. {
  19898. detail::BufferStream strm;
  19899. std::string frame;
  19900. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19901. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19902. strm.write(frame.data(), frame.size());
  19903. ws::Opcode opcode;
  19904. std::string payload;
  19905. bool fin;
  19906. EXPECT_EQ(
  19907. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19908. ws::impl::FrameRead::Fail);
  19909. }
  19910. // Ping with payload_len=126 (extended length) - must be rejected
  19911. {
  19912. detail::BufferStream strm;
  19913. std::string frame;
  19914. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19915. frame += static_cast<char>(126); // payload_len=126 (>125)
  19916. frame += static_cast<char>(0x00); // extended length high byte
  19917. frame += static_cast<char>(126); // extended length low byte
  19918. frame += std::string(126, 'x');
  19919. strm.write(frame.data(), frame.size());
  19920. ws::Opcode opcode;
  19921. std::string payload;
  19922. bool fin;
  19923. EXPECT_EQ(
  19924. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19925. ws::impl::FrameRead::Fail);
  19926. }
  19927. // Ping with FIN=1 and payload_len=125 - should succeed
  19928. {
  19929. detail::BufferStream strm;
  19930. std::string frame;
  19931. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19932. frame += static_cast<char>(125); // payload_len=125
  19933. frame += std::string(125, 'x');
  19934. strm.write(frame.data(), frame.size());
  19935. ws::Opcode opcode;
  19936. std::string payload;
  19937. bool fin;
  19938. EXPECT_EQ(
  19939. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19940. ws::impl::FrameRead::Ok);
  19941. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19942. EXPECT_EQ(125u, payload.size());
  19943. EXPECT_TRUE(fin);
  19944. }
  19945. }
  19946. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19947. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19948. // length MUST be 0.
  19949. // MSB set - must be rejected
  19950. {
  19951. detail::BufferStream strm;
  19952. std::string frame;
  19953. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19954. frame += static_cast<char>(127); // 64-bit extended length
  19955. frame += static_cast<char>(0x80); // MSB set (invalid)
  19956. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19957. strm.write(frame.data(), frame.size());
  19958. ws::Opcode opcode;
  19959. std::string payload;
  19960. bool fin;
  19961. EXPECT_EQ(
  19962. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19963. ws::impl::FrameRead::Fail);
  19964. }
  19965. // MSB clear - should pass length parsing (will be rejected by max_len,
  19966. // but that's a different check; use a small length to verify)
  19967. {
  19968. detail::BufferStream strm;
  19969. std::string frame;
  19970. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19971. frame += static_cast<char>(127); // 64-bit extended length
  19972. frame += std::string(7, '\0'); // high bytes = 0
  19973. frame += static_cast<char>(0x03); // length = 3
  19974. frame += "abc";
  19975. strm.write(frame.data(), frame.size());
  19976. ws::Opcode opcode;
  19977. std::string payload;
  19978. bool fin;
  19979. EXPECT_EQ(
  19980. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19981. ws::impl::FrameRead::Ok);
  19982. EXPECT_EQ(ws::Opcode::Text, opcode);
  19983. EXPECT_EQ("abc", payload);
  19984. }
  19985. }
  19986. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19987. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19988. // Valid UTF-8
  19989. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19990. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19991. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19992. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19993. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19994. // Invalid UTF-8
  19995. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19996. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19997. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19998. EXPECT_FALSE(
  19999. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20000. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20001. }
  20002. TEST(WebSocketTest, ConnectAndDisconnect) {
  20003. Server svr;
  20004. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20005. std::string msg;
  20006. while (ws.read(msg)) {}
  20007. });
  20008. auto port = svr.bind_to_any_port(HOST);
  20009. std::thread t([&]() { svr.listen_after_bind(); });
  20010. svr.wait_until_ready();
  20011. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20012. auto res = client.connect();
  20013. ASSERT_TRUE(res);
  20014. EXPECT_EQ(Error::Success, res.error());
  20015. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20016. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20017. EXPECT_TRUE(client.is_open());
  20018. client.close();
  20019. EXPECT_FALSE(client.is_open());
  20020. svr.stop();
  20021. t.join();
  20022. }
  20023. TEST(WebSocketTest, ValidURL) {
  20024. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20025. EXPECT_TRUE(ws1.is_valid());
  20026. ws::WebSocketClient ws2("ws://example.com/path");
  20027. EXPECT_TRUE(ws2.is_valid());
  20028. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20029. EXPECT_TRUE(ws3.is_valid());
  20030. #ifdef CPPHTTPLIB_SSL_ENABLED
  20031. ws::WebSocketClient wss1("wss://example.com/path");
  20032. EXPECT_TRUE(wss1.is_valid());
  20033. ws::WebSocketClient wss2("wss://example.com:443/path");
  20034. EXPECT_TRUE(wss2.is_valid());
  20035. #endif
  20036. }
  20037. TEST(WebSocketTest, InvalidURL) {
  20038. // No scheme
  20039. ws::WebSocketClient ws1("localhost:8080/path");
  20040. EXPECT_FALSE(ws1.is_valid());
  20041. // No path
  20042. ws::WebSocketClient ws2("ws://localhost:8080");
  20043. EXPECT_FALSE(ws2.is_valid());
  20044. // Empty string
  20045. ws::WebSocketClient ws3("");
  20046. EXPECT_FALSE(ws3.is_valid());
  20047. // Missing host
  20048. ws::WebSocketClient ws4("ws://:8080/path");
  20049. EXPECT_FALSE(ws4.is_valid());
  20050. // Port number overflow — should not crash
  20051. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20052. EXPECT_FALSE(ws5.is_valid());
  20053. // Port out of range
  20054. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20055. EXPECT_FALSE(ws6.is_valid());
  20056. }
  20057. TEST(WebSocketTest, UnsupportedScheme) {
  20058. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20059. ws::WebSocketClient ws1("http://localhost:8080/path");
  20060. EXPECT_FALSE(ws1.is_valid());
  20061. ws::WebSocketClient ws2("https://localhost:8080/path");
  20062. EXPECT_FALSE(ws2.is_valid());
  20063. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20064. EXPECT_FALSE(ws3.is_valid());
  20065. #else
  20066. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20067. std::invalid_argument);
  20068. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20069. std::invalid_argument);
  20070. #endif
  20071. }
  20072. TEST(WebSocketTest, ConnectWhenInvalid) {
  20073. ws::WebSocketClient ws("not a valid url");
  20074. EXPECT_FALSE(ws.is_valid());
  20075. auto res = ws.connect();
  20076. EXPECT_FALSE(res);
  20077. EXPECT_EQ(Error::Connection, res.error());
  20078. EXPECT_EQ(-1, res.status());
  20079. }
  20080. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20081. // Grab a port that is free, then close it again so nothing listens there
  20082. Server svr;
  20083. auto port = svr.bind_to_any_port(HOST);
  20084. svr.stop();
  20085. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20086. auto res = client.connect();
  20087. ASSERT_FALSE(res);
  20088. EXPECT_EQ(Error::Connection, res.error());
  20089. EXPECT_EQ(-1, res.status());
  20090. }
  20091. TEST(WebSocketTest, DefaultPort) {
  20092. ws::WebSocketClient ws1("ws://example.com/path");
  20093. EXPECT_TRUE(ws1.is_valid());
  20094. // ws:// defaults to port 80 (verified by successful parse)
  20095. #ifdef CPPHTTPLIB_SSL_ENABLED
  20096. ws::WebSocketClient ws2("wss://example.com/path");
  20097. EXPECT_TRUE(ws2.is_valid());
  20098. // wss:// defaults to port 443 (verified by successful parse)
  20099. #endif
  20100. }
  20101. TEST(WebSocketTest, IPv6LiteralAddress) {
  20102. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20103. EXPECT_TRUE(ws1.is_valid());
  20104. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20105. EXPECT_TRUE(ws2.is_valid());
  20106. }
  20107. TEST(WebSocketTest, ComplexPath) {
  20108. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20109. EXPECT_TRUE(ws1.is_valid());
  20110. ws::WebSocketClient ws2("ws://localhost:8080/");
  20111. EXPECT_TRUE(ws2.is_valid());
  20112. }
  20113. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20114. Server svr;
  20115. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20116. std::string msg;
  20117. while (ws.read(msg)) {}
  20118. });
  20119. auto port = svr.bind_to_any_port(HOST);
  20120. std::thread t([&]() { svr.listen_after_bind(); });
  20121. svr.wait_until_ready();
  20122. auto another_host = "example.com";
  20123. auto wrong_ip = "192.0.2.1";
  20124. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20125. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20126. ASSERT_TRUE(client.connect());
  20127. EXPECT_TRUE(client.is_open());
  20128. client.close();
  20129. svr.stop();
  20130. t.join();
  20131. }
  20132. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20133. Server svr;
  20134. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20135. std::string msg;
  20136. while (ws.read(msg)) {}
  20137. });
  20138. auto port = svr.bind_to_any_port(HOST);
  20139. std::thread t([&]() { svr.listen_after_bind(); });
  20140. svr.wait_until_ready();
  20141. auto wrong_ip = "192.0.2.1";
  20142. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20143. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20144. client.set_connection_timeout(1);
  20145. client.set_read_timeout(1);
  20146. client.set_write_timeout(1);
  20147. EXPECT_FALSE(client.connect());
  20148. EXPECT_FALSE(client.is_open());
  20149. svr.stop();
  20150. t.join();
  20151. }
  20152. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20153. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20154. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20155. // (RFC 6761) is only a map key and the Host header value.
  20156. auto host = "target.invalid";
  20157. Server svr;
  20158. std::string received_host;
  20159. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20160. received_host = req.get_header_value("Host");
  20161. std::string msg;
  20162. while (ws.read(msg)) {}
  20163. });
  20164. auto port = svr.bind_to_any_port(HOST);
  20165. std::thread t([&]() { svr.listen_after_bind(); });
  20166. // ASSERT_* below returns from the test body, which would leave t joinable
  20167. // and make ~thread call std::terminate.
  20168. auto se = detail::scope_exit([&] {
  20169. svr.stop();
  20170. if (t.joinable()) { t.join(); }
  20171. });
  20172. svr.wait_until_ready();
  20173. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20174. std::to_string(port) + "/ws");
  20175. client.set_hostname_addr_map({{host, HOST}});
  20176. ASSERT_TRUE(client.connect());
  20177. EXPECT_TRUE(client.is_open());
  20178. client.close();
  20179. svr.stop();
  20180. t.join();
  20181. // The mapping only redirects the connection; the identity stays host_.
  20182. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20183. }
  20184. class WebSocketIntegrationTest : public ::testing::Test {
  20185. protected:
  20186. void SetUp() override {
  20187. server_ = httplib::detail::make_unique<Server>();
  20188. setup_server();
  20189. start_server();
  20190. }
  20191. void TearDown() override {
  20192. server_->stop();
  20193. if (server_thread_.joinable()) { server_thread_.join(); }
  20194. }
  20195. void setup_server() {
  20196. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20197. std::string msg;
  20198. ws::ReadResult ret;
  20199. while ((ret = ws.read(msg))) {
  20200. if (ret == ws::Binary) {
  20201. ws.send(msg.data(), msg.size());
  20202. } else {
  20203. ws.send(msg);
  20204. }
  20205. }
  20206. });
  20207. server_->WebSocket("/ws-echo-string",
  20208. [](const Request &, ws::WebSocket &ws) {
  20209. std::string msg;
  20210. while (ws.read(msg)) {
  20211. ws.send("echo: " + msg);
  20212. }
  20213. });
  20214. server_->WebSocket(
  20215. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20216. // Echo back request metadata
  20217. ws.send("path:" + req.path);
  20218. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20219. std::string msg;
  20220. while (ws.read(msg)) {}
  20221. });
  20222. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20223. std::string msg;
  20224. ws.read(msg); // wait for a message
  20225. ws.close();
  20226. });
  20227. server_->WebSocket("/ws-close-status",
  20228. [](const Request &, ws::WebSocket &ws) {
  20229. std::string msg;
  20230. ws.read(msg); // wait for a message
  20231. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20232. });
  20233. server_->WebSocket(
  20234. "/ws-subprotocol",
  20235. [](const Request &, ws::WebSocket &ws) {
  20236. std::string msg;
  20237. while (ws.read(msg)) {
  20238. ws.send(msg);
  20239. }
  20240. },
  20241. [](const std::vector<std::string> &protocols) -> std::string {
  20242. for (const auto &p : protocols) {
  20243. if (p == "graphql-ws") { return p; }
  20244. }
  20245. return "";
  20246. });
  20247. server_->WebSocket(
  20248. "/ws-subprotocol-unoffered",
  20249. [](const Request &, ws::WebSocket &ws) {
  20250. std::string msg;
  20251. while (ws.read(msg)) {
  20252. ws.send(msg);
  20253. }
  20254. },
  20255. [](const std::vector<std::string> &) -> std::string {
  20256. return "admin";
  20257. });
  20258. }
  20259. void start_server() {
  20260. port_ = server_->bind_to_any_port(HOST);
  20261. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20262. server_->wait_until_ready();
  20263. }
  20264. std::unique_ptr<Server> server_;
  20265. std::thread server_thread_;
  20266. int port_ = 0;
  20267. };
  20268. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20269. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20270. "/ws-echo");
  20271. ASSERT_TRUE(client.connect());
  20272. ASSERT_TRUE(client.is_open());
  20273. ASSERT_TRUE(client.send("Hello WebSocket"));
  20274. std::string msg;
  20275. EXPECT_EQ(ws::Text, client.read(msg));
  20276. EXPECT_EQ("Hello WebSocket", msg);
  20277. client.close();
  20278. }
  20279. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20280. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20281. "/ws-echo");
  20282. ASSERT_TRUE(client.connect());
  20283. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20284. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20285. std::string msg;
  20286. EXPECT_EQ(ws::Binary, client.read(msg));
  20287. EXPECT_EQ(binary_data, msg);
  20288. client.close();
  20289. }
  20290. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20291. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20292. "/ws-echo");
  20293. ASSERT_TRUE(client.connect());
  20294. for (int i = 0; i < 10; i++) {
  20295. auto text = "message " + std::to_string(i);
  20296. ASSERT_TRUE(client.send(text));
  20297. std::string msg;
  20298. ASSERT_TRUE(client.read(msg));
  20299. EXPECT_EQ(text, msg);
  20300. }
  20301. client.close();
  20302. }
  20303. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20304. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20305. "/ws-close");
  20306. ASSERT_TRUE(client.connect());
  20307. // Send a message to trigger the server to close
  20308. ASSERT_TRUE(client.send("trigger close"));
  20309. // The server will close, so read should return false
  20310. std::string msg;
  20311. EXPECT_FALSE(client.read(msg));
  20312. EXPECT_FALSE(client.is_open());
  20313. }
  20314. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20315. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20316. "/ws-echo");
  20317. ASSERT_TRUE(client.connect());
  20318. // 128KB message
  20319. std::string large_data(128 * 1024, 'X');
  20320. ASSERT_TRUE(client.send(large_data));
  20321. std::string msg;
  20322. ASSERT_TRUE(client.read(msg));
  20323. EXPECT_EQ(large_data, msg);
  20324. client.close();
  20325. }
  20326. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20327. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20328. "/ws-echo");
  20329. ASSERT_TRUE(client.connect());
  20330. const int num_threads = 4;
  20331. std::vector<std::thread> threads;
  20332. std::atomic<int> send_count{0};
  20333. for (int t = 0; t < num_threads; t++) {
  20334. threads.emplace_back([&client, &send_count, t]() {
  20335. for (int i = 0; i < 5; i++) {
  20336. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20337. if (client.send(text)) { send_count++; }
  20338. }
  20339. });
  20340. }
  20341. for (auto &th : threads) {
  20342. th.join();
  20343. }
  20344. int received = 0;
  20345. std::string msg;
  20346. while (received < send_count.load()) {
  20347. if (!client.read(msg)) { break; }
  20348. received++;
  20349. }
  20350. EXPECT_EQ(send_count.load(), received);
  20351. client.close();
  20352. }
  20353. TEST_F(WebSocketIntegrationTest, ReadString) {
  20354. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20355. "/ws-echo-string");
  20356. ASSERT_TRUE(client.connect());
  20357. ASSERT_TRUE(client.send("hello"));
  20358. std::string msg;
  20359. ASSERT_TRUE(client.read(msg));
  20360. EXPECT_EQ("echo: hello", msg);
  20361. ASSERT_TRUE(client.send("world"));
  20362. ASSERT_TRUE(client.read(msg));
  20363. EXPECT_EQ("echo: world", msg);
  20364. client.close();
  20365. }
  20366. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20367. Headers headers = {{"X-Test-Header", "test-value"}};
  20368. ws::WebSocketClient client(
  20369. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20370. ASSERT_TRUE(client.connect());
  20371. std::string msg;
  20372. ASSERT_TRUE(client.read(msg));
  20373. EXPECT_EQ("path:/ws-request-info", msg);
  20374. ASSERT_TRUE(client.read(msg));
  20375. EXPECT_EQ("header:test-value", msg);
  20376. client.close();
  20377. }
  20378. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20379. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20380. "/ws-echo");
  20381. client.set_read_timeout(1, 0); // 1 second
  20382. ASSERT_TRUE(client.connect());
  20383. // Don't send anything — server echo handler waits for a message, so read()
  20384. // should time out. The connection survives it: nothing was consumed.
  20385. std::string msg;
  20386. EXPECT_EQ(client.read(msg), ws::Timeout);
  20387. EXPECT_TRUE(client.is_open());
  20388. // And it is still usable afterwards.
  20389. EXPECT_TRUE(client.send("after timeout"));
  20390. EXPECT_EQ(client.read(msg), ws::Text);
  20391. EXPECT_EQ(msg, "after timeout");
  20392. }
  20393. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20394. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20395. "/ws-echo");
  20396. client.set_read_timeout(1, 0);
  20397. ASSERT_TRUE(client.connect());
  20398. ASSERT_TRUE(client.send("first"));
  20399. std::string msg;
  20400. ASSERT_EQ(client.read(msg), ws::Text);
  20401. ASSERT_EQ(msg, "first");
  20402. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20403. // not be used with a read timeout: it would reprocess the previous message.
  20404. EXPECT_EQ(client.read(msg), ws::Timeout);
  20405. EXPECT_EQ(msg, "first");
  20406. }
  20407. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20408. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20409. "/ws-echo");
  20410. ASSERT_TRUE(client.connect());
  20411. // Setting it once the connection is open reaches the live stream, not just
  20412. // the seed for the next connect().
  20413. client.set_read_timeout(1, 0);
  20414. std::string msg;
  20415. EXPECT_EQ(client.read(msg), ws::Timeout);
  20416. EXPECT_TRUE(client.is_open());
  20417. }
  20418. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20419. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20420. "/ws-echo");
  20421. client.set_read_timeout(5, 0);
  20422. ASSERT_TRUE(client.connect());
  20423. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20424. // The server should reject it and close the connection.
  20425. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20426. client.send(oversized);
  20427. // The server's read() should have failed due to payload limit,
  20428. // so our read() should return false (connection closed).
  20429. std::string msg;
  20430. EXPECT_FALSE(client.read(msg));
  20431. }
  20432. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20433. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20434. "/ws-echo");
  20435. client.set_read_timeout(10, 0);
  20436. ASSERT_TRUE(client.connect());
  20437. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20438. // This should succeed.
  20439. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20440. ASSERT_TRUE(client.send(at_limit));
  20441. std::string msg;
  20442. ASSERT_TRUE(client.read(msg));
  20443. EXPECT_EQ(at_limit.size(), msg.size());
  20444. client.close();
  20445. }
  20446. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20447. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20448. "/nonexistent");
  20449. auto res = client.connect();
  20450. EXPECT_FALSE(res);
  20451. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20452. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20453. EXPECT_FALSE(client.is_open());
  20454. }
  20455. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20456. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20457. "/ws-echo");
  20458. ASSERT_TRUE(client.connect());
  20459. ASSERT_TRUE(client.send(""));
  20460. std::string msg;
  20461. EXPECT_EQ(ws::Text, client.read(msg));
  20462. EXPECT_EQ("", msg);
  20463. client.close();
  20464. }
  20465. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20466. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20467. "/ws-echo");
  20468. // First connection
  20469. ASSERT_TRUE(client.connect());
  20470. ASSERT_TRUE(client.send("first"));
  20471. std::string msg;
  20472. ASSERT_TRUE(client.read(msg));
  20473. EXPECT_EQ("first", msg);
  20474. client.close();
  20475. EXPECT_FALSE(client.is_open());
  20476. // Reconnect using the same client object
  20477. ASSERT_TRUE(client.connect());
  20478. ASSERT_TRUE(client.is_open());
  20479. ASSERT_TRUE(client.send("second"));
  20480. ASSERT_TRUE(client.read(msg));
  20481. EXPECT_EQ("second", msg);
  20482. client.close();
  20483. }
  20484. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20485. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20486. "/ws-close-status");
  20487. ASSERT_TRUE(client.connect());
  20488. // Trigger the server to close with GoingAway status
  20489. ASSERT_TRUE(client.send("trigger"));
  20490. // read() should return false after receiving the close frame
  20491. std::string msg;
  20492. EXPECT_FALSE(client.read(msg));
  20493. EXPECT_FALSE(client.is_open());
  20494. }
  20495. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20496. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20497. "/ws-echo");
  20498. ASSERT_TRUE(client.connect());
  20499. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20500. EXPECT_FALSE(client.is_open());
  20501. }
  20502. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20503. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20504. ws::WebSocketClient client(
  20505. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20506. ASSERT_TRUE(client.connect());
  20507. // Server should have selected graphql-ws
  20508. EXPECT_EQ("graphql-ws", client.subprotocol());
  20509. client.close();
  20510. }
  20511. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  20512. Headers headers;
  20513. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  20514. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  20515. ws::WebSocketClient client(
  20516. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20517. ASSERT_TRUE(client.connect());
  20518. // The offer on the second field line counts too, so graphql-ws is selected
  20519. EXPECT_EQ("graphql-ws", client.subprotocol());
  20520. client.close();
  20521. }
  20522. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  20523. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20524. ws::WebSocketClient client(
  20525. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20526. ASSERT_TRUE(client.connect());
  20527. // Server should not have selected any subprotocol
  20528. EXPECT_TRUE(client.subprotocol().empty());
  20529. client.close();
  20530. }
  20531. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  20532. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  20533. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20534. "/ws-subprotocol-unoffered",
  20535. headers);
  20536. ASSERT_TRUE(client.connect());
  20537. EXPECT_TRUE(client.subprotocol().empty());
  20538. client.close();
  20539. }
  20540. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  20541. // Connect without requesting any subprotocol
  20542. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20543. "/ws-subprotocol");
  20544. ASSERT_TRUE(client.connect());
  20545. EXPECT_TRUE(client.subprotocol().empty());
  20546. client.close();
  20547. }
  20548. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  20549. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20550. "/ws-echo");
  20551. client.set_tcp_nodelay(true);
  20552. client.set_connection_timeout(3, 0);
  20553. bool socket_options_called = false;
  20554. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  20555. ASSERT_TRUE(client.connect());
  20556. ASSERT_TRUE(client.is_open());
  20557. EXPECT_TRUE(socket_options_called);
  20558. ASSERT_TRUE(client.send("hello"));
  20559. std::string msg;
  20560. auto result = client.read(msg);
  20561. EXPECT_EQ(result, ws::ReadResult::Text);
  20562. EXPECT_EQ(msg, "hello");
  20563. client.close();
  20564. }
  20565. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20566. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20567. "/ws-echo");
  20568. client.set_connection_timeout(std::chrono::seconds(3));
  20569. client.set_write_timeout(std::chrono::seconds(3));
  20570. // A sub-second remainder exercises the seconds/microseconds split.
  20571. client.set_read_timeout(std::chrono::milliseconds(1500));
  20572. ASSERT_TRUE(client.connect());
  20573. auto start = std::chrono::steady_clock::now();
  20574. std::string msg;
  20575. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20576. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20577. std::chrono::steady_clock::now() - start)
  20578. .count();
  20579. // Above 1s so that dropping the microseconds half of the split fails here.
  20580. // Ignoring the setter altogether would not reach this line at all: a client
  20581. // waits forever by default.
  20582. EXPECT_GE(elapsed, 1400);
  20583. EXPECT_LT(elapsed, 30000);
  20584. }
  20585. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20586. Server svr;
  20587. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20588. if (!req.has_header("Authorization")) {
  20589. res.status = StatusCode::Unauthorized_401;
  20590. res.set_content("Unauthorized", "text/plain");
  20591. return Server::HandlerResponse::Handled;
  20592. }
  20593. return Server::HandlerResponse::Unhandled;
  20594. });
  20595. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20596. std::string msg;
  20597. while (ws.read(msg)) {
  20598. ws.send(msg);
  20599. }
  20600. });
  20601. auto port = svr.bind_to_any_port("localhost");
  20602. std::thread t([&]() { svr.listen_after_bind(); });
  20603. svr.wait_until_ready();
  20604. // Without Authorization header - should be rejected before upgrade
  20605. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20606. EXPECT_FALSE(client1.connect());
  20607. // The rejection is framed like any other HTTP response
  20608. {
  20609. Client cli("localhost", port);
  20610. Headers headers = {{"Upgrade", "websocket"},
  20611. {"Connection", "Upgrade"},
  20612. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20613. {"Sec-WebSocket-Version", "13"}};
  20614. auto res = cli.Get("/ws", headers);
  20615. ASSERT_TRUE(res);
  20616. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20617. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20618. EXPECT_EQ("Unauthorized", res->body);
  20619. }
  20620. // With Authorization header - should succeed
  20621. Headers headers = {{"Authorization", "Bearer token123"}};
  20622. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20623. headers);
  20624. ASSERT_TRUE(client2.connect());
  20625. ASSERT_TRUE(client2.send("hello"));
  20626. std::string msg;
  20627. ASSERT_TRUE(client2.read(msg));
  20628. EXPECT_EQ("hello", msg);
  20629. client2.close();
  20630. svr.stop();
  20631. t.join();
  20632. }
  20633. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20634. Server svr;
  20635. std::atomic<int> pre_request_calls{0};
  20636. std::atomic<bool> route_matched{false};
  20637. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20638. pre_request_calls++;
  20639. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20640. if (req.get_header_value("Authorization") != "Bearer token123") {
  20641. res.status = StatusCode::Unauthorized_401;
  20642. res.set_content("Unauthorized", "text/plain");
  20643. return Server::HandlerResponse::Handled;
  20644. }
  20645. return Server::HandlerResponse::Unhandled;
  20646. });
  20647. std::atomic<bool> handler_called{false};
  20648. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20649. handler_called = true;
  20650. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20651. });
  20652. auto port = svr.bind_to_any_port("localhost");
  20653. std::thread t([&]() { svr.listen_after_bind(); });
  20654. svr.wait_until_ready();
  20655. // Without Authorization header - should be rejected before upgrade
  20656. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20657. "/ws/1");
  20658. EXPECT_FALSE(client1.connect());
  20659. EXPECT_FALSE(handler_called);
  20660. EXPECT_EQ(1, pre_request_calls);
  20661. EXPECT_TRUE(route_matched);
  20662. // The rejection is an ordinary HTTP response, not a protocol switch
  20663. {
  20664. Client cli("localhost", port);
  20665. Headers headers = {{"Upgrade", "websocket"},
  20666. {"Connection", "Upgrade"},
  20667. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20668. {"Sec-WebSocket-Version", "13"}};
  20669. auto res = cli.Get("/ws/1", headers);
  20670. ASSERT_TRUE(res);
  20671. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20672. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20673. EXPECT_EQ("Unauthorized", res->body);
  20674. }
  20675. EXPECT_FALSE(handler_called);
  20676. // With Authorization header - should succeed
  20677. Headers headers = {{"Authorization", "Bearer token123"}};
  20678. ws::WebSocketClient client2(
  20679. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20680. ASSERT_TRUE(client2.connect());
  20681. std::string msg;
  20682. ASSERT_TRUE(client2.read(msg));
  20683. EXPECT_EQ("/ws/:id 2", msg);
  20684. EXPECT_TRUE(handler_called);
  20685. client2.close();
  20686. svr.stop();
  20687. t.join();
  20688. }
  20689. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20690. Server svr;
  20691. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20692. // A read timeout is how a handler gets control back. Without it, a handler
  20693. // parked in read() can never write on the connection it is reading.
  20694. ws.set_read_timeout(std::chrono::milliseconds(100));
  20695. std::string msg;
  20696. while (ws.is_open()) {
  20697. auto r = ws.read(msg);
  20698. if (r == httplib::ws::Timeout) {
  20699. ws.send("tick");
  20700. continue;
  20701. }
  20702. if (r == httplib::ws::Fail) { break; }
  20703. ws.send(msg);
  20704. }
  20705. });
  20706. auto port = svr.bind_to_any_port("localhost");
  20707. std::thread t([&]() { svr.listen_after_bind(); });
  20708. svr.wait_until_ready();
  20709. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20710. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20711. ASSERT_TRUE(client.connect());
  20712. // The client sends nothing, so anything it receives came out of the
  20713. // handler's timeout path.
  20714. std::string msg;
  20715. ASSERT_EQ(client.read(msg), ws::Text);
  20716. EXPECT_EQ("tick", msg);
  20717. client.close();
  20718. svr.stop();
  20719. t.join();
  20720. }
  20721. // Stream::read may return fewer bytes than asked for. This is that contract at
  20722. // its worst -- one byte per call -- which is what a frame header straddling a
  20723. // read buffer's boundary looks like to the frame parser.
  20724. class WsByteAtATimeStream : public Stream {
  20725. public:
  20726. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20727. bool is_readable() const override { return true; }
  20728. bool wait_readable() const override { return true; }
  20729. bool wait_writable() const override { return true; }
  20730. ssize_t read(char *ptr, size_t size) override {
  20731. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20732. *ptr = data_[pos_++];
  20733. return 1;
  20734. }
  20735. ssize_t write(const char *, size_t size) override {
  20736. return static_cast<ssize_t>(size);
  20737. }
  20738. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20739. ip = "127.0.0.1";
  20740. port = 0;
  20741. }
  20742. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20743. ip = "127.0.0.1";
  20744. port = 0;
  20745. }
  20746. socket_t socket() const override { return INVALID_SOCKET; }
  20747. time_t duration() const override { return 0; }
  20748. private:
  20749. std::string data_;
  20750. size_t pos_ = 0;
  20751. };
  20752. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20753. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20754. // length and the mask key are all multi-byte fields here. Each used to be
  20755. // read with a single read() call, which fails as soon as one is split.
  20756. std::string body(200, 'x');
  20757. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20758. std::string frame;
  20759. frame += static_cast<char>(0x81); // FIN + Text
  20760. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20761. frame += static_cast<char>(body.size() >> 8);
  20762. frame += static_cast<char>(body.size() & 0xff);
  20763. for (size_t i = 0; i < 4; i++) {
  20764. frame += static_cast<char>(mask[i]);
  20765. }
  20766. for (size_t i = 0; i < body.size(); i++) {
  20767. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20768. }
  20769. WsByteAtATimeStream strm(frame);
  20770. ws::Opcode opcode;
  20771. std::string payload;
  20772. bool fin = false;
  20773. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20774. /*expect_masked=*/true, 1024),
  20775. ws::impl::FrameRead::Ok);
  20776. EXPECT_TRUE(fin);
  20777. EXPECT_EQ(opcode, ws::Opcode::Text);
  20778. EXPECT_EQ(payload, body);
  20779. }
  20780. TEST(WebSocketTest, QueryStringInHandshake) {
  20781. Server svr;
  20782. std::mutex mtx;
  20783. std::string received_target;
  20784. std::string received_token;
  20785. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20786. {
  20787. std::lock_guard<std::mutex> lock(mtx);
  20788. received_target = req.target;
  20789. if (req.has_param("token")) {
  20790. received_token = req.get_param_value("token");
  20791. }
  20792. }
  20793. std::string msg;
  20794. while (ws.read(msg)) {
  20795. ws.send(msg);
  20796. }
  20797. });
  20798. auto port = svr.bind_to_any_port("localhost");
  20799. std::thread t([&]() { svr.listen_after_bind(); });
  20800. svr.wait_until_ready();
  20801. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20802. "/ws?token=ABC&session=123");
  20803. ASSERT_TRUE(client.connect());
  20804. // Round-trip ensures the handler has run and captured the request.
  20805. ASSERT_TRUE(client.send("hello"));
  20806. std::string msg;
  20807. ASSERT_TRUE(client.read(msg));
  20808. EXPECT_EQ("hello", msg);
  20809. client.close();
  20810. {
  20811. std::lock_guard<std::mutex> lock(mtx);
  20812. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20813. EXPECT_EQ("ABC", received_token);
  20814. }
  20815. svr.stop();
  20816. t.join();
  20817. }
  20818. // Run a handshake against a throwaway server and hand the request the server
  20819. // received back to the caller, so tests can assert on the headers the client
  20820. // actually put on the wire.
  20821. static void capture_websocket_handshake_request(
  20822. const Headers &client_headers,
  20823. std::function<void(const Request &, int port)> verify) {
  20824. Server svr;
  20825. std::mutex mtx;
  20826. Request received;
  20827. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20828. {
  20829. std::lock_guard<std::mutex> lock(mtx);
  20830. received = req;
  20831. }
  20832. std::string msg;
  20833. while (ws.read(msg)) {
  20834. ws.send(msg);
  20835. }
  20836. });
  20837. auto port = svr.bind_to_any_port("localhost");
  20838. std::thread t([&]() { svr.listen_after_bind(); });
  20839. auto se = detail::scope_exit([&] {
  20840. svr.stop();
  20841. t.join();
  20842. });
  20843. svr.wait_until_ready();
  20844. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20845. client_headers);
  20846. ASSERT_TRUE(client.connect());
  20847. ASSERT_TRUE(client.send("hello"));
  20848. std::string msg;
  20849. ASSERT_TRUE(client.read(msg));
  20850. client.close();
  20851. {
  20852. std::lock_guard<std::mutex> lock(mtx);
  20853. verify(received, port);
  20854. }
  20855. }
  20856. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20857. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20858. // Non-default port must be present in the Host header. Default ports
  20859. // (80/443) are omitted; that logic is covered by
  20860. // MakeHostAndPortStringTest.
  20861. EXPECT_EQ("localhost:" + std::to_string(port),
  20862. req.get_header_value("Host"));
  20863. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20864. req.get_header_value("User-Agent"));
  20865. EXPECT_FALSE(req.has_header("Accept"));
  20866. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20867. EXPECT_FALSE(req.has_header("Content-Length"));
  20868. });
  20869. }
  20870. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20871. capture_websocket_handshake_request(
  20872. {{"Host", "example.com"},
  20873. {"User-Agent", "custom-agent"},
  20874. {"X-Custom", "value"}},
  20875. [](const Request &req, int) {
  20876. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20877. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20878. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20879. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20880. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20881. });
  20882. }
  20883. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20884. capture_websocket_handshake_request(
  20885. {{"Upgrade", "bogus"},
  20886. {"Connection", "close"},
  20887. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20888. {"Sec-WebSocket-Version", "8"}},
  20889. [](const Request &req, int) {
  20890. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20891. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20892. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20893. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20894. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20895. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20896. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20897. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20898. req.get_header_value("Sec-WebSocket-Key"));
  20899. });
  20900. }
  20901. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20902. // A header the client refuses to send must abort the handshake before any
  20903. // part of it reaches the wire; a lone request line would otherwise sit in
  20904. // the peer's buffer as a truncated request.
  20905. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20906. ASSERT_NE(INVALID_SOCKET, srv);
  20907. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20908. sockaddr_in addr{};
  20909. addr.sin_family = AF_INET;
  20910. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20911. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20912. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20913. ASSERT_EQ(0, ::listen(srv, 1));
  20914. sockaddr_in bound{};
  20915. socklen_t bound_len = sizeof(bound);
  20916. ASSERT_EQ(
  20917. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20918. auto port = ntohs(bound.sin_port);
  20919. ssize_t received = -1;
  20920. std::thread t([&] {
  20921. // Bound every blocking call so a regression fails the test with a bad
  20922. // value instead of hanging the suite.
  20923. fd_set rfds;
  20924. FD_ZERO(&rfds);
  20925. FD_SET(srv, &rfds);
  20926. timeval tv{5, 0};
  20927. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20928. 0) {
  20929. return;
  20930. }
  20931. sockaddr_in cli_addr{};
  20932. socklen_t cli_len = sizeof(cli_addr);
  20933. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20934. if (cli == INVALID_SOCKET) { return; }
  20935. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20936. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20937. char buf[4096];
  20938. received = ::recv(cli, buf, sizeof(buf), 0);
  20939. });
  20940. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20941. // connect() has already shut the socket down by the time it returns false,
  20942. // so the peer sees EOF without waiting for the client to be destroyed.
  20943. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20944. {{"X-Bad", "a\r\nInjected: 1"}});
  20945. EXPECT_FALSE(client.connect());
  20946. t.join();
  20947. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20948. EXPECT_EQ(0, received);
  20949. }
  20950. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20951. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20952. // contains "upgrade" as a substring is a different token and must not
  20953. // start a WebSocket handshake.
  20954. auto make_request = [](const std::vector<std::string> &connection_values) {
  20955. Request req;
  20956. req.method = "GET";
  20957. req.headers.emplace("Upgrade", "websocket");
  20958. for (const auto &value : connection_values) {
  20959. req.headers.emplace("Connection", value);
  20960. }
  20961. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20962. req.headers.emplace("Sec-WebSocket-Version", "13");
  20963. return req;
  20964. };
  20965. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20966. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20967. EXPECT_TRUE(
  20968. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20969. EXPECT_TRUE(
  20970. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20971. EXPECT_TRUE(
  20972. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20973. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20974. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20975. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20976. EXPECT_FALSE(
  20977. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20978. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20979. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20980. }
  20981. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20982. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20983. // asks recipients to match each protocol-name case-insensitively, and RFC
  20984. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20985. // client naming websocket alongside another protocol, or on a second field
  20986. // line, is offering websocket; a value that merely contains "websocket" as a
  20987. // substring is a different protocol name and is not.
  20988. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20989. Request req;
  20990. req.method = "GET";
  20991. for (const auto &value : upgrade_values) {
  20992. req.headers.emplace("Upgrade", value);
  20993. }
  20994. req.headers.emplace("Connection", "Upgrade");
  20995. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20996. req.headers.emplace("Sec-WebSocket-Version", "13");
  20997. return req;
  20998. };
  20999. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21000. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21001. EXPECT_TRUE(
  21002. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21003. EXPECT_TRUE(
  21004. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21005. EXPECT_TRUE(
  21006. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21007. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21008. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21009. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21010. EXPECT_FALSE(
  21011. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21012. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21013. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21014. }
  21015. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21016. Server svr;
  21017. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21018. auto port = svr.bind_to_any_port("localhost");
  21019. std::thread t([&]() { svr.listen_after_bind(); });
  21020. auto se = detail::scope_exit([&] {
  21021. svr.stop();
  21022. t.join();
  21023. });
  21024. svr.wait_until_ready();
  21025. Headers headers = {{"Upgrade", "websocket"},
  21026. {"Connection", "notupgrade"},
  21027. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21028. {"Sec-WebSocket-Version", "13"}};
  21029. Client cli("localhost", port);
  21030. auto res = cli.Get("/ws", headers);
  21031. // The route exists only as a WebSocket route, so a request that fails the
  21032. // handshake check falls through to ordinary routing.
  21033. ASSERT_TRUE(res);
  21034. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21035. }
  21036. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21037. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21038. // Connection value is the only thing left for the client to reject.
  21039. Server svr;
  21040. svr.Get("/ws", [](const Request &req, Response &res) {
  21041. res.status = StatusCode::SwitchingProtocol_101;
  21042. res.set_header("Upgrade", "websocket");
  21043. res.set_header("Connection", "notupgrade");
  21044. res.set_header("Sec-WebSocket-Accept",
  21045. detail::websocket_accept_key(
  21046. req.get_header_value("Sec-WebSocket-Key")));
  21047. });
  21048. auto port = svr.bind_to_any_port("localhost");
  21049. std::thread t([&]() { svr.listen_after_bind(); });
  21050. auto se = detail::scope_exit([&] {
  21051. svr.stop();
  21052. t.join();
  21053. });
  21054. svr.wait_until_ready();
  21055. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21056. auto res = client.connect();
  21057. EXPECT_FALSE(res);
  21058. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21059. EXPECT_FALSE(client.is_open());
  21060. }
  21061. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21062. Server svr;
  21063. svr.Get("/ws", [](const Request &req, Response &res) {
  21064. res.status = StatusCode::SwitchingProtocol_101;
  21065. res.set_header("Upgrade", "websocket");
  21066. res.set_header("Connection", "Upgrade");
  21067. res.set_header("Sec-WebSocket-Accept",
  21068. detail::websocket_accept_key(
  21069. req.get_header_value("Sec-WebSocket-Key")));
  21070. res.set_header("Sec-WebSocket-Protocol", "admin");
  21071. });
  21072. auto port = svr.bind_to_any_port("localhost");
  21073. std::thread t([&]() { svr.listen_after_bind(); });
  21074. auto se = detail::scope_exit([&] {
  21075. svr.stop();
  21076. t.join();
  21077. });
  21078. svr.wait_until_ready();
  21079. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21080. // Server selects a subprotocol the client never offered
  21081. {
  21082. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21083. ws::WebSocketClient client(url, headers);
  21084. auto res = client.connect();
  21085. EXPECT_FALSE(res);
  21086. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21087. EXPECT_FALSE(client.is_open());
  21088. EXPECT_TRUE(client.subprotocol().empty());
  21089. }
  21090. // Client offered none but the server named one anyway
  21091. {
  21092. ws::WebSocketClient client(url);
  21093. auto res = client.connect();
  21094. EXPECT_FALSE(res);
  21095. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21096. EXPECT_FALSE(client.is_open());
  21097. EXPECT_TRUE(client.subprotocol().empty());
  21098. }
  21099. }
  21100. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21101. // The socket path doubles as the URL host, so it must not contain '/'.
  21102. const char *shard = getenv("GTEST_SHARD_INDEX");
  21103. const std::string sock_path =
  21104. shard ? std::string("httplib-ws-") + shard + ".sock"
  21105. : std::string("httplib-ws.sock");
  21106. std::remove(sock_path.c_str());
  21107. Server svr;
  21108. std::mutex mtx;
  21109. std::string received_host;
  21110. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21111. {
  21112. std::lock_guard<std::mutex> lock(mtx);
  21113. received_host = req.get_header_value("Host");
  21114. }
  21115. std::string msg;
  21116. while (ws.read(msg)) {
  21117. ws.send(msg);
  21118. }
  21119. });
  21120. svr.set_address_family(AF_UNIX);
  21121. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21122. auto se = detail::scope_exit([&] {
  21123. svr.stop();
  21124. t.join();
  21125. std::remove(sock_path.c_str());
  21126. });
  21127. svr.wait_until_ready();
  21128. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21129. client.set_address_family(AF_UNIX);
  21130. ASSERT_TRUE(client.connect());
  21131. ASSERT_TRUE(client.send("hello"));
  21132. std::string msg;
  21133. ASSERT_TRUE(client.read(msg));
  21134. client.close();
  21135. {
  21136. std::lock_guard<std::mutex> lock(mtx);
  21137. // There is no host:port for a Unix socket, so the same "localhost"
  21138. // placeholder the HTTP client uses is expected.
  21139. EXPECT_EQ("localhost", received_host);
  21140. }
  21141. }
  21142. // Two threads must never parse WebSocket frames from the same stream.
  21143. // close() used to read the peer's Close reply with its own frame read, so it
  21144. // raced a reader thread that was in the middle of a payload: the payload loop
  21145. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21146. // so bytes taken by close() were replaced with bytes from further along the
  21147. // stream. The message kept its length and silently changed content.
  21148. //
  21149. // The raw peer below sends a frame header plus part of the payload, waits for
  21150. // the handler to call close(), and only then sends the rest. Whichever thread
  21151. // would win the race for those bytes, the message must arrive intact, because
  21152. // close() must not touch the stream while read() owns it.
  21153. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21154. #ifndef _WIN32
  21155. signal(SIGPIPE, SIG_IGN);
  21156. #endif
  21157. const size_t payload_len = 120; // fits the 7-bit length field
  21158. const size_t prefix_len = 8;
  21159. const int attempts = 8;
  21160. std::string expected(payload_len, '\0');
  21161. for (size_t i = 0; i < payload_len; i++) {
  21162. expected[i] = static_cast<char>('a' + i % 26);
  21163. }
  21164. std::atomic<bool> peer_stalled{false};
  21165. std::atomic<bool> handler_done{false};
  21166. std::mutex received_mutex;
  21167. std::vector<std::string> received;
  21168. // Bound every wait, so a regression fails the test instead of hanging the
  21169. // suite.
  21170. auto wait_for = [](const std::atomic<bool> &flag) {
  21171. for (int i = 0; i < 500 && !flag; i++) {
  21172. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21173. }
  21174. };
  21175. Server svr;
  21176. svr.set_websocket_ping_interval(0);
  21177. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21178. std::thread reader([&]() {
  21179. std::string msg;
  21180. while (ws.read(msg)) {
  21181. std::lock_guard<std::mutex> guard(received_mutex);
  21182. received.push_back(msg);
  21183. }
  21184. });
  21185. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21186. // inside read_websocket_frame() when close() runs.
  21187. wait_for(peer_stalled);
  21188. ws.close();
  21189. reader.join();
  21190. handler_done = true;
  21191. });
  21192. auto port = svr.bind_to_any_port("127.0.0.1");
  21193. std::thread t([&]() { svr.listen_after_bind(); });
  21194. auto se = detail::scope_exit([&] {
  21195. svr.stop();
  21196. t.join();
  21197. });
  21198. svr.wait_until_ready();
  21199. auto send_bytes = [](socket_t s, const std::string &data) {
  21200. #ifdef _WIN32
  21201. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21202. #else
  21203. auto n = ::send(s, data.data(), data.size(), 0);
  21204. #endif
  21205. return n == static_cast<decltype(n)>(data.size());
  21206. };
  21207. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21208. // Every length used here fits the 7-bit length field.
  21209. auto masked_header = [](uint8_t first_byte, size_t len) {
  21210. std::string h;
  21211. h += static_cast<char>(first_byte);
  21212. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21213. h.append(4, '\0'); // mask key
  21214. return h;
  21215. };
  21216. for (int attempt = 0; attempt < attempts; attempt++) {
  21217. peer_stalled = false;
  21218. handler_done = false;
  21219. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21220. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21221. auto se_sock = detail::scope_exit([&] {
  21222. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21223. });
  21224. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21225. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21226. sockaddr_in addr{};
  21227. addr.sin_family = AF_INET;
  21228. addr.sin_port = htons(static_cast<uint16_t>(port));
  21229. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21230. ASSERT_EQ(
  21231. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21232. << "attempt " << attempt;
  21233. ASSERT_TRUE(send_bytes(sock,
  21234. "GET /ws HTTP/1.1\r\n"
  21235. "Host: 127.0.0.1\r\n"
  21236. "Upgrade: websocket\r\n"
  21237. "Connection: Upgrade\r\n"
  21238. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21239. "Sec-WebSocket-Version: 13\r\n"
  21240. "\r\n"))
  21241. << "attempt " << attempt;
  21242. std::string response;
  21243. while (response.find("\r\n\r\n") == std::string::npos) {
  21244. char buf[512];
  21245. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21246. if (n <= 0) { break; }
  21247. response.append(buf, static_cast<size_t>(n));
  21248. }
  21249. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21250. << "attempt " << attempt;
  21251. // Send the header of a Binary message but only the first prefix_len bytes
  21252. // of its payload, leaving the reader thread stalled inside the payload.
  21253. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21254. expected.substr(0, prefix_len)))
  21255. << "attempt " << attempt;
  21256. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21257. peer_stalled = true;
  21258. // Let close() send its Close frame and park in its own read before the
  21259. // rest of the payload arrives, so both threads are waiting for it.
  21260. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21261. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21262. close_frame += static_cast<char>(0x03); // status 1000
  21263. close_frame += static_cast<char>(0xE8);
  21264. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21265. << "attempt " << attempt;
  21266. // Closing the peer releases the reader thread even on the buggy path,
  21267. // where it waits for bytes another thread already consumed.
  21268. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21269. detail::close_socket(sock);
  21270. sock = INVALID_SOCKET;
  21271. wait_for(handler_done);
  21272. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21273. }
  21274. std::lock_guard<std::mutex> guard(received_mutex);
  21275. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21276. << "a message in flight when close() ran was dropped";
  21277. for (size_t i = 0; i < received.size(); i++) {
  21278. EXPECT_EQ(expected, received[i]) << "message " << i;
  21279. }
  21280. }
  21281. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21282. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21283. protected:
  21284. void SetUp() override {
  21285. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21286. SERVER_PRIVATE_KEY_FILE);
  21287. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21288. std::string msg;
  21289. ws::ReadResult ret;
  21290. while ((ret = ws.read(msg))) {
  21291. if (ret == ws::Binary) {
  21292. ws.send(msg.data(), msg.size());
  21293. } else {
  21294. ws.send(msg);
  21295. }
  21296. }
  21297. });
  21298. port_ = server_->bind_to_any_port(HOST);
  21299. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21300. server_->wait_until_ready();
  21301. }
  21302. void TearDown() override {
  21303. server_->stop();
  21304. if (server_thread_.joinable()) { server_thread_.join(); }
  21305. }
  21306. std::unique_ptr<SSLServer> server_;
  21307. std::thread server_thread_;
  21308. int port_ = 0;
  21309. };
  21310. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21311. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21312. "/ws-echo");
  21313. client.enable_server_certificate_verification(false);
  21314. ASSERT_TRUE(client.connect());
  21315. ASSERT_TRUE(client.is_open());
  21316. ASSERT_TRUE(client.send("Hello WSS"));
  21317. std::string msg;
  21318. EXPECT_EQ(ws::Text, client.read(msg));
  21319. EXPECT_EQ("Hello WSS", msg);
  21320. client.close();
  21321. }
  21322. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21323. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21324. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21325. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21326. // client (without calling close() first) is the only path that runs
  21327. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21328. // bug exactly.
  21329. //
  21330. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21331. // when linked against an instrumented libssl; run under Valgrind to catch it
  21332. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21333. // suite (the freed session otherwise stalls on the close handshake) — this test
  21334. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21335. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21336. {
  21337. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21338. "/ws-echo");
  21339. client.enable_server_certificate_verification(false);
  21340. client.set_read_timeout(2, 0);
  21341. client.set_write_timeout(2, 0);
  21342. ASSERT_TRUE(client.connect());
  21343. ASSERT_TRUE(client.is_open());
  21344. ASSERT_TRUE(client.send("still open"));
  21345. // Intentionally do NOT call client.close(): leaving scope runs
  21346. // shutdown_and_close() with the WebSocket still open, which must send the
  21347. // close frame while the TLS session is still alive.
  21348. }
  21349. }
  21350. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21351. // shutdown_and_close() at the start of connect(), reproducing the same
  21352. // use-after-free within the test body rather than at scope exit. The second
  21353. // connect must succeed and echo, proving the close handshake ran over a live
  21354. // session. See the note above about memory-tool requirements.
  21355. TEST_F(WebSocketSSLIntegrationTest,
  21356. ReconnectWhileOpenSendsCloseOverLiveSession) {
  21357. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21358. "/ws-echo");
  21359. client.enable_server_certificate_verification(false);
  21360. client.set_read_timeout(2, 0);
  21361. client.set_write_timeout(2, 0);
  21362. ASSERT_TRUE(client.connect());
  21363. ASSERT_TRUE(client.is_open());
  21364. ASSERT_TRUE(client.send("still open"));
  21365. // Reconnect without closing first: connect() calls shutdown_and_close() on
  21366. // the still-open connection, which must not touch a freed TLS session.
  21367. ASSERT_TRUE(client.connect());
  21368. ASSERT_TRUE(client.is_open());
  21369. ASSERT_TRUE(client.send("after reconnect"));
  21370. std::string msg;
  21371. EXPECT_EQ(ws::Text, client.read(msg));
  21372. EXPECT_EQ("after reconnect", msg);
  21373. client.close();
  21374. }
  21375. #endif
  21376. #ifdef CPPHTTPLIB_SSL_ENABLED
  21377. class WebSocketSSLCATest : public ::testing::Test {
  21378. protected:
  21379. void SetUp() override {
  21380. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  21381. SERVER_PRIVATE_KEY_FILE);
  21382. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21383. std::string msg;
  21384. while (ws.read(msg)) {
  21385. ws.send(msg);
  21386. }
  21387. });
  21388. port_ = server_->bind_to_any_port("127.0.0.1");
  21389. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21390. server_->wait_until_ready();
  21391. }
  21392. void TearDown() override {
  21393. server_->stop();
  21394. if (server_thread_.joinable()) { server_thread_.join(); }
  21395. }
  21396. std::string url() const {
  21397. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21398. }
  21399. std::unique_ptr<SSLServer> server_;
  21400. std::thread server_thread_;
  21401. int port_ = 0;
  21402. };
  21403. // A custom CA loaded as PEM verifies the server with full certificate
  21404. // verification enabled
  21405. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21406. ws::WebSocketClient client(url());
  21407. std::string cert;
  21408. read_file(SERVER_CERT2_FILE, cert);
  21409. client.load_ca_cert_store(cert.c_str(), cert.size());
  21410. ASSERT_TRUE(client.connect());
  21411. ASSERT_TRUE(client.send("hello"));
  21412. std::string msg;
  21413. EXPECT_EQ(ws::Text, client.read(msg));
  21414. EXPECT_EQ("hello", msg);
  21415. client.close();
  21416. }
  21417. // A custom CA that does not cover the server must fail verification (the
  21418. // custom CA is exclusive; system certs are not loaded alongside it)
  21419. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21420. ws::WebSocketClient client(url());
  21421. std::string cert;
  21422. read_file(CLIENT_CA_CERT_FILE, cert);
  21423. client.load_ca_cert_store(cert.c_str(), cert.size());
  21424. auto res = client.connect();
  21425. ASSERT_FALSE(res);
  21426. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21427. EXPECT_EQ(-1, res.status());
  21428. EXPECT_NE(0u, res.ssl_backend_error());
  21429. }
  21430. // The same CA as a file path rather than PEM in memory
  21431. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21432. ws::WebSocketClient client(url());
  21433. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21434. ASSERT_TRUE(client.connect());
  21435. ASSERT_TRUE(client.send("hello"));
  21436. std::string msg;
  21437. EXPECT_EQ(ws::Text, client.read(msg));
  21438. EXPECT_EQ("hello", msg);
  21439. client.close();
  21440. }
  21441. // ...and a CA file that does not cover the server still fails, so it is the
  21442. // path above that decides the outcome
  21443. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21444. ws::WebSocketClient client(url());
  21445. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21446. ASSERT_FALSE(client.connect());
  21447. }
  21448. // Regression test: reconnecting with a native custom CA store used to reuse
  21449. // a store handle the previous TLS context had already freed (use-after-free
  21450. // under the OpenSSL backend). The context now lives as long as the client.
  21451. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  21452. ws::WebSocketClient client(url());
  21453. std::string cert;
  21454. read_file(SERVER_CERT2_FILE, cert);
  21455. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  21456. ASSERT_TRUE(client.connect());
  21457. client.close();
  21458. ASSERT_TRUE(client.connect());
  21459. ASSERT_TRUE(client.send("again"));
  21460. std::string msg;
  21461. EXPECT_EQ(ws::Text, client.read(msg));
  21462. EXPECT_EQ("again", msg);
  21463. client.close();
  21464. }
  21465. // Regression test: a certificate with a trusted chain but no identity match
  21466. // for the server IP must be rejected. The Mbed TLS backend used to skip
  21467. // verification entirely for IP hosts, so this connection succeeded there.
  21468. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  21469. // chain verification while the identity check must still fail.
  21470. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  21471. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21472. ASSERT_TRUE(svr.is_valid());
  21473. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21474. std::string msg;
  21475. while (ws.read(msg)) {
  21476. ws.send(msg);
  21477. }
  21478. });
  21479. auto port = svr.bind_to_any_port("127.0.0.1");
  21480. auto t = std::thread([&]() { svr.listen_after_bind(); });
  21481. auto se = detail::scope_exit([&] {
  21482. svr.stop();
  21483. t.join();
  21484. });
  21485. svr.wait_until_ready();
  21486. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  21487. "/echo");
  21488. std::string cert;
  21489. read_file(SERVER_CERT_FILE, cert);
  21490. client.load_ca_cert_store(cert.c_str(), cert.size());
  21491. ASSERT_FALSE(client.connect());
  21492. }
  21493. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  21494. // SNI, so nothing binds the host name to the TLS session. These bind the
  21495. // server to "localhost" instead, the only shape that exercises the SNI and
  21496. // hostname-verification path with certificate verification left enabled.
  21497. class WebSocketSSLDnsHostTest : public ::testing::Test {
  21498. protected:
  21499. void Start(const char *cert_file) {
  21500. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  21501. SERVER_PRIVATE_KEY_FILE);
  21502. ASSERT_TRUE(server_->is_valid());
  21503. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21504. std::string msg;
  21505. while (ws.read(msg)) {
  21506. ws.send(msg);
  21507. }
  21508. });
  21509. port_ = server_->bind_to_any_port("localhost");
  21510. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21511. server_->wait_until_ready();
  21512. }
  21513. void TearDown() override {
  21514. if (server_) { server_->stop(); }
  21515. if (server_thread_.joinable()) { server_thread_.join(); }
  21516. }
  21517. std::string url() const {
  21518. return "wss://localhost:" + std::to_string(port_) + "/echo";
  21519. }
  21520. std::unique_ptr<SSLServer> server_;
  21521. std::thread server_thread_;
  21522. int port_ = 0;
  21523. };
  21524. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  21525. // out and the connection is usable
  21526. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  21527. Start(SERVER_CERT2_FILE);
  21528. ws::WebSocketClient client(url());
  21529. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21530. ASSERT_TRUE(client.connect());
  21531. ASSERT_TRUE(client.send("hello"));
  21532. std::string msg;
  21533. EXPECT_EQ(ws::Text, client.read(msg));
  21534. EXPECT_EQ("hello", msg);
  21535. client.close();
  21536. }
  21537. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  21538. // while the identity check must still reject "localhost"
  21539. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  21540. Start(SERVER_CERT_FILE);
  21541. ws::WebSocketClient client(url());
  21542. client.set_ca_cert_path(SERVER_CERT_FILE);
  21543. auto res = client.connect();
  21544. ASSERT_FALSE(res);
  21545. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  21546. EXPECT_EQ(-1, res.status());
  21547. }
  21548. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  21549. // disabled: the chain is still checked, only the identity check is skipped
  21550. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  21551. Start(SERVER_CERT_FILE);
  21552. ws::WebSocketClient client(url());
  21553. client.set_ca_cert_path(SERVER_CERT_FILE);
  21554. client.enable_server_hostname_verification(false);
  21555. ASSERT_TRUE(client.connect());
  21556. ASSERT_TRUE(client.send("hello"));
  21557. std::string msg;
  21558. EXPECT_EQ(ws::Text, client.read(msg));
  21559. EXPECT_EQ("hello", msg);
  21560. client.close();
  21561. }
  21562. // A CA that did not sign the server certificate fails the chain, even though
  21563. // the name would match
  21564. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  21565. Start(SERVER_CERT2_FILE);
  21566. ws::WebSocketClient client(url());
  21567. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21568. ASSERT_FALSE(client.connect());
  21569. }
  21570. // With verification disabled, neither the chain nor the name is checked
  21571. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  21572. Start(SERVER_CERT_FILE);
  21573. ws::WebSocketClient client(url());
  21574. client.enable_server_certificate_verification(false);
  21575. ASSERT_TRUE(client.connect());
  21576. ASSERT_TRUE(client.send("hello"));
  21577. std::string msg;
  21578. EXPECT_EQ(ws::Text, client.read(msg));
  21579. EXPECT_EQ("hello", msg);
  21580. client.close();
  21581. }
  21582. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  21583. protected:
  21584. void SetUp() override {
  21585. server_ = httplib::detail::make_unique<SSLServer>(
  21586. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21587. ASSERT_TRUE(server_->is_valid());
  21588. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21589. std::string msg;
  21590. while (ws.read(msg)) {
  21591. ws.send(msg);
  21592. }
  21593. });
  21594. port_ = server_->bind_to_any_port("localhost");
  21595. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21596. server_->wait_until_ready();
  21597. }
  21598. void TearDown() override {
  21599. server_->stop();
  21600. if (server_thread_.joinable()) { server_thread_.join(); }
  21601. }
  21602. std::string url() const {
  21603. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21604. }
  21605. void ConnectWithClientCert(const std::string &client_cert_file,
  21606. const std::string &client_private_key_file,
  21607. const char *private_key_password) {
  21608. std::string cert_pem, key_pem;
  21609. read_file(client_cert_file, cert_pem);
  21610. read_file(client_private_key_file, key_pem);
  21611. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21612. key_pem.c_str(), key_pem.size(),
  21613. private_key_password};
  21614. ws::WebSocketClient client(url(), pem);
  21615. ASSERT_TRUE(client.is_valid());
  21616. client.enable_server_certificate_verification(false);
  21617. ASSERT_TRUE(client.connect());
  21618. ASSERT_TRUE(client.send("hello"));
  21619. std::string msg;
  21620. EXPECT_EQ(ws::Text, client.read(msg));
  21621. EXPECT_EQ("hello", msg);
  21622. client.close();
  21623. }
  21624. std::unique_ptr<SSLServer> server_;
  21625. std::thread server_thread_;
  21626. int port_ = 0;
  21627. };
  21628. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21629. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21630. }
  21631. // Control for the tests above: the fixture's server really does require a
  21632. // client certificate, so it is the PEM the constructor installed that decides
  21633. // the outcome.
  21634. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21635. ws::WebSocketClient client(url());
  21636. ASSERT_TRUE(client.is_valid());
  21637. client.enable_server_certificate_verification(false);
  21638. EXPECT_FALSE(client.connect());
  21639. }
  21640. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21641. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21642. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21643. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21644. }
  21645. #endif
  21646. #if !defined(_WIN32)
  21647. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21648. auto secret_dir = std::string("./symlink_test_secret");
  21649. auto served_dir = std::string("./symlink_test_served");
  21650. auto secret_file = secret_dir + "/secret.txt";
  21651. auto symlink_path = served_dir + "/escape";
  21652. // Setup: create directories and files
  21653. mkdir(secret_dir.c_str(), 0755);
  21654. mkdir(served_dir.c_str(), 0755);
  21655. {
  21656. std::ofstream ofs(secret_file);
  21657. ofs << "SECRET_DATA";
  21658. }
  21659. // Create symlink using absolute path so it resolves correctly
  21660. #ifdef PATH_MAX
  21661. char abs_secret[PATH_MAX];
  21662. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21663. #else
  21664. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21665. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21666. ASSERT_NE(nullptr, abs_secret);
  21667. #endif
  21668. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21669. auto se = detail::scope_exit([&] {
  21670. unlink(symlink_path.c_str());
  21671. unlink(secret_file.c_str());
  21672. rmdir(served_dir.c_str());
  21673. rmdir(secret_dir.c_str());
  21674. });
  21675. Server svr;
  21676. svr.set_mount_point("/", served_dir);
  21677. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21678. auto se2 = detail::scope_exit([&] {
  21679. svr.stop();
  21680. listen_thread.join();
  21681. });
  21682. svr.wait_until_ready();
  21683. Client cli("localhost", PORT);
  21684. // Symlink pointing outside base dir should be blocked
  21685. auto res = cli.Get("/escape/secret.txt");
  21686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21687. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21688. }
  21689. #endif
  21690. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  21691. // "GET /smuggled" request), reads the first response, and only then sends the
  21692. // embedded request as the body. Returns how many times /smuggled ran.
  21693. //
  21694. // The body is sent AFTER receiving the first response (as in the original
  21695. // PoC) so that the stream_line_reader cannot buffer it together with the
  21696. // headers of the first request.
  21697. static int count_smuggled_requests(const std::string &outer_head,
  21698. std::string &first_response) {
  21699. Server svr;
  21700. svr.set_mount_point("/", "./www");
  21701. std::atomic<int> smuggled_count(0);
  21702. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21703. smuggled_count++;
  21704. res.set_content("oops", "text/plain");
  21705. });
  21706. svr.Post("/post", [&](const Request &req, Response &res) {
  21707. res.set_content(req.body, "text/plain");
  21708. });
  21709. auto port = svr.bind_to_any_port("localhost");
  21710. thread t = thread([&] { svr.listen_after_bind(); });
  21711. auto se = detail::scope_exit([&] {
  21712. svr.stop();
  21713. t.join();
  21714. });
  21715. svr.wait_until_ready();
  21716. auto error = Error::Success;
  21717. auto sock = detail::create_client_socket(
  21718. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21719. /*connection_timeout_sec=*/2, 0,
  21720. /*read_timeout_sec=*/2, 0,
  21721. /*write_timeout_sec=*/2, 0, std::string(), error);
  21722. EXPECT_NE(INVALID_SOCKET, sock);
  21723. if (sock == INVALID_SOCKET) { return -1; }
  21724. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21725. // The "smuggled" request will be sent as the body of the outer request
  21726. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21727. "Host: localhost\r\n"
  21728. "Connection: close\r\n"
  21729. "\r\n";
  21730. auto head = outer_head;
  21731. auto len = std::to_string(smuggled.size());
  21732. for (auto pos = head.find("{len}"); pos != std::string::npos;
  21733. pos = head.find("{len}", pos + len.size())) {
  21734. head.replace(pos, 5, len);
  21735. }
  21736. // Step 1: Send only the outer request headers (no body yet)
  21737. auto sent = send(sock, head.data(), head.size(), 0);
  21738. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  21739. // Step 2: Read the first response
  21740. char buf[4096];
  21741. for (;;) {
  21742. auto n = recv(sock, buf, sizeof(buf), 0);
  21743. if (n <= 0) break;
  21744. first_response.append(buf, static_cast<size_t>(n));
  21745. // Stop once we have a complete response (headers + body)
  21746. auto hdr_end = first_response.find("\r\n\r\n");
  21747. if (hdr_end != std::string::npos) {
  21748. // Check for Content-Length to know when the body is complete
  21749. auto cl_pos = first_response.find("Content-Length:");
  21750. if (cl_pos != std::string::npos) {
  21751. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21752. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21753. auto cl = std::stoul(
  21754. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21755. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21756. } else {
  21757. break; // No Content-Length, assume headers-only response
  21758. }
  21759. }
  21760. }
  21761. // Step 3: Now send the body, which looks like a new HTTP request. On a
  21762. // vulnerable server the keep-alive loop reads this as a second request. The
  21763. // server may already have closed the connection, so the result is ignored.
  21764. send(sock, smuggled.data(), smuggled.size(), 0);
  21765. // Half-close so that a server which drained the body sees EOF and closes,
  21766. // instead of the read below waiting for the read timeout.
  21767. #ifdef _WIN32
  21768. ::shutdown(sock, SD_SEND);
  21769. #else
  21770. ::shutdown(sock, SHUT_WR);
  21771. #endif
  21772. // Step 4: Read until the server closes the connection
  21773. for (;;) {
  21774. auto n = recv(sock, buf, sizeof(buf), 0);
  21775. if (n <= 0) break;
  21776. }
  21777. return smuggled_count.load();
  21778. }
  21779. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21780. // A GET request with Content-Length to a static file handler must have its
  21781. // body drained before the keep-alive connection is reused. Otherwise the
  21782. // unread body bytes are interpreted as the next HTTP request.
  21783. std::string first_response;
  21784. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21785. "Host: localhost\r\n"
  21786. "Content-Length: {len}\r\n"
  21787. "\r\n",
  21788. first_response));
  21789. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  21790. }
  21791. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  21792. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  21793. // be answered with 400 and the connection closed. Treating it as "no body"
  21794. // leaves the body to be parsed as the next request.
  21795. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  21796. const char *targets[] = {
  21797. "GET /file", // handler that never reads the body
  21798. "GET /not-found", // no handler matches (404)
  21799. "POST /post", // handler that reads the body
  21800. };
  21801. for (auto target : targets) {
  21802. for (auto value : values) {
  21803. std::string first_response;
  21804. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  21805. " HTTP/1.1\r\n"
  21806. "Host: localhost\r\n"
  21807. "Content-Length: " +
  21808. value + "\r\n\r\n",
  21809. first_response))
  21810. << target << " with Content-Length: " << value;
  21811. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  21812. << target << " with Content-Length: " << value;
  21813. }
  21814. }
  21815. }
  21816. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  21817. // A 400 for an unparseable request line leaves the rest of the message
  21818. // unread, so the connection must be closed rather than reused.
  21819. std::string first_response;
  21820. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  21821. "Host: localhost\r\n"
  21822. "Content-Length: {len}\r\n"
  21823. "\r\n",
  21824. first_response));
  21825. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21826. }
  21827. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  21828. // Same as above for a header block that fails to parse.
  21829. std::string first_response;
  21830. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21831. "Host: localhost\r\n"
  21832. "Bad Header\r\n"
  21833. "Content-Length: {len}\r\n"
  21834. "\r\n",
  21835. first_response));
  21836. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21837. }
  21838. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  21839. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  21840. // server must not read another request on that connection, even when the
  21841. // request had no body to drain.
  21842. std::string first_response;
  21843. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  21844. "Host: localhost\r\n"
  21845. "\r\n",
  21846. first_response));
  21847. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  21848. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  21849. }
  21850. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21851. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21852. // must be rejected with 400 Bad Request.
  21853. Server svr;
  21854. svr.Post("/test", [&](const Request &, Response &res) {
  21855. res.set_content("ok", "text/plain");
  21856. });
  21857. thread t = thread([&] { svr.listen(HOST, PORT); });
  21858. auto se = detail::scope_exit([&] {
  21859. svr.stop();
  21860. t.join();
  21861. ASSERT_FALSE(svr.is_running());
  21862. });
  21863. svr.wait_until_ready();
  21864. // Exact "chunked"
  21865. {
  21866. auto req = "POST /test HTTP/1.1\r\n"
  21867. "Host: localhost\r\n"
  21868. "Content-Length: 5\r\n"
  21869. "Transfer-Encoding: chunked\r\n"
  21870. "Connection: close\r\n"
  21871. "\r\n"
  21872. "hello";
  21873. std::string response;
  21874. ASSERT_TRUE(send_request(1, req, &response));
  21875. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21876. response.substr(0, response.find("\r\n")));
  21877. }
  21878. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21879. {
  21880. auto req = "POST /test HTTP/1.1\r\n"
  21881. "Host: localhost\r\n"
  21882. "Content-Length: 5\r\n"
  21883. "Transfer-Encoding: gzip, chunked\r\n"
  21884. "Connection: close\r\n"
  21885. "\r\n"
  21886. "hello";
  21887. std::string response;
  21888. ASSERT_TRUE(send_request(1, req, &response));
  21889. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21890. response.substr(0, response.find("\r\n")));
  21891. }
  21892. }
  21893. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21894. Server svr;
  21895. svr.Post("/test", [&](const Request &, Response &res) {
  21896. res.set_content("ok", "text/plain");
  21897. });
  21898. thread t = thread([&] { svr.listen(HOST, PORT); });
  21899. auto se = detail::scope_exit([&] {
  21900. svr.stop();
  21901. t.join();
  21902. ASSERT_FALSE(svr.is_running());
  21903. });
  21904. svr.wait_until_ready();
  21905. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  21906. // length cannot be determined, so the server must answer 400 and close
  21907. // rather than treat the request as bodyless and leave the body in the
  21908. // socket for the next request to pick up.
  21909. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  21910. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  21911. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  21912. std::string response;
  21913. ASSERT_TRUE(send_request(1, req, &response));
  21914. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21915. response.substr(0, response.find("\r\n")))
  21916. << transfer_encoding;
  21917. }
  21918. // RFC 9110 5.3: the codings may also be split across several
  21919. // Transfer-Encoding lines, which combine in the order they were received.
  21920. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  21921. // just like the single-line "chunked, gzip" above.
  21922. {
  21923. auto req = "POST /test HTTP/1.1\r\n"
  21924. "Host: localhost\r\n"
  21925. "Transfer-Encoding: chunked\r\n"
  21926. "Transfer-Encoding: gzip\r\n"
  21927. "\r\n"
  21928. "0\r\n\r\n";
  21929. std::string response;
  21930. ASSERT_TRUE(send_request(1, req, &response));
  21931. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21932. response.substr(0, response.find("\r\n")));
  21933. }
  21934. // A sequence ending in chunked stays valid.
  21935. auto req = "POST /test HTTP/1.1\r\n"
  21936. "Host: localhost\r\n"
  21937. "Transfer-Encoding: gzip, chunked\r\n"
  21938. "Connection: close\r\n"
  21939. "\r\n"
  21940. "0\r\n\r\n";
  21941. std::string response;
  21942. ASSERT_TRUE(send_request(1, req, &response));
  21943. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21944. // ...including when it is spread over several lines.
  21945. auto split_req = "POST /test HTTP/1.1\r\n"
  21946. "Host: localhost\r\n"
  21947. "Transfer-Encoding: gzip\r\n"
  21948. "Transfer-Encoding: chunked\r\n"
  21949. "Connection: close\r\n"
  21950. "\r\n"
  21951. "0\r\n\r\n";
  21952. std::string split_response;
  21953. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21954. EXPECT_EQ("HTTP/1.1 200 OK",
  21955. split_response.substr(0, split_response.find("\r\n")));
  21956. }
  21957. // Regression for issue #2450: a DELETE without Content-Length on a
  21958. // keep-alive connection must not let the post-response drain consume the
  21959. // next request's bytes.
  21960. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21961. Server svr;
  21962. std::atomic<int> delete_count(0);
  21963. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21964. delete_count++;
  21965. res.status = StatusCode::NoContent_204;
  21966. });
  21967. auto port = svr.bind_to_any_port(HOST);
  21968. thread t = thread([&] { svr.listen_after_bind(); });
  21969. auto se = detail::scope_exit([&] {
  21970. svr.stop();
  21971. t.join();
  21972. });
  21973. svr.wait_until_ready();
  21974. auto error = Error::Success;
  21975. auto sock = detail::create_client_socket(
  21976. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21977. /*connection_timeout_sec=*/2, 0,
  21978. /*read_timeout_sec=*/2, 0,
  21979. /*write_timeout_sec=*/2, 0, std::string(), error);
  21980. ASSERT_NE(INVALID_SOCKET, sock);
  21981. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21982. auto send_request_and_read_response = [&](const std::string &req,
  21983. std::string &out) -> bool {
  21984. auto sent = send(sock, req.data(), req.size(), 0);
  21985. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21986. char buf[4096];
  21987. for (;;) {
  21988. auto n = recv(sock, buf, sizeof(buf), 0);
  21989. if (n <= 0) { return !out.empty(); }
  21990. out.append(buf, static_cast<size_t>(n));
  21991. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21992. }
  21993. };
  21994. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21995. "Host: localhost\r\n"
  21996. "\r\n";
  21997. std::string resp1;
  21998. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21999. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22000. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22001. "Host: localhost\r\n"
  22002. "Connection: close\r\n"
  22003. "\r\n";
  22004. std::string resp2;
  22005. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22006. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22007. EXPECT_EQ(2, delete_count.load());
  22008. }
  22009. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22010. Server svr;
  22011. svr.Post("/ingest", [&](const Request &, Response &res,
  22012. const ContentReader &content_reader) {
  22013. auto consumed = content_reader([](const char *, size_t) { return false; });
  22014. EXPECT_FALSE(consumed);
  22015. res.status = StatusCode::Conflict_409;
  22016. res.set_header("Connection", "close");
  22017. });
  22018. auto port = svr.bind_to_any_port(HOST);
  22019. thread t = thread([&] { svr.listen_after_bind(); });
  22020. auto se = detail::scope_exit([&] {
  22021. svr.stop();
  22022. t.join();
  22023. });
  22024. svr.wait_until_ready();
  22025. auto error = Error::Success;
  22026. auto sock = detail::create_client_socket(
  22027. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22028. /*connection_timeout_sec=*/2, 0,
  22029. /*read_timeout_sec=*/1, 0,
  22030. /*write_timeout_sec=*/2, 0, std::string(), error);
  22031. ASSERT_NE(INVALID_SOCKET, sock);
  22032. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22033. std::string request = "POST /ingest HTTP/1.1\r\n"
  22034. "Host: localhost\r\n"
  22035. "Transfer-Encoding: chunked\r\n"
  22036. "\r\n"
  22037. "4\r\n"
  22038. "data\r\n";
  22039. auto sent = send(sock, request.data(), request.size(), 0);
  22040. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22041. std::string response;
  22042. ssize_t received = 0;
  22043. do {
  22044. char buf[4096];
  22045. received = recv(sock, buf, sizeof(buf), 0);
  22046. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22047. } while (received > 0);
  22048. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22049. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22050. EXPECT_EQ(0, received);
  22051. }
  22052. namespace no_proxy_test {
  22053. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22054. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22055. // calling listen().
  22056. class ScopedServer {
  22057. public:
  22058. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22059. ~ScopedServer() {
  22060. svr_.stop();
  22061. if (th_.joinable()) { th_.join(); }
  22062. }
  22063. Server &svr() { return svr_; }
  22064. int port() const { return port_; }
  22065. void listen() {
  22066. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22067. svr_.wait_until_ready();
  22068. }
  22069. private:
  22070. Server svr_;
  22071. std::thread th_;
  22072. int port_ = 0;
  22073. };
  22074. class ProxyAndTargetServers {
  22075. public:
  22076. ProxyAndTargetServers() {
  22077. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22078. proxy_hits_++;
  22079. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22080. res.set_content("via-proxy", "text/plain");
  22081. });
  22082. target_.Get(".*", [this](const Request &req, Response &res) {
  22083. target_hits_++;
  22084. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22085. res.set_content("direct", "text/plain");
  22086. });
  22087. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22088. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22089. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22090. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22091. proxy_mock_.wait_until_ready();
  22092. target_.wait_until_ready();
  22093. }
  22094. ~ProxyAndTargetServers() {
  22095. proxy_mock_.stop();
  22096. target_.stop();
  22097. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22098. if (target_thread_.joinable()) { target_thread_.join(); }
  22099. }
  22100. Server &proxy_mock() { return proxy_mock_; }
  22101. Server &target() { return target_; }
  22102. int proxy_port() const { return proxy_port_; }
  22103. int target_port() const { return target_port_; }
  22104. int proxy_hits() const { return proxy_hits_.load(); }
  22105. int target_hits() const { return target_hits_.load(); }
  22106. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22107. void reset_counters() {
  22108. proxy_hits_ = 0;
  22109. target_hits_ = 0;
  22110. last_had_proxy_authz_ = false;
  22111. }
  22112. private:
  22113. Server proxy_mock_;
  22114. Server target_;
  22115. std::thread proxy_thread_;
  22116. std::thread target_thread_;
  22117. int proxy_port_ = 0;
  22118. int target_port_ = 0;
  22119. std::atomic<int> proxy_hits_{0};
  22120. std::atomic<int> target_hits_{0};
  22121. std::atomic<bool> last_had_proxy_authz_{false};
  22122. };
  22123. inline std::unique_ptr<Client> make_client(const std::string &host,
  22124. ProxyAndTargetServers &s) {
  22125. auto cli = detail::make_unique<Client>(host, s.target_port());
  22126. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22127. cli->set_proxy("127.0.0.1", s.proxy_port());
  22128. return cli;
  22129. }
  22130. } // namespace no_proxy_test
  22131. using no_proxy_test::make_client;
  22132. using no_proxy_test::ProxyAndTargetServers;
  22133. TEST(NoProxyTest, ExactHostnameBypasses) {
  22134. ProxyAndTargetServers s;
  22135. auto cli = make_client("example.com", s);
  22136. cli->set_no_proxy({"example.com"});
  22137. auto res = cli->Get("/");
  22138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22139. EXPECT_EQ(0, s.proxy_hits());
  22140. EXPECT_EQ(1, s.target_hits());
  22141. }
  22142. TEST(NoProxyTest, SubdomainBypasses) {
  22143. ProxyAndTargetServers s;
  22144. auto cli = make_client("foo.example.com", s);
  22145. cli->set_no_proxy({"example.com"});
  22146. auto res = cli->Get("/");
  22147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22148. EXPECT_EQ(0, s.proxy_hits());
  22149. EXPECT_EQ(1, s.target_hits());
  22150. }
  22151. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  22152. // Regression guard: "evilexample.com" must not be considered a subdomain
  22153. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22154. // check would let traffic bypass the proxy and leak credentials direct
  22155. // to the attacker host.
  22156. ProxyAndTargetServers s;
  22157. auto cli = make_client("evilexample.com", s);
  22158. cli->set_no_proxy({"example.com"});
  22159. auto res = cli->Get("/");
  22160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22161. EXPECT_GE(s.proxy_hits(), 1);
  22162. EXPECT_EQ(0, s.target_hits());
  22163. }
  22164. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22165. ProxyAndTargetServers s;
  22166. auto cli = make_client("example.com.evil.com", s);
  22167. cli->set_no_proxy({"example.com"});
  22168. auto res = cli->Get("/");
  22169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22170. EXPECT_GE(s.proxy_hits(), 1);
  22171. EXPECT_EQ(0, s.target_hits());
  22172. }
  22173. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22174. ProxyAndTargetServers s;
  22175. auto cli = make_client("example.com", s);
  22176. cli->set_no_proxy({".example.com"});
  22177. auto res = cli->Get("/");
  22178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22179. EXPECT_EQ(0, s.proxy_hits());
  22180. EXPECT_EQ(1, s.target_hits());
  22181. }
  22182. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22183. ProxyAndTargetServers s;
  22184. auto cli = make_client("Example.COM", s);
  22185. cli->set_no_proxy({"EXAMPLE.com"});
  22186. auto res = cli->Get("/");
  22187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22188. EXPECT_EQ(0, s.proxy_hits());
  22189. EXPECT_EQ(1, s.target_hits());
  22190. }
  22191. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22192. ProxyAndTargetServers s;
  22193. auto cli = make_client("example.com.", s);
  22194. cli->set_no_proxy({"example.com"});
  22195. auto res = cli->Get("/");
  22196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22197. EXPECT_EQ(0, s.proxy_hits());
  22198. EXPECT_EQ(1, s.target_hits());
  22199. }
  22200. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22201. // Trailing dots must be normalized on BOTH sides — host and entry.
  22202. // An implementation that only strips the host-side trailing dot would
  22203. // fail to match host "example.com" against entry "example.com." because
  22204. // a literal substring search would compare 11 chars against 12.
  22205. ProxyAndTargetServers s;
  22206. auto cli = make_client("example.com", s);
  22207. cli->set_no_proxy({"example.com."});
  22208. auto res = cli->Get("/");
  22209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22210. EXPECT_EQ(0, s.proxy_hits());
  22211. EXPECT_EQ(1, s.target_hits());
  22212. }
  22213. TEST(NoProxyTest, WildcardBypassesEverything) {
  22214. ProxyAndTargetServers s;
  22215. auto cli = make_client("anything.invalid.test", s);
  22216. cli->set_no_proxy({"*"});
  22217. auto res = cli->Get("/");
  22218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22219. EXPECT_EQ(0, s.proxy_hits());
  22220. EXPECT_EQ(1, s.target_hits());
  22221. }
  22222. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22223. ProxyAndTargetServers s;
  22224. Client cli("127.0.0.1", s.target_port());
  22225. cli.set_proxy("127.0.0.1", s.proxy_port());
  22226. cli.set_no_proxy({"127.0.0.1"});
  22227. auto res = cli.Get("/");
  22228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22229. EXPECT_EQ(0, s.proxy_hits());
  22230. EXPECT_EQ(1, s.target_hits());
  22231. }
  22232. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22233. ProxyAndTargetServers s;
  22234. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22235. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22236. cli.set_proxy("127.0.0.1", s.proxy_port());
  22237. cli.set_no_proxy({"::1"});
  22238. auto res = cli.Get("/");
  22239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22240. EXPECT_EQ(0, s.proxy_hits());
  22241. EXPECT_EQ(1, s.target_hits());
  22242. }
  22243. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22244. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22245. // must still be recognized as IPv6 for CIDR matching. Implementations
  22246. // that detect IPv6 only when the host begins with '[' would parse the
  22247. // host as a hostname and miss the match.
  22248. ProxyAndTargetServers s;
  22249. Client cli("fe80::1", s.target_port());
  22250. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22251. cli.set_proxy("127.0.0.1", s.proxy_port());
  22252. cli.set_no_proxy({"fe80::/10"});
  22253. auto res = cli.Get("/");
  22254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22255. EXPECT_EQ(0, s.proxy_hits());
  22256. EXPECT_EQ(1, s.target_hits());
  22257. }
  22258. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22259. ProxyAndTargetServers s;
  22260. Client cli("::1", s.target_port());
  22261. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22262. cli.set_proxy("127.0.0.1", s.proxy_port());
  22263. cli.set_no_proxy({"[::1]"});
  22264. auto res = cli.Get("/");
  22265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22266. EXPECT_EQ(0, s.proxy_hits());
  22267. EXPECT_EQ(1, s.target_hits());
  22268. }
  22269. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  22270. ProxyAndTargetServers s;
  22271. Client cli("fe80::1", s.target_port());
  22272. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22273. cli.set_proxy("127.0.0.1", s.proxy_port());
  22274. cli.set_no_proxy({"[fe80::]/10"});
  22275. auto res = cli.Get("/");
  22276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22277. EXPECT_EQ(0, s.proxy_hits());
  22278. EXPECT_EQ(1, s.target_hits());
  22279. }
  22280. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22281. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22282. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22283. // tricks via address-family conversion.
  22284. ProxyAndTargetServers s;
  22285. Client cli("::ffff:127.0.0.1", s.target_port());
  22286. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22287. cli.set_proxy("127.0.0.1", s.proxy_port());
  22288. cli.set_no_proxy({"127.0.0.1"});
  22289. auto res = cli.Get("/");
  22290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22291. EXPECT_GE(s.proxy_hits(), 1);
  22292. EXPECT_EQ(0, s.target_hits());
  22293. }
  22294. TEST(NoProxyTest, IPv4CidrMatch) {
  22295. ProxyAndTargetServers s;
  22296. Client cli("127.0.0.1", s.target_port());
  22297. cli.set_proxy("127.0.0.1", s.proxy_port());
  22298. cli.set_no_proxy({"127.0.0.0/8"});
  22299. auto res = cli.Get("/");
  22300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22301. EXPECT_EQ(0, s.proxy_hits());
  22302. EXPECT_EQ(1, s.target_hits());
  22303. }
  22304. TEST(NoProxyTest, IPv4CidrNonMatch) {
  22305. ProxyAndTargetServers s;
  22306. Client cli("127.0.0.1", s.target_port());
  22307. cli.set_proxy("127.0.0.1", s.proxy_port());
  22308. cli.set_no_proxy({"10.0.0.0/8"});
  22309. auto res = cli.Get("/");
  22310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22311. EXPECT_GE(s.proxy_hits(), 1);
  22312. EXPECT_EQ(0, s.target_hits());
  22313. }
  22314. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  22315. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  22316. // IPv4 target matches.
  22317. ProxyAndTargetServers s;
  22318. Client cli("127.0.0.1", s.target_port());
  22319. cli.set_proxy("127.0.0.1", s.proxy_port());
  22320. cli.set_no_proxy({"0.0.0.0/0"});
  22321. auto res = cli.Get("/");
  22322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22323. EXPECT_EQ(0, s.proxy_hits());
  22324. EXPECT_EQ(1, s.target_hits());
  22325. }
  22326. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  22327. ProxyAndTargetServers s;
  22328. Client cli("127.0.0.1", s.target_port());
  22329. cli.set_proxy("127.0.0.1", s.proxy_port());
  22330. cli.set_no_proxy({"127.0.0.1"});
  22331. auto res = cli.Get("/");
  22332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22333. EXPECT_EQ(0, s.proxy_hits());
  22334. EXPECT_EQ(1, s.target_hits());
  22335. }
  22336. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  22337. ProxyAndTargetServers s;
  22338. Client cli("127.0.0.1", s.target_port());
  22339. cli.set_proxy("127.0.0.1", s.proxy_port());
  22340. cli.set_no_proxy({"127.0.0.0/33"});
  22341. auto res = cli.Get("/");
  22342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22343. EXPECT_GE(s.proxy_hits(), 1);
  22344. EXPECT_EQ(0, s.target_hits());
  22345. }
  22346. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  22347. // Empty prefix after the slash must be rejected, not silently treated as /32.
  22348. ProxyAndTargetServers s;
  22349. Client cli("127.0.0.1", s.target_port());
  22350. cli.set_proxy("127.0.0.1", s.proxy_port());
  22351. cli.set_no_proxy({"127.0.0.1/"});
  22352. auto res = cli.Get("/");
  22353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22354. EXPECT_GE(s.proxy_hits(), 1);
  22355. EXPECT_EQ(0, s.target_hits());
  22356. }
  22357. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  22358. ProxyAndTargetServers s;
  22359. auto cli = make_client("internal.corp", s);
  22360. cli->set_proxy_basic_auth("u", "p");
  22361. cli->set_no_proxy({"internal.corp"});
  22362. auto res = cli->Get("/");
  22363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22364. EXPECT_EQ(1, s.target_hits());
  22365. EXPECT_EQ(0, s.proxy_hits());
  22366. EXPECT_FALSE(s.last_had_proxy_authz())
  22367. << "Proxy-Authorization must not be sent direct to the target";
  22368. }
  22369. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  22370. ProxyAndTargetServers s;
  22371. auto cli = make_client("public.example", s);
  22372. cli->set_proxy_basic_auth("u", "p");
  22373. cli->set_no_proxy({"internal.corp"}); // does not match
  22374. auto res = cli->Get("/");
  22375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22376. EXPECT_GE(s.proxy_hits(), 1);
  22377. EXPECT_TRUE(s.last_had_proxy_authz());
  22378. }
  22379. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  22380. ProxyAndTargetServers s;
  22381. auto cli = make_client("anything.test", s);
  22382. auto res = cli->Get("/");
  22383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22384. EXPECT_GE(s.proxy_hits(), 1);
  22385. EXPECT_EQ(0, s.target_hits());
  22386. }
  22387. TEST(NoProxyTest, PortSpecificEntryRejected) {
  22388. ProxyAndTargetServers s;
  22389. auto cli = make_client("example.com", s);
  22390. cli->set_no_proxy({"example.com:8080"});
  22391. auto res = cli->Get("/");
  22392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22393. EXPECT_GE(s.proxy_hits(), 1);
  22394. EXPECT_EQ(0, s.target_hits());
  22395. }
  22396. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  22397. ProxyAndTargetServers s;
  22398. auto cli = make_client("anything.test", s);
  22399. cli->set_no_proxy({"", " ", "\t"});
  22400. auto res = cli->Get("/");
  22401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22402. EXPECT_GE(s.proxy_hits(), 1);
  22403. EXPECT_EQ(0, s.target_hits());
  22404. }
  22405. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  22406. // An entry with leading/trailing whitespace must still match — env-style
  22407. // values are commonly pasted with stray spaces and an implementation
  22408. // that feeds the raw token directly to inet_pton would fail to match
  22409. // valid CIDRs because of the spaces.
  22410. ProxyAndTargetServers s;
  22411. Client cli("127.0.0.1", s.target_port());
  22412. cli.set_proxy("127.0.0.1", s.proxy_port());
  22413. cli.set_no_proxy({" 127.0.0.0/8 "});
  22414. auto res = cli.Get("/");
  22415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22416. EXPECT_EQ(0, s.proxy_hits());
  22417. EXPECT_EQ(1, s.target_hits());
  22418. }
  22419. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  22420. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  22421. // go direct and must NOT carry Proxy-Authorization.
  22422. std::atomic<int> proxy_hits{0};
  22423. std::atomic<int> target_hits{0};
  22424. std::atomic<bool> target_saw_authz{false};
  22425. no_proxy_test::ScopedServer proxy_mock, target;
  22426. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22427. proxy_hits++;
  22428. res.status = 302;
  22429. res.set_header("Location", "http://127.0.0.1:" +
  22430. std::to_string(target.port()) + "/landed");
  22431. });
  22432. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22433. target_hits++;
  22434. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  22435. res.set_content("direct", "text/plain");
  22436. });
  22437. proxy_mock.listen();
  22438. target.listen();
  22439. Client cli("public.example", target.port());
  22440. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22441. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22442. cli.set_proxy_basic_auth("u", "p");
  22443. cli.set_no_proxy({"127.0.0.1"});
  22444. cli.set_follow_location(true);
  22445. auto res = cli.Get("/redir");
  22446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22447. EXPECT_GE(proxy_hits.load(), 1);
  22448. EXPECT_GE(target_hits.load(), 1);
  22449. EXPECT_FALSE(target_saw_authz.load());
  22450. }
  22451. #ifdef CPPHTTPLIB_SSL_ENABLED
  22452. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  22453. // Direct origin replying 407 must not trigger the digest retry; otherwise
  22454. // proxy creds would be sent to the (possibly hostile) origin.
  22455. std::atomic<int> target_hits{0};
  22456. std::atomic<bool> target_saw_proxy_authz{false};
  22457. no_proxy_test::ScopedServer target;
  22458. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22459. target_hits++;
  22460. if (req.has_header("Proxy-Authorization")) {
  22461. target_saw_proxy_authz = true;
  22462. }
  22463. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22464. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  22465. "nonce=\"abc\", algorithm=MD5");
  22466. });
  22467. target.listen();
  22468. // The proxy address is set to the target's port: the bypass MUST kick in;
  22469. // if it doesn't, the test still routes "via proxy" to the same server and
  22470. // the Proxy-Authorization assertion below catches the leak.
  22471. Client cli("evil.example", target.port());
  22472. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  22473. cli.set_proxy("127.0.0.1", target.port());
  22474. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22475. cli.set_no_proxy({"evil.example"});
  22476. auto res = cli.Get("/x");
  22477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22478. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22479. EXPECT_EQ(1, target_hits.load());
  22480. EXPECT_FALSE(target_saw_proxy_authz.load());
  22481. }
  22482. #endif
  22483. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  22484. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  22485. std::atomic<int> proxy_hits{0};
  22486. std::atomic<int> bypass_hits{0};
  22487. std::atomic<bool> proxy_saw_c_url{false};
  22488. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  22489. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22490. proxy_hits++;
  22491. if (req.path.find("/start") != std::string::npos) {
  22492. res.status = 302;
  22493. res.set_header("Location", "http://127.0.0.1:" +
  22494. std::to_string(bypass_server.port()) +
  22495. "/middle");
  22496. return;
  22497. }
  22498. if (req.path.find("/end") != std::string::npos) {
  22499. proxy_saw_c_url = true;
  22500. res.set_content("c-via-proxy", "text/plain");
  22501. return;
  22502. }
  22503. res.set_content("unexpected", "text/plain");
  22504. });
  22505. // public.example's "advertised" port is arbitrary (the request never lands
  22506. // there — it goes through the proxy), but use a dynamic value to stay
  22507. // friendly with sharded parallel runs.
  22508. int public_port = bypass_server.port();
  22509. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  22510. bypass_hits++;
  22511. res.status = 302;
  22512. res.set_header("Location", "http://public.example:" +
  22513. std::to_string(public_port) + "/end");
  22514. });
  22515. proxy_mock.listen();
  22516. bypass_server.listen();
  22517. Client cli("public.example", public_port);
  22518. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22519. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22520. cli.set_no_proxy({"127.0.0.1"});
  22521. cli.set_follow_location(true);
  22522. auto res = cli.Get("/start");
  22523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22524. EXPECT_EQ(StatusCode::OK_200, res->status);
  22525. EXPECT_EQ("c-via-proxy", res->body);
  22526. EXPECT_GE(proxy_hits.load(), 2);
  22527. EXPECT_GE(bypass_hits.load(), 1);
  22528. EXPECT_TRUE(proxy_saw_c_url.load());
  22529. }
  22530. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  22531. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  22532. // request reconnects to the correct endpoint.
  22533. std::atomic<int> proxy_hits{0};
  22534. std::atomic<int> target_hits{0};
  22535. no_proxy_test::ScopedServer proxy_mock, target;
  22536. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22537. proxy_hits++;
  22538. res.set_content("via-proxy", "text/plain");
  22539. });
  22540. target.svr().Get(".*", [&](const Request &, Response &res) {
  22541. target_hits++;
  22542. res.set_content("direct", "text/plain");
  22543. });
  22544. proxy_mock.listen();
  22545. target.listen();
  22546. Client cli("public.example", target.port());
  22547. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22548. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22549. cli.set_keep_alive(true);
  22550. auto res1 = cli.Get("/a");
  22551. ASSERT_TRUE(res1);
  22552. EXPECT_EQ("via-proxy", res1->body);
  22553. EXPECT_EQ(1, proxy_hits.load());
  22554. EXPECT_EQ(0, target_hits.load());
  22555. cli.set_no_proxy({"public.example"});
  22556. auto res2 = cli.Get("/b");
  22557. ASSERT_TRUE(res2);
  22558. EXPECT_EQ("direct", res2->body);
  22559. EXPECT_EQ(1, proxy_hits.load());
  22560. EXPECT_EQ(1, target_hits.load());
  22561. }
  22562. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  22563. namespace proxy_tunnel_test {
  22564. // SSLServer counterpart to no_proxy_test::ScopedServer.
  22565. class ScopedSSLServer {
  22566. public:
  22567. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  22568. port_ = svr_.bind_to_any_port("127.0.0.1");
  22569. }
  22570. ~ScopedSSLServer() {
  22571. svr_.stop();
  22572. if (th_.joinable()) { th_.join(); }
  22573. }
  22574. SSLServer &svr() { return svr_; }
  22575. int port() const { return port_; }
  22576. void listen() {
  22577. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22578. svr_.wait_until_ready();
  22579. }
  22580. private:
  22581. SSLServer svr_;
  22582. std::thread th_;
  22583. int port_ = 0;
  22584. };
  22585. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  22586. class ScopedConnectProxy {
  22587. public:
  22588. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  22589. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  22590. if (listen_fd_ < 0) { return; }
  22591. int yes = 1;
  22592. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  22593. sockaddr_in a{};
  22594. a.sin_family = AF_INET;
  22595. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22596. a.sin_port = 0;
  22597. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  22598. return;
  22599. }
  22600. socklen_t alen = sizeof(a);
  22601. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  22602. 0) {
  22603. return;
  22604. }
  22605. port_ = ntohs(a.sin_port);
  22606. if (::listen(listen_fd_, 1) != 0) { return; }
  22607. th_ = std::thread([this] { run(); });
  22608. }
  22609. ~ScopedConnectProxy() {
  22610. stop_ = true;
  22611. if (listen_fd_ >= 0) {
  22612. ::shutdown(listen_fd_, SHUT_RDWR);
  22613. ::close(listen_fd_);
  22614. }
  22615. if (th_.joinable()) { th_.join(); }
  22616. }
  22617. int port() const { return port_; }
  22618. int connect_hits() const { return connect_hits_.load(); }
  22619. // Head of the last CONNECT request, as the proxy saw it on the wire.
  22620. std::string connect_request() const {
  22621. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22622. return connect_request_;
  22623. }
  22624. private:
  22625. void run() {
  22626. while (!stop_.load()) {
  22627. fd_set rfds;
  22628. FD_ZERO(&rfds);
  22629. FD_SET(listen_fd_, &rfds);
  22630. timeval tv{0, 100 * 1000};
  22631. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  22632. if (sel <= 0) { continue; }
  22633. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  22634. if (client_fd < 0) { continue; }
  22635. std::string req;
  22636. char buf[2048];
  22637. while (req.find("\r\n\r\n") == std::string::npos) {
  22638. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  22639. if (n <= 0) { break; }
  22640. req.append(buf, static_cast<size_t>(n));
  22641. }
  22642. if (req.compare(0, 7, "CONNECT") != 0) {
  22643. ::close(client_fd);
  22644. continue;
  22645. }
  22646. connect_hits_++;
  22647. {
  22648. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22649. connect_request_ = req;
  22650. }
  22651. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  22652. ::send(client_fd, ok, std::strlen(ok), 0);
  22653. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  22654. sockaddr_in o{};
  22655. o.sin_family = AF_INET;
  22656. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22657. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  22658. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  22659. 0) {
  22660. ::close(client_fd);
  22661. ::close(origin_fd);
  22662. continue;
  22663. }
  22664. auto forward = [](int from, int to) {
  22665. char b[8192];
  22666. for (;;) {
  22667. ssize_t n = ::recv(from, b, sizeof(b), 0);
  22668. if (n <= 0) { break; }
  22669. ssize_t off = 0;
  22670. while (off < n) {
  22671. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  22672. if (s <= 0) {
  22673. off = n;
  22674. break;
  22675. }
  22676. off += s;
  22677. }
  22678. }
  22679. ::shutdown(to, SHUT_WR);
  22680. };
  22681. std::thread t1([&] { forward(client_fd, origin_fd); });
  22682. std::thread t2([&] { forward(origin_fd, client_fd); });
  22683. t1.join();
  22684. t2.join();
  22685. ::close(client_fd);
  22686. ::close(origin_fd);
  22687. }
  22688. }
  22689. int forward_port_ = -1;
  22690. int listen_fd_ = -1;
  22691. int port_ = 0;
  22692. std::thread th_;
  22693. std::atomic<bool> stop_{false};
  22694. std::atomic<int> connect_hits_{0};
  22695. mutable std::mutex connect_request_mutex_;
  22696. std::string connect_request_;
  22697. };
  22698. // Sends one request through the CONNECT proxy to the TLS origin with a
  22699. // credential configured for each hop, and checks that each credential reaches
  22700. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22701. // origin's (every header in origin_headers) on the tunnelled request.
  22702. void CredentialsStayWithTheirHop(
  22703. const std::function<void(SSLClient &)> &set_credentials,
  22704. const std::string &scheme,
  22705. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22706. std::atomic<int> origin_hits{0};
  22707. std::atomic<bool> origin_saw_proxy_authz{false};
  22708. std::atomic<bool> origin_saw_headers{false};
  22709. ScopedSSLServer origin;
  22710. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22711. origin_hits++;
  22712. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22713. origin_saw_headers =
  22714. std::all_of(origin_headers.begin(), origin_headers.end(),
  22715. [&](const std::string &h) { return req.has_header(h); });
  22716. res.set_content("ok", "text/plain");
  22717. });
  22718. origin.listen();
  22719. ScopedConnectProxy proxy(origin.port());
  22720. ASSERT_NE(0, proxy.port());
  22721. // Pinned to 127.0.0.1 for the same reason as the test below.
  22722. SSLClient cli("127.0.0.1", origin.port());
  22723. cli.enable_server_certificate_verification(false);
  22724. cli.set_proxy("127.0.0.1", proxy.port());
  22725. set_credentials(cli);
  22726. auto res = cli.Get("/x");
  22727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22728. EXPECT_EQ(StatusCode::OK_200, res->status);
  22729. EXPECT_EQ(1, origin_hits.load());
  22730. EXPECT_EQ(1, proxy.connect_hits());
  22731. EXPECT_TRUE(origin_saw_headers.load());
  22732. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22733. << "Proxy-Authorization must not be sent inside the tunnel";
  22734. auto connect_req = proxy.connect_request();
  22735. EXPECT_NE(std::string::npos,
  22736. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22737. for (const auto &h : origin_headers) {
  22738. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22739. << h << " must not be sent to the proxy on CONNECT";
  22740. }
  22741. }
  22742. } // namespace proxy_tunnel_test
  22743. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22744. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22745. [](SSLClient &cli) {
  22746. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22747. cli.set_basic_auth("origin-user", "origin-pass");
  22748. },
  22749. "Basic");
  22750. }
  22751. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22752. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22753. [](SSLClient &cli) {
  22754. cli.set_proxy_bearer_token_auth("proxy-token");
  22755. cli.set_bearer_token_auth("origin-token");
  22756. },
  22757. "Bearer");
  22758. }
  22759. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22760. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22761. [](SSLClient &cli) {
  22762. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22763. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22764. {"Cookie", "sid=origin-session"},
  22765. {"X-Api-Key", "origin-key"}});
  22766. },
  22767. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22768. }
  22769. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22770. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22771. // retry; otherwise proxy creds would be sent to the origin.
  22772. std::atomic<int> origin_hits{0};
  22773. std::atomic<bool> origin_saw_proxy_authz{false};
  22774. proxy_tunnel_test::ScopedSSLServer origin;
  22775. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22776. origin_hits++;
  22777. if (req.has_header("Proxy-Authorization")) {
  22778. origin_saw_proxy_authz = true;
  22779. }
  22780. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22781. res.set_header("Proxy-Authenticate",
  22782. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22783. "algorithm=MD5");
  22784. });
  22785. origin.listen();
  22786. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22787. ASSERT_NE(0, proxy.port());
  22788. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22789. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22790. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22791. // and answer with its own status, making this test flaky.
  22792. SSLClient cli("127.0.0.1", origin.port());
  22793. cli.enable_server_certificate_verification(false);
  22794. cli.set_proxy("127.0.0.1", proxy.port());
  22795. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22796. auto res = cli.Get("/x");
  22797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22798. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22799. EXPECT_EQ(1, origin_hits.load());
  22800. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22801. EXPECT_EQ(1, proxy.connect_hits());
  22802. }
  22803. #endif