test.cc 879 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165
  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 is a CryptoAPI
  11937. // policy status, which no backend reports for a self-signed certificate.
  11938. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  11939. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11940. ASSERT_TRUE(svr.is_valid());
  11941. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11942. auto se = detail::scope_exit([&] {
  11943. svr.stop();
  11944. t.join();
  11945. ASSERT_FALSE(svr.is_running());
  11946. });
  11947. svr.wait_until_ready();
  11948. SSLClient cli("127.0.0.1", PORT);
  11949. cli.set_connection_timeout(30);
  11950. auto res = cli.Get("/");
  11951. ASSERT_FALSE(res);
  11952. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11953. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  11954. }
  11955. #endif
  11956. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11957. Client cli("https://google.com");
  11958. auto res = cli.Get("/");
  11959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11960. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11961. }
  11962. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11963. SSLClient cli("google.com");
  11964. cli.set_ca_cert_path(CA_CERT_FILE);
  11965. auto res = cli.Get("/");
  11966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11967. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11968. }
  11969. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11970. SSLClient cli("google.com");
  11971. cli.enable_server_certificate_verification(true);
  11972. cli.set_ca_cert_path("hello");
  11973. auto res = cli.Get("/");
  11974. ASSERT_TRUE(!res);
  11975. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11976. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11977. // should be set
  11978. EXPECT_EQ(0, res.ssl_error());
  11979. // Verify backend error is captured for SSLLoadingCerts
  11980. // This error occurs when loading CA certificates fails
  11981. EXPECT_NE(0UL, res.ssl_backend_error());
  11982. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11983. // OpenSSL specific error codes:
  11984. // > openssl errstr 0x80000002
  11985. // error:80000002:system library::No such file or directory
  11986. // > openssl errstr 0xA000126
  11987. // error:0A000126:SSL routines::unexpected eof while reading
  11988. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11989. res.ssl_backend_error() == 0xA000126);
  11990. #endif
  11991. }
  11992. TEST(SSLClientTest, ServerCertificateVerification4) {
  11993. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11994. ASSERT_TRUE(svr.is_valid());
  11995. svr.Get("/test", [&](const Request &, Response &res) {
  11996. res.set_content("test", "text/plain");
  11997. svr.stop();
  11998. ASSERT_TRUE(true);
  11999. });
  12000. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12001. auto se = detail::scope_exit([&] {
  12002. t.join();
  12003. ASSERT_FALSE(svr.is_running());
  12004. });
  12005. svr.wait_until_ready();
  12006. SSLClient cli("127.0.0.1", PORT);
  12007. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12008. cli.enable_server_certificate_verification(true);
  12009. cli.set_connection_timeout(30);
  12010. auto res = cli.Get("/test");
  12011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12012. ASSERT_EQ(StatusCode::OK_200, res->status);
  12013. }
  12014. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12015. std::string cert;
  12016. read_file(CA_CERT_FILE, cert);
  12017. SSLClient cli("google.com");
  12018. cli.load_ca_cert_store(cert.data(), cert.size());
  12019. const auto res = cli.Get("/");
  12020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12021. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12022. }
  12023. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12024. // clang-format off
  12025. static constexpr char cert[] =
  12026. "GlobalSign Root CA\n"
  12027. "==================\n"
  12028. "-----BEGIN CERTIFICATE-----\n"
  12029. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12030. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12031. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12032. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12033. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12034. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12035. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12036. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12037. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12038. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12039. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12040. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12041. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12042. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12043. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12044. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12045. "-----END CERTIFICATE-----\n";
  12046. // clang-format on
  12047. SSLClient cli("google.com");
  12048. cli.load_ca_cert_store(cert, sizeof(cert));
  12049. const auto res = cli.Get("/");
  12050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12051. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12052. }
  12053. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12054. SSLClient cli("www.youtube.com");
  12055. cli.set_ca_cert_path(CA_CERT_FILE);
  12056. cli.enable_server_certificate_verification(true);
  12057. cli.set_follow_location(true);
  12058. auto res = cli.Get("/");
  12059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12060. ASSERT_EQ(StatusCode::OK_200, res->status);
  12061. }
  12062. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12063. SSLClient cli("wWw.YouTube.Com");
  12064. cli.set_ca_cert_path(CA_CERT_FILE);
  12065. cli.enable_server_certificate_verification(true);
  12066. cli.enable_server_hostname_verification(true);
  12067. cli.set_follow_location(true);
  12068. auto res = cli.Get("/");
  12069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12070. ASSERT_EQ(StatusCode::OK_200, res->status);
  12071. }
  12072. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12073. SSLClient cli("gOoGlE.COm");
  12074. cli.enable_server_certificate_verification(true);
  12075. cli.enable_server_hostname_verification(true);
  12076. cli.set_follow_location(true);
  12077. auto res = cli.Get("/");
  12078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12079. ASSERT_EQ(StatusCode::OK_200, res->status);
  12080. }
  12081. TEST(SSLClientTest, Issue2004_Online) {
  12082. Client client("https://google.com");
  12083. client.set_follow_location(true);
  12084. auto res = client.Get("/");
  12085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12086. ASSERT_EQ(StatusCode::OK_200, res->status);
  12087. auto body = res->body;
  12088. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12089. }
  12090. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12091. // Create SSLClient with invalid cert/key to make is_valid() return false
  12092. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12093. "nonexistent_key.pem");
  12094. // is_valid() should be false due to cert loading failure
  12095. ASSERT_FALSE(cli.is_valid());
  12096. auto res = cli.Get("/");
  12097. ASSERT_FALSE(res);
  12098. EXPECT_EQ(Error::SSLConnection, res.error());
  12099. }
  12100. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12101. // Test for Issue #2251: SSL error not properly reported when client cert
  12102. // and key paths are swapped or mismatched
  12103. // This simulates the scenario where user accidentally swaps the cert and key
  12104. // files
  12105. // Using client cert file as private key and vice versa (completely wrong)
  12106. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12107. // Should fail validation due to cert/key mismatch
  12108. ASSERT_FALSE(cli.is_valid());
  12109. // Attempt to make a request should fail with proper error
  12110. auto res = cli.Get("/");
  12111. ASSERT_FALSE(res);
  12112. EXPECT_EQ(Error::SSLConnection, res.error());
  12113. // SSL error should be recorded in the Result object (this is the key fix for
  12114. // Issue #2251)
  12115. auto backend_error = res.ssl_backend_error();
  12116. EXPECT_NE(0u, backend_error);
  12117. }
  12118. // Tests cert/key mismatch detection at the TLS context level
  12119. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12120. // Test that using mismatched cert/key causes connection failure.
  12121. // We verify this at the SSLClient level rather than through internal
  12122. // TLS API functions.
  12123. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12124. cli.enable_server_certificate_verification(false);
  12125. cli.set_connection_timeout(2);
  12126. // The mismatch should cause a connection or handshake error
  12127. auto res = cli.Get("/test");
  12128. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12129. // Either way, the request should fail
  12130. EXPECT_FALSE(res);
  12131. }
  12132. #endif
  12133. #if 0
  12134. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12135. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12136. ASSERT_TRUE(cli != nullptr);
  12137. cli->set_address_family(AF_INET6);
  12138. cli->set_interface("en0");
  12139. auto res = cli->Get("/get");
  12140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12141. ASSERT_EQ(StatusCode::OK_200, res->status);
  12142. }
  12143. #endif
  12144. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12145. #ifdef CPPHTTPLIB_SSL_ENABLED
  12146. void ClientCertPresent(
  12147. const std::string &client_cert_file,
  12148. const std::string &client_private_key_file,
  12149. const std::string &client_encrypted_private_key_pass = std::string()) {
  12150. using namespace httplib::tls;
  12151. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12152. CLIENT_CA_CERT_DIR);
  12153. ASSERT_TRUE(svr.is_valid());
  12154. svr.Get("/test", [&](const Request &req, Response &res) {
  12155. res.set_content("test", "text/plain");
  12156. auto cert = req.peer_cert();
  12157. ASSERT_TRUE(static_cast<bool>(cert));
  12158. std::string common_name = cert.subject_cn();
  12159. EXPECT_EQ("Common Name", common_name);
  12160. });
  12161. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12162. auto se = detail::scope_exit([&] {
  12163. svr.stop();
  12164. t.join();
  12165. ASSERT_FALSE(svr.is_running());
  12166. });
  12167. svr.wait_until_ready();
  12168. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12169. client_encrypted_private_key_pass);
  12170. cli.enable_server_certificate_verification(false);
  12171. cli.set_connection_timeout(30);
  12172. auto res = cli.Get("/test");
  12173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12174. ASSERT_EQ(StatusCode::OK_200, res->status);
  12175. }
  12176. TEST(SSLClientServerTest, ClientCertPresent) {
  12177. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12178. }
  12179. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12180. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12181. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12182. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12183. }
  12184. // PEM memory-based constructor tests (works with all TLS backends)
  12185. void PemMemoryClientCertPresent(
  12186. const std::string &client_cert_file,
  12187. const std::string &client_private_key_file,
  12188. const std::string &client_encrypted_private_key_pass = std::string()) {
  12189. // Read PEM files into memory
  12190. std::string server_cert_pem, server_key_pem;
  12191. std::string client_ca_pem;
  12192. std::string client_cert_pem, client_key_pem;
  12193. read_file(SERVER_CERT_FILE, server_cert_pem);
  12194. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12195. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12196. read_file(client_cert_file, client_cert_pem);
  12197. read_file(client_private_key_file, client_key_pem);
  12198. // Create server with PEM memory
  12199. SSLServer::PemMemory server_pem = {
  12200. server_cert_pem.c_str(),
  12201. server_cert_pem.size(),
  12202. server_key_pem.c_str(),
  12203. server_key_pem.size(),
  12204. client_ca_pem.c_str(),
  12205. client_ca_pem.size(),
  12206. nullptr // no password for server key
  12207. };
  12208. SSLServer svr(server_pem);
  12209. ASSERT_TRUE(svr.is_valid());
  12210. svr.Get("/test", [&](const Request &, Response &res) {
  12211. res.set_content("test", "text/plain");
  12212. });
  12213. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12214. auto se = detail::scope_exit([&] {
  12215. svr.stop();
  12216. t.join();
  12217. ASSERT_FALSE(svr.is_running());
  12218. });
  12219. svr.wait_until_ready();
  12220. // Create client with PEM memory
  12221. const char *password = client_encrypted_private_key_pass.empty()
  12222. ? nullptr
  12223. : client_encrypted_private_key_pass.c_str();
  12224. SSLClient::PemMemory client_pem = {
  12225. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12226. client_key_pem.size(), password};
  12227. SSLClient cli(HOST, PORT, client_pem);
  12228. cli.enable_server_certificate_verification(false);
  12229. cli.set_connection_timeout(30);
  12230. auto res = cli.Get("/test");
  12231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12232. ASSERT_EQ(StatusCode::OK_200, res->status);
  12233. }
  12234. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12235. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12236. }
  12237. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12238. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12239. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12240. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12241. }
  12242. TEST(SSLClientServerTest, ClientCertMissing) {
  12243. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12244. CLIENT_CA_CERT_DIR);
  12245. ASSERT_TRUE(svr.is_valid());
  12246. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12247. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12248. auto se = detail::scope_exit([&] {
  12249. svr.stop();
  12250. t.join();
  12251. ASSERT_FALSE(svr.is_running());
  12252. });
  12253. svr.wait_until_ready();
  12254. SSLClient cli(HOST, PORT);
  12255. cli.set_connection_timeout(30);
  12256. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12257. // the chain check on Windows, so the result does not depend on the order.
  12258. cli.enable_server_hostname_verification(false);
  12259. auto res = cli.Get("/test");
  12260. ASSERT_TRUE(!res);
  12261. // When client cert is missing and server requires it, connection fails
  12262. // Error type depends on backend implementation
  12263. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12264. res.error() == Error::SSLConnection);
  12265. // Verify backend error is captured
  12266. // Note: This test may have different error codes depending on the exact
  12267. // verification failure
  12268. EXPECT_NE(0UL, res.ssl_backend_error());
  12269. }
  12270. TEST(SSLClientServerTest, TrustDirOptional) {
  12271. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12272. ASSERT_TRUE(svr.is_valid());
  12273. svr.Get("/test", [&](const Request &, Response &res) {
  12274. res.set_content("test", "text/plain");
  12275. });
  12276. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12277. auto se = detail::scope_exit([&] {
  12278. svr.stop();
  12279. t.join();
  12280. ASSERT_FALSE(svr.is_running());
  12281. });
  12282. svr.wait_until_ready();
  12283. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12284. cli.enable_server_certificate_verification(false);
  12285. cli.set_connection_timeout(30);
  12286. auto res = cli.Get("/test");
  12287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12288. ASSERT_EQ(StatusCode::OK_200, res->status);
  12289. }
  12290. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12291. class NoListenSSLServer : public SSLServer {
  12292. public:
  12293. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12294. const char *client_ca_cert_file_path,
  12295. const char *client_ca_cert_dir_path = nullptr)
  12296. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12297. client_ca_cert_dir_path),
  12298. stop_(false) {}
  12299. std::atomic_bool stop_;
  12300. private:
  12301. bool process_and_close_socket(socket_t /*sock*/) override {
  12302. // Don't create SSL context
  12303. while (!stop_.load()) {
  12304. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12305. }
  12306. return true;
  12307. }
  12308. };
  12309. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12310. CLIENT_CA_CERT_FILE);
  12311. ASSERT_TRUE(svr.is_valid());
  12312. svr.Get("/test", [&](const Request &, Response &res) {
  12313. res.set_content("test", "text/plain");
  12314. });
  12315. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12316. auto se = detail::scope_exit([&] {
  12317. svr.stop_ = true;
  12318. svr.stop();
  12319. t.join();
  12320. ASSERT_FALSE(svr.is_running());
  12321. });
  12322. svr.wait_until_ready();
  12323. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12324. cli.enable_server_certificate_verification(false);
  12325. cli.set_connection_timeout(1);
  12326. auto res = cli.Get("/test");
  12327. ASSERT_TRUE(!res);
  12328. EXPECT_EQ(Error::SSLConnection, res.error());
  12329. // Timeout results in WantRead error code (maps to backend-specific value)
  12330. EXPECT_NE(0, res.ssl_error());
  12331. }
  12332. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12333. // Test SSLServer with client certificate verification using the standard
  12334. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12335. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12336. CLIENT_CA_CERT_DIR);
  12337. ASSERT_TRUE(svr.is_valid());
  12338. svr.Get("/test", [&](const Request &req, Response &res) {
  12339. res.set_content("test", "text/plain");
  12340. auto cert = req.peer_cert();
  12341. ASSERT_TRUE(static_cast<bool>(cert));
  12342. auto common_name = cert.subject_cn();
  12343. EXPECT_EQ("Common Name", common_name);
  12344. });
  12345. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12346. auto se = detail::scope_exit([&] {
  12347. svr.stop();
  12348. t.join();
  12349. ASSERT_FALSE(svr.is_running());
  12350. });
  12351. svr.wait_until_ready();
  12352. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12353. cli.enable_server_certificate_verification(false);
  12354. cli.set_connection_timeout(30);
  12355. auto res = cli.Get("/test");
  12356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12357. ASSERT_EQ(StatusCode::OK_200, res->status);
  12358. }
  12359. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12360. // Verifies that wildcard matching and exact matching work consistently
  12361. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12362. using namespace httplib::tls;
  12363. // We need a running server to test against
  12364. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12365. ASSERT_TRUE(svr.is_valid());
  12366. svr.Get("/test", [](const Request &, Response &res) {
  12367. res.set_content("ok", "text/plain");
  12368. });
  12369. thread t([&]() { svr.listen(HOST, PORT); });
  12370. auto se = detail::scope_exit([&] {
  12371. svr.stop();
  12372. t.join();
  12373. });
  12374. svr.wait_until_ready();
  12375. bool verify_callback_called = false;
  12376. bool verify_result_wrong = false;
  12377. SSLClient cli(HOST, PORT);
  12378. cli.enable_server_certificate_verification(true);
  12379. cli.set_ca_cert_path(CA_CERT_FILE);
  12380. cli.set_connection_timeout(5);
  12381. // Note: Test certificate has CN="Common Name", not "localhost"
  12382. bool verify_result_cn = false;
  12383. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12384. verify_callback_called = true;
  12385. if (!ctx.cert) return false;
  12386. // Test 1: "Common Name" should match (our test server cert CN)
  12387. verify_result_cn = ctx.check_hostname("Common Name");
  12388. // Test 2: wrong hostname should not match
  12389. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12390. return true; // Accept for the purpose of this test
  12391. });
  12392. auto res = cli.Get("/test");
  12393. // The request may succeed or fail depending on cert configuration
  12394. // but the callback should have been called
  12395. ASSERT_TRUE(verify_callback_called)
  12396. << "Verify callback should have been called";
  12397. // CN="Common Name" should match our test certificate
  12398. //
  12399. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12400. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12401. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12402. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12403. // <openssl/base.h>, which is included transitively when
  12404. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12405. #if defined(OPENSSL_IS_BORINGSSL)
  12406. EXPECT_FALSE(verify_result_cn)
  12407. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12408. #else
  12409. EXPECT_TRUE(verify_result_cn)
  12410. << "verify_hostname should match 'Common Name' (certificate CN)";
  12411. #endif
  12412. // Wrong hostname should not match
  12413. EXPECT_FALSE(verify_result_wrong)
  12414. << "verify_hostname should not match 'wronghost.example.com'";
  12415. }
  12416. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12417. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12418. // X509_check_ip behavior and must hold for every backend.
  12419. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12420. using namespace httplib::tls;
  12421. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12422. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12423. ASSERT_TRUE(svr.is_valid());
  12424. svr.Get("/test", [](const Request &, Response &res) {
  12425. res.set_content("ok", "text/plain");
  12426. });
  12427. thread t([&]() { svr.listen(HOST, PORT); });
  12428. auto se = detail::scope_exit([&] {
  12429. svr.stop();
  12430. t.join();
  12431. });
  12432. svr.wait_until_ready();
  12433. bool verify_callback_called = false;
  12434. bool ip_matched_via_cn = true;
  12435. SSLClient cli(HOST, PORT);
  12436. cli.enable_server_certificate_verification(true);
  12437. cli.set_ca_cert_path(CA_CERT_FILE);
  12438. cli.set_connection_timeout(5);
  12439. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12440. verify_callback_called = true;
  12441. if (!ctx.cert) return false;
  12442. // The IP appears only in the CN, so it must NOT be accepted.
  12443. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12444. return true; // Accept for the purpose of this test
  12445. });
  12446. cli.Get("/test");
  12447. ASSERT_TRUE(verify_callback_called)
  12448. << "Verify callback should have been called";
  12449. EXPECT_FALSE(ip_matched_via_cn)
  12450. << "An IP host must not be authenticated via the certificate CN";
  12451. }
  12452. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12453. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12454. using namespace httplib::tls;
  12455. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12456. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12457. ASSERT_TRUE(svr.is_valid());
  12458. svr.Get("/test", [](const Request &, Response &res) {
  12459. res.set_content("ok", "text/plain");
  12460. });
  12461. thread t([&]() { svr.listen(HOST, PORT); });
  12462. auto se = detail::scope_exit([&] {
  12463. svr.stop();
  12464. t.join();
  12465. });
  12466. svr.wait_until_ready();
  12467. bool verify_callback_called = false;
  12468. bool san_matched = false;
  12469. bool wrong_ipv6_matched = true;
  12470. bool cn_ipv6_matched = true;
  12471. SSLClient cli(HOST, PORT);
  12472. cli.enable_server_certificate_verification(true);
  12473. cli.set_ca_cert_path(CA_CERT_FILE);
  12474. cli.set_connection_timeout(5);
  12475. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12476. verify_callback_called = true;
  12477. if (!ctx.cert) return false;
  12478. // Matches the IPv6 iPAddress SAN.
  12479. san_matched = ctx.check_hostname("2001:db8::1");
  12480. // A different IPv6 address must not match.
  12481. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12482. // "::1" lives only in the CN, so it must not be accepted.
  12483. cn_ipv6_matched = ctx.check_hostname("::1");
  12484. return true; // Accept for the purpose of this test
  12485. });
  12486. cli.Get("/test");
  12487. ASSERT_TRUE(verify_callback_called)
  12488. << "Verify callback should have been called";
  12489. EXPECT_TRUE(san_matched)
  12490. << "verify_hostname should match an IPv6 iPAddress SAN";
  12491. EXPECT_FALSE(wrong_ipv6_matched)
  12492. << "verify_hostname should not match a non-matching IPv6 address";
  12493. EXPECT_FALSE(cn_ipv6_matched)
  12494. << "An IPv6 host must not be authenticated via the certificate CN";
  12495. }
  12496. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12497. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12498. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12499. using namespace httplib::tls;
  12500. // SANs: DNS:a.zz, IP:42.46.122.122
  12501. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12502. ASSERT_TRUE(svr.is_valid());
  12503. svr.Get("/test", [](const Request &, Response &res) {
  12504. res.set_content("ok", "text/plain");
  12505. });
  12506. auto port = svr.bind_to_any_port(HOST);
  12507. thread t([&]() { svr.listen_after_bind(); });
  12508. auto se = detail::scope_exit([&] {
  12509. svr.stop();
  12510. t.join();
  12511. });
  12512. svr.wait_until_ready();
  12513. bool verify_callback_called = false;
  12514. bool dns_san_matched = false;
  12515. bool ip_san_matched = false;
  12516. bool ip_matched_via_dns_san = true;
  12517. bool dns_matched_via_ip_san = true;
  12518. SSLClient cli(HOST, port);
  12519. cli.enable_server_certificate_verification(true);
  12520. cli.set_ca_cert_path(CA_CERT_FILE);
  12521. cli.set_connection_timeout(5);
  12522. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12523. verify_callback_called = true;
  12524. if (!ctx.cert) return false;
  12525. dns_san_matched = ctx.check_hostname("a.zz");
  12526. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12527. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12528. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12529. return true; // Accept for the purpose of this test
  12530. });
  12531. cli.Get("/test");
  12532. ASSERT_TRUE(verify_callback_called)
  12533. << "Verify callback should have been called";
  12534. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12535. EXPECT_TRUE(ip_san_matched)
  12536. << "verify_hostname should match an iPAddress SAN";
  12537. EXPECT_FALSE(ip_matched_via_dns_san)
  12538. << "An IP host must not be authenticated via a dNSName SAN";
  12539. EXPECT_FALSE(dns_matched_via_ip_san)
  12540. << "A DNS host must not be authenticated via an iPAddress SAN";
  12541. }
  12542. // sans() must report each SAN entry under its own type.
  12543. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  12544. using namespace httplib::tls;
  12545. // SANs: DNS:a.zz, IP:42.46.122.122
  12546. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12547. ASSERT_TRUE(svr.is_valid());
  12548. svr.Get("/test", [](const Request &, Response &res) {
  12549. res.set_content("ok", "text/plain");
  12550. });
  12551. auto port = svr.bind_to_any_port(HOST);
  12552. thread t([&]() { svr.listen_after_bind(); });
  12553. auto se = detail::scope_exit([&] {
  12554. svr.stop();
  12555. t.join();
  12556. });
  12557. svr.wait_until_ready();
  12558. bool verify_callback_called = false;
  12559. std::vector<SanEntry> sans;
  12560. SSLClient cli(HOST, port);
  12561. cli.enable_server_certificate_verification(true);
  12562. cli.set_ca_cert_path(CA_CERT_FILE);
  12563. cli.set_connection_timeout(5);
  12564. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12565. verify_callback_called = true;
  12566. if (!ctx.cert) return false;
  12567. sans = ctx.sans();
  12568. return true; // Accept for the purpose of this test
  12569. });
  12570. cli.Get("/test");
  12571. ASSERT_TRUE(verify_callback_called)
  12572. << "Verify callback should have been called";
  12573. auto has_san = [&](SanType type, const std::string &value) {
  12574. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  12575. return san.type == type && san.value == value;
  12576. });
  12577. };
  12578. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  12579. << "sans() should report the dNSName SAN";
  12580. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  12581. << "sans() should report the iPAddress SAN";
  12582. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  12583. << "sans() must not report the dNSName SAN as an address";
  12584. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  12585. << "sans() must not report the iPAddress SAN as a DNS name";
  12586. }
  12587. #endif
  12588. // mbedTLS-specific callback constructor test
  12589. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12590. #ifdef CPPHTTPLIB_SSL_ENABLED
  12591. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12593. ASSERT_TRUE(svr.is_valid());
  12594. // Set up a handler to verify client certificate is present
  12595. bool client_cert_verified = false;
  12596. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12597. // Verify that client certificate was provided
  12598. client_cert_verified = true;
  12599. res.set_content("success", "text/plain");
  12600. });
  12601. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12602. auto se = detail::scope_exit([&] {
  12603. svr.stop();
  12604. t.join();
  12605. ASSERT_FALSE(svr.is_running());
  12606. });
  12607. svr.wait_until_ready();
  12608. // Client with certificate
  12609. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12610. cli.enable_server_certificate_verification(false);
  12611. cli.set_connection_timeout(30);
  12612. auto res = cli.Get("/test");
  12613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12614. ASSERT_EQ(StatusCode::OK_200, res->status);
  12615. ASSERT_TRUE(client_cert_verified);
  12616. EXPECT_EQ("success", res->body);
  12617. }
  12618. #endif
  12619. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12620. // backends
  12621. #ifdef CPPHTTPLIB_SSL_ENABLED
  12622. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12623. using namespace httplib::tls;
  12624. // Test that when client CA cert file is provided,
  12625. // the server properly requests and validates client certificates
  12626. // Create a server with client authentication
  12627. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12628. ASSERT_TRUE(svr.is_valid());
  12629. bool handler_called = false;
  12630. svr.Get("/test", [&](const Request &req, Response &res) {
  12631. handler_called = true;
  12632. // Verify that a client certificate was provided
  12633. auto cert = req.peer_cert();
  12634. ASSERT_TRUE(static_cast<bool>(cert));
  12635. // Get the issuer name
  12636. std::string issuer_str = cert.issuer_name();
  12637. ASSERT_FALSE(issuer_str.empty());
  12638. // The client certificate should be issued by our test CA
  12639. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12640. res.set_content("authenticated", "text/plain");
  12641. });
  12642. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12643. auto se = detail::scope_exit([&] {
  12644. svr.stop();
  12645. t.join();
  12646. ASSERT_FALSE(svr.is_running());
  12647. });
  12648. svr.wait_until_ready();
  12649. // Connect with a client certificate issued by the CA
  12650. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12651. cli.enable_server_certificate_verification(false);
  12652. cli.set_connection_timeout(30);
  12653. auto res = cli.Get("/test");
  12654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12655. ASSERT_EQ(StatusCode::OK_200, res->status);
  12656. ASSERT_TRUE(handler_called);
  12657. EXPECT_EQ("authenticated", res->body);
  12658. }
  12659. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12660. using namespace httplib::tls;
  12661. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12662. ASSERT_TRUE(svr.is_valid());
  12663. svr.Get("/test", [](const Request &, Response &res) {
  12664. res.set_content("ok", "text/plain");
  12665. });
  12666. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12667. auto se = detail::scope_exit([&] {
  12668. svr.stop();
  12669. t.join();
  12670. });
  12671. svr.wait_until_ready();
  12672. SSLClient cli(HOST, PORT);
  12673. cli.enable_server_certificate_verification(false);
  12674. cli.set_connection_timeout(30);
  12675. bool cert_checked = false;
  12676. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12677. if (ctx.cert) {
  12678. auto sans = ctx.sans();
  12679. // Test certificate may or may not have SANs - just verify the API
  12680. // works If SANs exist, verify the types are valid
  12681. for (const auto &san : sans) {
  12682. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12683. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12684. san.type == SanType::OTHER);
  12685. EXPECT_FALSE(san.value.empty());
  12686. }
  12687. cert_checked = true;
  12688. }
  12689. return true;
  12690. });
  12691. auto res = cli.Get("/test");
  12692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12693. EXPECT_TRUE(cert_checked);
  12694. }
  12695. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12696. using namespace httplib::tls;
  12697. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12698. ASSERT_TRUE(svr.is_valid());
  12699. svr.Get("/test", [](const Request &, Response &res) {
  12700. res.set_content("ok", "text/plain");
  12701. });
  12702. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12703. auto se = detail::scope_exit([&] {
  12704. svr.stop();
  12705. t.join();
  12706. });
  12707. svr.wait_until_ready();
  12708. SSLClient cli(HOST, PORT);
  12709. cli.enable_server_certificate_verification(false);
  12710. cli.set_connection_timeout(30);
  12711. bool validity_checked = false;
  12712. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12713. if (ctx.cert) {
  12714. time_t not_before = 0, not_after = 0;
  12715. bool result = ctx.validity(not_before, not_after);
  12716. EXPECT_TRUE(result);
  12717. // Verify that not_before < now < not_after for a valid cert
  12718. time_t now = time(nullptr);
  12719. EXPECT_LT(not_before, now);
  12720. EXPECT_GT(not_after, now);
  12721. validity_checked = true;
  12722. }
  12723. return true;
  12724. });
  12725. auto res = cli.Get("/test");
  12726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12727. EXPECT_TRUE(validity_checked);
  12728. }
  12729. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12730. using namespace httplib::tls;
  12731. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12732. ASSERT_TRUE(svr.is_valid());
  12733. svr.Get("/test", [](const Request &, Response &res) {
  12734. res.set_content("ok", "text/plain");
  12735. });
  12736. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12737. auto se = detail::scope_exit([&] {
  12738. svr.stop();
  12739. t.join();
  12740. });
  12741. svr.wait_until_ready();
  12742. SSLClient cli(HOST, PORT);
  12743. cli.enable_server_certificate_verification(false);
  12744. cli.set_connection_timeout(30);
  12745. bool serial_checked = false;
  12746. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12747. if (ctx.cert) {
  12748. std::string serial = ctx.serial();
  12749. EXPECT_FALSE(serial.empty());
  12750. // Serial should be a hex string
  12751. for (char c : serial) {
  12752. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12753. (c >= 'a' && c <= 'f'));
  12754. }
  12755. serial_checked = true;
  12756. }
  12757. return true;
  12758. });
  12759. auto res = cli.Get("/test");
  12760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12761. EXPECT_TRUE(serial_checked);
  12762. }
  12763. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12764. // Test 1: Valid CA file - no error should be recorded
  12765. {
  12766. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12767. CLIENT_CA_CERT_FILE);
  12768. ASSERT_TRUE(svr.is_valid());
  12769. // With valid setup, last_ssl_error should be 0
  12770. EXPECT_EQ(0, svr.ssl_last_error());
  12771. }
  12772. // Test 2: Invalid CA file content
  12773. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12774. {
  12775. // Create a temporary file with completely invalid content
  12776. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12777. {
  12778. std::ofstream ofs(temp_invalid_ca);
  12779. ofs << "This is not a certificate file at all\n";
  12780. ofs << "Just plain text content\n";
  12781. }
  12782. // Create server with invalid CA file
  12783. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12784. // Clean up temporary file
  12785. std::remove(temp_invalid_ca);
  12786. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12787. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12788. // Note: SSL_CTX_load_verify_locations typically fails first,
  12789. // but our error handling code path is still exercised
  12790. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12791. }
  12792. }
  12793. TEST(VerifyCallbackTest, VerifyContextFields) {
  12794. using namespace httplib::tls;
  12795. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12796. ASSERT_TRUE(svr.is_valid());
  12797. svr.Get("/test", [](const Request &, Response &res) {
  12798. res.set_content("ok", "text/plain");
  12799. });
  12800. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12801. auto se = detail::scope_exit([&] {
  12802. svr.stop();
  12803. t.join();
  12804. });
  12805. svr.wait_until_ready();
  12806. SSLClient cli(HOST, PORT);
  12807. cli.enable_server_certificate_verification(false);
  12808. cli.set_connection_timeout(30);
  12809. int callback_count = 0;
  12810. bool saw_leaf_cert = false;
  12811. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12812. if (ctx.cert) {
  12813. callback_count++;
  12814. // We should see at least one certificate (the leaf)
  12815. std::string cn = ctx.subject_cn();
  12816. if (!cn.empty()) { saw_leaf_cert = true; }
  12817. // Verify context fields are populated
  12818. EXPECT_NE(ctx.session, nullptr);
  12819. EXPECT_GE(ctx.depth, 0);
  12820. }
  12821. return true;
  12822. });
  12823. auto res = cli.Get("/test");
  12824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12825. EXPECT_GT(callback_count, 0);
  12826. EXPECT_TRUE(saw_leaf_cert);
  12827. }
  12828. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12829. using httplib::tls::TlsError;
  12830. // Test that verify_error_to_string returns empty for success
  12831. std::string success_str = TlsError::verify_error_to_string(0);
  12832. EXPECT_TRUE(success_str.empty());
  12833. // Test that verify_error_to_string returns non-empty for error codes
  12834. // Using a common error code (certificate expired)
  12835. std::string error_str =
  12836. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12837. EXPECT_FALSE(error_str.empty());
  12838. }
  12839. TEST(SessionVerifierTest, CertificateAccepted) {
  12840. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12841. ASSERT_TRUE(svr.is_valid());
  12842. svr.Get("/test", [](const Request &, Response &res) {
  12843. res.set_content("ok", "text/plain");
  12844. });
  12845. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12846. auto se = detail::scope_exit([&] {
  12847. svr.stop();
  12848. t.join();
  12849. });
  12850. svr.wait_until_ready();
  12851. SSLClient cli(HOST, PORT);
  12852. cli.enable_server_certificate_verification(false);
  12853. cli.set_connection_timeout(30);
  12854. bool callback_called = false;
  12855. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12856. EXPECT_NE(session, nullptr);
  12857. callback_called = true;
  12858. return SSLVerifierResponse::CertificateAccepted;
  12859. });
  12860. auto res = cli.Get("/test");
  12861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12862. EXPECT_EQ(200, res->status);
  12863. EXPECT_TRUE(callback_called);
  12864. }
  12865. TEST(SessionVerifierTest, CertificateRejected) {
  12866. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12867. ASSERT_TRUE(svr.is_valid());
  12868. svr.Get("/test", [](const Request &, Response &res) {
  12869. res.set_content("ok", "text/plain");
  12870. });
  12871. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12872. auto se = detail::scope_exit([&] {
  12873. svr.stop();
  12874. t.join();
  12875. });
  12876. svr.wait_until_ready();
  12877. SSLClient cli(HOST, PORT);
  12878. cli.enable_server_certificate_verification(false);
  12879. cli.set_connection_timeout(30);
  12880. bool callback_called = false;
  12881. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12882. EXPECT_NE(session, nullptr);
  12883. callback_called = true;
  12884. return SSLVerifierResponse::CertificateRejected;
  12885. });
  12886. auto res = cli.Get("/test");
  12887. EXPECT_FALSE(res);
  12888. EXPECT_TRUE(callback_called);
  12889. }
  12890. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12891. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12892. ASSERT_TRUE(svr.is_valid());
  12893. svr.Get("/test", [](const Request &, Response &res) {
  12894. res.set_content("ok", "text/plain");
  12895. });
  12896. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12897. auto se = detail::scope_exit([&] {
  12898. svr.stop();
  12899. t.join();
  12900. });
  12901. svr.wait_until_ready();
  12902. // NoDecisionMade with verification disabled should succeed (no default check)
  12903. SSLClient cli(HOST, PORT);
  12904. cli.enable_server_certificate_verification(false);
  12905. cli.set_connection_timeout(30);
  12906. bool callback_called = false;
  12907. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12908. EXPECT_NE(session, nullptr);
  12909. callback_called = true;
  12910. return SSLVerifierResponse::NoDecisionMade;
  12911. });
  12912. auto res = cli.Get("/test");
  12913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12914. EXPECT_EQ(200, res->status);
  12915. EXPECT_TRUE(callback_called);
  12916. }
  12917. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12918. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12919. ASSERT_TRUE(svr.is_valid());
  12920. svr.Get("/test", [](const Request &, Response &res) {
  12921. res.set_content("ok", "text/plain");
  12922. });
  12923. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12924. auto se = detail::scope_exit([&] {
  12925. svr.stop();
  12926. t.join();
  12927. });
  12928. svr.wait_until_ready();
  12929. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12930. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12931. // so we only check that the request fails, not whether the callback was
  12932. // called.
  12933. SSLClient cli(HOST, PORT);
  12934. cli.enable_server_certificate_verification(true);
  12935. cli.set_connection_timeout(30);
  12936. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12937. EXPECT_NE(session, nullptr);
  12938. return SSLVerifierResponse::NoDecisionMade;
  12939. });
  12940. auto res = cli.Get("/test");
  12941. EXPECT_FALSE(res);
  12942. }
  12943. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12944. // Test SSL server using PemMemory constructor with client CA certificates
  12945. // Read PEM files
  12946. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12947. read_file(SERVER_CERT_FILE, server_cert_pem);
  12948. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12949. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12950. // Create SSLServer with PemMemory constructor including client CA
  12951. SSLServer::PemMemory server_pem = {
  12952. server_cert_pem.c_str(),
  12953. server_cert_pem.size(),
  12954. server_key_pem.c_str(),
  12955. server_key_pem.size(),
  12956. client_ca_pem.c_str(),
  12957. client_ca_pem.size(),
  12958. nullptr // no password for server key
  12959. };
  12960. SSLServer svr(server_pem);
  12961. ASSERT_TRUE(svr.is_valid());
  12962. // No SSL error should be recorded for valid setup
  12963. EXPECT_EQ(0, svr.ssl_last_error());
  12964. // Set up server endpoints
  12965. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12966. res.set_content("ok", "text/plain");
  12967. });
  12968. // Start server in a thread
  12969. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12970. svr.wait_until_ready();
  12971. // Connect with client certificate (using constructor with paths)
  12972. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12973. cli.enable_server_certificate_verification(false);
  12974. auto res = cli.Get("/test-pem-ca");
  12975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12976. EXPECT_EQ(200, res->status);
  12977. EXPECT_EQ("ok", res->body);
  12978. svr.stop();
  12979. server_thread.join();
  12980. }
  12981. #endif
  12982. #ifdef _WIN32
  12983. TEST(CleanupTest, WSACleanup) {
  12984. int ret = WSACleanup();
  12985. ASSERT_EQ(0, ret);
  12986. }
  12987. #endif
  12988. #ifndef CPPHTTPLIB_SSL_ENABLED
  12989. TEST(NoSSLSupport, SimpleInterface) {
  12990. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12991. }
  12992. #endif
  12993. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12994. TEST(InvalidScheme, SimpleInterface) {
  12995. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12996. }
  12997. #endif
  12998. TEST(NoScheme, SimpleInterface) {
  12999. Client cli("yahoo.com:80");
  13000. ASSERT_TRUE(cli.is_valid());
  13001. }
  13002. TEST(SendAPI, SimpleInterface_Online) {
  13003. Client cli("http://yahoo.com");
  13004. Request req;
  13005. req.method = "GET";
  13006. req.path = "/";
  13007. auto res = cli.send(req);
  13008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13009. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13010. }
  13011. TEST(SendAPI, WithParamsInRequest) {
  13012. Server svr;
  13013. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13014. EXPECT_TRUE(req.has_param("test"));
  13015. EXPECT_EQ("test_value", req.get_param_value("test"));
  13016. });
  13017. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13018. auto se = detail::scope_exit([&] {
  13019. svr.stop();
  13020. t.join();
  13021. ASSERT_FALSE(svr.is_running());
  13022. });
  13023. svr.wait_until_ready();
  13024. Client cli(HOST, PORT);
  13025. {
  13026. Request req;
  13027. req.method = "GET";
  13028. req.path = "/";
  13029. req.params.emplace("test", "test_value");
  13030. auto res = cli.send(req);
  13031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13032. }
  13033. {
  13034. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13036. }
  13037. }
  13038. TEST(ClientImplMethods, GetSocketTest) {
  13039. httplib::Server svr;
  13040. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13041. res.status = StatusCode::OK_200;
  13042. });
  13043. auto port = svr.bind_to_any_port("127.0.0.1");
  13044. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13045. auto se = detail::scope_exit([&] {
  13046. svr.stop();
  13047. thread.join();
  13048. ASSERT_FALSE(svr.is_running());
  13049. });
  13050. svr.wait_until_ready();
  13051. {
  13052. httplib::Client cli("127.0.0.1", port);
  13053. cli.set_keep_alive(true);
  13054. // Use the behavior of cpp-httplib of opening the connection
  13055. // only when the first request happens. If that changes,
  13056. // this test would be obsolete.
  13057. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13058. // This also implicitly tests the server. But other tests would fail much
  13059. // earlier than this one to be considered.
  13060. auto res = cli.Get("/");
  13061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13062. EXPECT_EQ(StatusCode::OK_200, res->status);
  13063. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13064. }
  13065. }
  13066. #ifdef CPPHTTPLIB_SSL_ENABLED
  13067. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13068. Client cli("http://yahoo.com");
  13069. auto res = cli.Get("/");
  13070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13071. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13072. cli.set_follow_location(true);
  13073. res = cli.Get("/");
  13074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13075. EXPECT_EQ(StatusCode::OK_200, res->status);
  13076. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13077. }
  13078. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13079. Client cli("https://yahoo.com");
  13080. auto res = cli.Get("/");
  13081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13082. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13083. cli.set_follow_location(true);
  13084. res = cli.Get("/");
  13085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13086. EXPECT_EQ(StatusCode::OK_200, res->status);
  13087. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13088. }
  13089. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13090. Client cli("https://yahoo.com");
  13091. auto res = cli.Get("/");
  13092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13093. ASSERT_FALSE(!res);
  13094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13095. ASSERT_FALSE(res == nullptr);
  13096. ASSERT_TRUE(res != nullptr);
  13097. EXPECT_EQ(Error::Success, res.error());
  13098. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13099. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13100. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13101. cli.set_follow_location(true);
  13102. res = cli.Get("/");
  13103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13104. EXPECT_EQ(Error::Success, res.error());
  13105. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13106. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13107. EXPECT_EQ(StatusCode::OK_200, res->status);
  13108. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13109. }
  13110. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13111. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13112. Client cli("https://cdnjs.cloudflare.com");
  13113. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13114. Headers{{"Accept-Encoding", "br"}});
  13115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13116. EXPECT_EQ(StatusCode::OK_200, res->status);
  13117. EXPECT_EQ(287630U, res->body.size());
  13118. EXPECT_EQ("application/javascript; charset=utf-8",
  13119. res->get_header_value("Content-Type"));
  13120. }
  13121. #endif
  13122. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13123. #undef REDIR_HOST // Silence compiler warning
  13124. #define REDIR_HOST "https://httpbingo.org"
  13125. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13126. Client cli(REDIR_HOST);
  13127. cli.set_follow_location(true);
  13128. auto res =
  13129. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13131. EXPECT_EQ(StatusCode::OK_200, res->status);
  13132. }
  13133. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13134. Client cli(REDIR_HOST);
  13135. cli.set_follow_location(true);
  13136. Params params;
  13137. params.emplace("url", "http://example.com");
  13138. params.emplace("status_code", "302");
  13139. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13141. EXPECT_EQ(StatusCode::OK_200, res->status);
  13142. }
  13143. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13144. Client cli(REDIR_HOST);
  13145. cli.set_follow_location(true);
  13146. Params params;
  13147. params.emplace("url", "http://example.com");
  13148. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13150. EXPECT_EQ(StatusCode::OK_200, res->status);
  13151. }
  13152. TEST(HttpToHttpsRedirectTest, CertFile) {
  13153. auto ssl_port = PORT + 1;
  13154. Server svr;
  13155. ASSERT_TRUE(svr.is_valid());
  13156. svr.Get("/index", [&](const Request &, Response &res) {
  13157. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13158. "/index");
  13159. svr.stop();
  13160. });
  13161. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13162. ASSERT_TRUE(ssl_svr.is_valid());
  13163. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13164. res.set_content("test", "text/plain");
  13165. ssl_svr.stop();
  13166. });
  13167. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13168. thread t2 =
  13169. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13170. auto se = detail::scope_exit([&] {
  13171. t2.join();
  13172. t.join();
  13173. ASSERT_FALSE(svr.is_running());
  13174. });
  13175. svr.wait_until_ready();
  13176. ssl_svr.wait_until_ready();
  13177. Client cli("127.0.0.1", PORT);
  13178. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13179. cli.enable_server_certificate_verification(true);
  13180. cli.set_follow_location(true);
  13181. cli.set_connection_timeout(30);
  13182. auto res = cli.Get("/index");
  13183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13184. ASSERT_EQ(StatusCode::OK_200, res->status);
  13185. }
  13186. TEST(SSLClientRedirectTest, CertFile) {
  13187. auto ssl_port = PORT + 1;
  13188. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13189. ASSERT_TRUE(ssl_svr1.is_valid());
  13190. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13191. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13192. "/index");
  13193. ssl_svr1.stop();
  13194. });
  13195. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13196. ASSERT_TRUE(ssl_svr2.is_valid());
  13197. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13198. res.set_content("test", "text/plain");
  13199. ssl_svr2.stop();
  13200. });
  13201. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13202. thread t2 =
  13203. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13204. auto se = detail::scope_exit([&] {
  13205. t2.join();
  13206. t.join();
  13207. ASSERT_FALSE(ssl_svr1.is_running());
  13208. });
  13209. ssl_svr1.wait_until_ready();
  13210. ssl_svr2.wait_until_ready();
  13211. SSLClient cli("127.0.0.1", PORT);
  13212. std::string cert;
  13213. read_file(SERVER_CERT2_FILE, cert);
  13214. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13215. cli.enable_server_certificate_verification(true);
  13216. cli.set_follow_location(true);
  13217. cli.set_connection_timeout(30);
  13218. auto res = cli.Get("/index");
  13219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13220. ASSERT_EQ(StatusCode::OK_200, res->status);
  13221. }
  13222. #endif
  13223. #ifdef CPPHTTPLIB_SSL_ENABLED
  13224. // Test that set_ca_cert_store() skips system certs (consistent with
  13225. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13226. // should be trusted - system certs should NOT be loaded.
  13227. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13228. // Load a specific cert that is NOT a system CA cert
  13229. std::string cert;
  13230. read_file(SERVER_CERT2_FILE, cert);
  13231. SSLClient cli("google.com");
  13232. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13233. cli.enable_server_certificate_verification(true);
  13234. // This should FAIL because:
  13235. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13236. // 2. System certs should NOT be loaded when custom store is set
  13237. // If system certs WERE loaded, this would succeed
  13238. auto res = cli.Get("/");
  13239. ASSERT_FALSE(res);
  13240. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13241. }
  13242. // Same as above, but through the native store handle path. Regression test:
  13243. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13244. // merged system certs into the user-provided store.
  13245. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13246. std::string cert;
  13247. read_file(SERVER_CERT2_FILE, cert);
  13248. SSLClient cli("google.com");
  13249. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13250. cli.enable_server_certificate_verification(true);
  13251. auto res = cli.Get("/");
  13252. ASSERT_FALSE(res);
  13253. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13254. }
  13255. // A custom store set via the native handle must still verify a server whose
  13256. // cert it does contain.
  13257. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13258. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13259. ASSERT_TRUE(svr.is_valid());
  13260. svr.Get("/test", [&](const Request &, Response &res) {
  13261. res.set_content("test", "text/plain");
  13262. });
  13263. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13264. auto se = detail::scope_exit([&] {
  13265. svr.stop();
  13266. t.join();
  13267. ASSERT_FALSE(svr.is_running());
  13268. });
  13269. svr.wait_until_ready();
  13270. SSLClient cli("127.0.0.1", PORT);
  13271. std::string cert;
  13272. read_file(SERVER_CERT2_FILE, cert);
  13273. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13274. cli.enable_server_certificate_verification(true);
  13275. cli.set_connection_timeout(30);
  13276. auto res = cli.Get("/test");
  13277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13278. ASSERT_EQ(StatusCode::OK_200, res->status);
  13279. }
  13280. // CA certs loaded through the universal Client must be transferred to the
  13281. // client created internally for following an HTTPS redirect. Regression test:
  13282. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13283. // the CA data for redirect transfer.
  13284. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13285. auto ssl_port = PORT + 1;
  13286. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13287. ASSERT_TRUE(ssl_svr1.is_valid());
  13288. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13289. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13290. "/index");
  13291. });
  13292. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13293. ASSERT_TRUE(ssl_svr2.is_valid());
  13294. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13295. res.set_content("test", "text/plain");
  13296. });
  13297. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13298. thread t2 =
  13299. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13300. auto se = detail::scope_exit([&] {
  13301. ssl_svr2.stop();
  13302. ssl_svr1.stop();
  13303. t2.join();
  13304. t.join();
  13305. ASSERT_FALSE(ssl_svr1.is_running());
  13306. });
  13307. ssl_svr1.wait_until_ready();
  13308. ssl_svr2.wait_until_ready();
  13309. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13310. std::string cert;
  13311. read_file(SERVER_CERT2_FILE, cert);
  13312. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13313. cli.enable_server_certificate_verification(true);
  13314. cli.set_follow_location(true);
  13315. cli.set_connection_timeout(30);
  13316. auto res = cli.Get("/index");
  13317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13318. ASSERT_EQ(StatusCode::OK_200, res->status);
  13319. }
  13320. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13321. // so a host signed by a system CA verifies even though a custom CA is set
  13322. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13323. std::string cert;
  13324. read_file(SERVER_CERT2_FILE, cert);
  13325. SSLClient cli("google.com");
  13326. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13327. cli.enable_system_ca(true);
  13328. cli.enable_server_certificate_verification(true);
  13329. auto res = cli.Get("/");
  13330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13331. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13332. }
  13333. // The custom CA remains effective when combined with the system CA
  13334. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13335. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13336. ASSERT_TRUE(svr.is_valid());
  13337. svr.Get("/test", [&](const Request &, Response &res) {
  13338. res.set_content("test", "text/plain");
  13339. });
  13340. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13341. auto se = detail::scope_exit([&] {
  13342. svr.stop();
  13343. t.join();
  13344. ASSERT_FALSE(svr.is_running());
  13345. });
  13346. svr.wait_until_ready();
  13347. SSLClient cli("127.0.0.1", PORT);
  13348. std::string cert;
  13349. read_file(SERVER_CERT2_FILE, cert);
  13350. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13351. cli.enable_system_ca(true);
  13352. cli.enable_server_certificate_verification(true);
  13353. cli.set_connection_timeout(30);
  13354. auto res = cli.Get("/test");
  13355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13356. ASSERT_EQ(StatusCode::OK_200, res->status);
  13357. }
  13358. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13359. // skip chain verification entirely (only the certificate identity was
  13360. // checked), so a server presenting an untrusted certificate with a matching
  13361. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13362. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13363. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13364. ASSERT_TRUE(svr.is_valid());
  13365. svr.Get("/test", [&](const Request &, Response &res) {
  13366. res.set_content("test", "text/plain");
  13367. });
  13368. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13369. auto se = detail::scope_exit([&] {
  13370. svr.stop();
  13371. t.join();
  13372. ASSERT_FALSE(svr.is_running());
  13373. });
  13374. svr.wait_until_ready();
  13375. SSLClient cli("127.0.0.1", PORT);
  13376. std::string cert;
  13377. // A trusted CA that did not sign the server certificate. The server cert
  13378. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13379. // this connection.
  13380. read_file(CLIENT_CA_CERT_FILE, cert);
  13381. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13382. cli.enable_server_certificate_verification(true);
  13383. cli.set_connection_timeout(30);
  13384. auto res = cli.Get("/test");
  13385. ASSERT_FALSE(res);
  13386. }
  13387. // enable_system_ca(false) prevents system CA loading entirely
  13388. TEST(SSLClientTest, DisableSystemCa_Online) {
  13389. SSLClient cli("google.com");
  13390. cli.enable_system_ca(false);
  13391. cli.enable_server_certificate_verification(true);
  13392. auto res = cli.Get("/");
  13393. ASSERT_FALSE(res);
  13394. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13395. // itself when the CA chain is empty
  13396. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13397. res.error() == Error::SSLConnection);
  13398. }
  13399. // The universal Client forwards enable_system_ca()
  13400. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13401. std::string cert;
  13402. read_file(SERVER_CERT2_FILE, cert);
  13403. Client cli("https://google.com");
  13404. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13405. cli.enable_system_ca(true);
  13406. cli.enable_server_certificate_verification(true);
  13407. auto res = cli.Get("/");
  13408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13409. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13410. }
  13411. // The system CA policy must carry over to the client created internally for
  13412. // following a cross-host HTTPS redirect
  13413. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13414. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13415. ASSERT_TRUE(svr.is_valid());
  13416. svr.Get("/index", [&](const Request &, Response &res) {
  13417. res.set_redirect("https://www.google.com/");
  13418. });
  13419. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13420. auto se = detail::scope_exit([&] {
  13421. svr.stop();
  13422. t.join();
  13423. ASSERT_FALSE(svr.is_running());
  13424. });
  13425. svr.wait_until_ready();
  13426. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13427. std::string cert;
  13428. read_file(SERVER_CERT2_FILE, cert);
  13429. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13430. cli.enable_system_ca(true);
  13431. cli.enable_server_certificate_verification(true);
  13432. cli.set_follow_location(true);
  13433. cli.set_connection_timeout(30);
  13434. // Receiving any response proves the redirect client completed the TLS
  13435. // handshake with a system-CA-signed host
  13436. auto res = cli.Get("/index");
  13437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13438. }
  13439. TEST(MultipartFormDataTest, LargeData) {
  13440. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13441. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13442. const ContentReader &content_reader) {
  13443. if (req.is_multipart_form_data()) {
  13444. std::vector<FormData> items;
  13445. content_reader(
  13446. [&](const FormData &file) {
  13447. items.push_back(file);
  13448. return true;
  13449. },
  13450. [&](const char *data, size_t data_length) {
  13451. items.back().content.append(data, data_length);
  13452. return true;
  13453. });
  13454. EXPECT_TRUE(std::string(items[0].name) == "document");
  13455. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13456. EXPECT_TRUE(items[0].filename == "2MB_data");
  13457. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13458. EXPECT_TRUE(items[1].name == "hello");
  13459. EXPECT_TRUE(items[1].content == "world");
  13460. EXPECT_TRUE(items[1].filename == "");
  13461. EXPECT_TRUE(items[1].content_type == "");
  13462. } else {
  13463. std::string body;
  13464. content_reader([&](const char *data, size_t data_length) {
  13465. body.append(data, data_length);
  13466. return true;
  13467. });
  13468. }
  13469. });
  13470. auto port = svr.bind_to_any_port(HOST);
  13471. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13472. auto se = detail::scope_exit([&] {
  13473. svr.stop();
  13474. t.join();
  13475. ASSERT_FALSE(svr.is_running());
  13476. });
  13477. svr.wait_until_ready();
  13478. {
  13479. std::string data(1024 * 1024 * 2, '.');
  13480. std::stringstream buffer;
  13481. buffer << data;
  13482. SSLClient cli(HOST, port);
  13483. cli.enable_server_certificate_verification(false);
  13484. UploadFormDataItems items{
  13485. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13486. {"hello", "world", "", ""},
  13487. };
  13488. auto res = cli.Post("/post", items);
  13489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13490. ASSERT_EQ(StatusCode::OK_200, res->status);
  13491. }
  13492. }
  13493. TEST(MultipartFormDataTest, DataProviderItems) {
  13494. std::random_device seed_gen;
  13495. std::mt19937 random(seed_gen());
  13496. std::string rand1;
  13497. rand1.resize(1000);
  13498. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13499. std::string rand2;
  13500. rand2.resize(3000);
  13501. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13502. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13503. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13504. const ContentReader &content_reader) {
  13505. ASSERT_FALSE(req.is_multipart_form_data());
  13506. std::string body;
  13507. content_reader([&](const char *data, size_t data_length) {
  13508. body.append(data, data_length);
  13509. return true;
  13510. });
  13511. EXPECT_EQ(body, "");
  13512. });
  13513. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13514. const ContentReader &content_reader) {
  13515. ASSERT_TRUE(req.is_multipart_form_data());
  13516. std::vector<FormData> items;
  13517. content_reader(
  13518. [&](const FormData &file) {
  13519. items.push_back(file);
  13520. return true;
  13521. },
  13522. [&](const char *data, size_t data_length) {
  13523. items.back().content.append(data, data_length);
  13524. return true;
  13525. });
  13526. ASSERT_TRUE(items.size() == 2);
  13527. EXPECT_EQ(std::string(items[0].name), "name1");
  13528. EXPECT_EQ(items[0].content, "Testing123");
  13529. EXPECT_EQ(items[0].filename, "filename1");
  13530. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13531. EXPECT_EQ(items[1].name, "name2");
  13532. EXPECT_EQ(items[1].content, "Testing456");
  13533. EXPECT_EQ(items[1].filename, "");
  13534. EXPECT_EQ(items[1].content_type, "");
  13535. });
  13536. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13537. const ContentReader &content_reader) {
  13538. ASSERT_TRUE(req.is_multipart_form_data());
  13539. std::vector<FormData> items;
  13540. content_reader(
  13541. [&](const FormData &file) {
  13542. items.push_back(file);
  13543. return true;
  13544. },
  13545. [&](const char *data, size_t data_length) {
  13546. items.back().content.append(data, data_length);
  13547. return true;
  13548. });
  13549. ASSERT_TRUE(items.size() == 2);
  13550. EXPECT_EQ(items[0].name, "name3");
  13551. EXPECT_EQ(items[0].content, rand1);
  13552. EXPECT_EQ(items[0].filename, "filename3");
  13553. EXPECT_EQ(items[0].content_type, "");
  13554. EXPECT_EQ(items[1].name, "name4");
  13555. EXPECT_EQ(items[1].content, rand2);
  13556. EXPECT_EQ(items[1].filename, "filename4");
  13557. EXPECT_EQ(items[1].content_type, "");
  13558. });
  13559. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13560. const ContentReader &content_reader) {
  13561. ASSERT_TRUE(req.is_multipart_form_data());
  13562. std::vector<FormData> items;
  13563. content_reader(
  13564. [&](const FormData &file) {
  13565. items.push_back(file);
  13566. return true;
  13567. },
  13568. [&](const char *data, size_t data_length) {
  13569. items.back().content.append(data, data_length);
  13570. return true;
  13571. });
  13572. ASSERT_TRUE(items.size() == 4);
  13573. EXPECT_EQ(std::string(items[0].name), "name1");
  13574. EXPECT_EQ(items[0].content, "Testing123");
  13575. EXPECT_EQ(items[0].filename, "filename1");
  13576. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13577. EXPECT_EQ(items[1].name, "name2");
  13578. EXPECT_EQ(items[1].content, "Testing456");
  13579. EXPECT_EQ(items[1].filename, "");
  13580. EXPECT_EQ(items[1].content_type, "");
  13581. EXPECT_EQ(items[2].name, "name3");
  13582. EXPECT_EQ(items[2].content, rand1);
  13583. EXPECT_EQ(items[2].filename, "filename3");
  13584. EXPECT_EQ(items[2].content_type, "");
  13585. EXPECT_EQ(items[3].name, "name4");
  13586. EXPECT_EQ(items[3].content, rand2);
  13587. EXPECT_EQ(items[3].filename, "filename4");
  13588. EXPECT_EQ(items[3].content_type, "");
  13589. });
  13590. auto port = svr.bind_to_any_port("localhost");
  13591. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13592. auto se = detail::scope_exit([&] {
  13593. svr.stop();
  13594. t.join();
  13595. ASSERT_FALSE(svr.is_running());
  13596. });
  13597. svr.wait_until_ready();
  13598. {
  13599. SSLClient cli("localhost", port);
  13600. cli.enable_server_certificate_verification(false);
  13601. UploadFormDataItems items{
  13602. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13603. {"name2", "Testing456", "", ""}, // not a file
  13604. };
  13605. {
  13606. auto res = cli.Post("/post-none", {}, {}, {});
  13607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13608. ASSERT_EQ(StatusCode::OK_200, res->status);
  13609. }
  13610. FormDataProviderItems providers;
  13611. {
  13612. auto res =
  13613. cli.Post("/post-items", {}, items, providers); // empty providers
  13614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13615. ASSERT_EQ(StatusCode::OK_200, res->status);
  13616. }
  13617. providers.push_back({"name3",
  13618. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13619. // test the offset is given correctly at each step
  13620. if (!offset)
  13621. sink.os.write(rand1.data(), 30);
  13622. else if (offset == 30)
  13623. sink.os.write(rand1.data() + 30, 300);
  13624. else if (offset == 330)
  13625. sink.os.write(rand1.data() + 330, 670);
  13626. else if (offset == rand1.size())
  13627. sink.done();
  13628. return true;
  13629. },
  13630. "filename3",
  13631. {}});
  13632. providers.push_back({"name4",
  13633. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13634. // test the offset is given correctly at each step
  13635. if (!offset)
  13636. sink.os.write(rand2.data(), 2000);
  13637. else if (offset == 2000)
  13638. sink.os.write(rand2.data() + 2000, 1);
  13639. else if (offset == 2001)
  13640. sink.os.write(rand2.data() + 2001, 999);
  13641. else if (offset == rand2.size())
  13642. sink.done();
  13643. return true;
  13644. },
  13645. "filename4",
  13646. {}});
  13647. {
  13648. auto res = cli.Post("/post-providers", {}, {}, providers);
  13649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13650. ASSERT_EQ(StatusCode::OK_200, res->status);
  13651. }
  13652. {
  13653. auto res = cli.Post("/post-both", {}, items, providers);
  13654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13655. ASSERT_EQ(StatusCode::OK_200, res->status);
  13656. }
  13657. }
  13658. }
  13659. TEST(MultipartFormDataTest, BadHeader) {
  13660. Server svr;
  13661. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13662. res.set_content("ok", "text/plain");
  13663. });
  13664. thread t = thread([&] { svr.listen(HOST, PORT); });
  13665. auto se = detail::scope_exit([&] {
  13666. svr.stop();
  13667. t.join();
  13668. ASSERT_FALSE(svr.is_running());
  13669. });
  13670. svr.wait_until_ready();
  13671. const std::string body =
  13672. "This is the preamble. It is to be ignored, though it\r\n"
  13673. "is a handy place for composition agents to include an\r\n"
  13674. "explanatory note to non-MIME conformant readers.\r\n"
  13675. "\r\n"
  13676. "\r\n"
  13677. "--simple boundary\r\n"
  13678. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13679. ": BAD...\r\n"
  13680. "\r\n"
  13681. "value1\r\n"
  13682. "--simple boundary\r\n"
  13683. "Content-Disposition: form-data; name=\"field2\"; "
  13684. "filename=\"example.txt\"\r\n"
  13685. "\r\n"
  13686. "value2\r\n"
  13687. "--simple boundary--\r\n"
  13688. "This is the epilogue. It is also to be ignored.\r\n";
  13689. std::string content_type =
  13690. R"(multipart/form-data; boundary="simple boundary")";
  13691. Client cli(HOST, PORT);
  13692. auto res = cli.Post("/post", body, content_type.c_str());
  13693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13694. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13695. }
  13696. TEST(MultipartFormDataTest, WithPreamble) {
  13697. Server svr;
  13698. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13699. res.set_content("ok", "text/plain");
  13700. });
  13701. thread t = thread([&] { svr.listen(HOST, PORT); });
  13702. auto se = detail::scope_exit([&] {
  13703. svr.stop();
  13704. t.join();
  13705. ASSERT_FALSE(svr.is_running());
  13706. });
  13707. svr.wait_until_ready();
  13708. const std::string body =
  13709. "This is the preamble. It is to be ignored, though it\r\n"
  13710. "is a handy place for composition agents to include an\r\n"
  13711. "explanatory note to non-MIME conformant readers.\r\n"
  13712. "\r\n"
  13713. "\r\n"
  13714. "--simple boundary\r\n"
  13715. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13716. "\r\n"
  13717. "value1\r\n"
  13718. "--simple boundary\r\n"
  13719. "Content-Disposition: form-data; name=\"field2\"; "
  13720. "filename=\"example.txt\"\r\n"
  13721. "\r\n"
  13722. "value2\r\n"
  13723. "--simple boundary--\r\n"
  13724. "This is the epilogue. It is also to be ignored.\r\n";
  13725. std::string content_type =
  13726. R"(multipart/form-data; boundary="simple boundary")";
  13727. Client cli(HOST, PORT);
  13728. auto res = cli.Post("/post", body, content_type.c_str());
  13729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13730. EXPECT_EQ(StatusCode::OK_200, res->status);
  13731. }
  13732. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13733. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13734. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13735. const ContentReader &content_reader) {
  13736. if (req.is_multipart_form_data()) {
  13737. std::vector<FormData> items;
  13738. content_reader(
  13739. [&](const FormData &file) {
  13740. items.push_back(file);
  13741. return true;
  13742. },
  13743. [&](const char *data, size_t data_length) {
  13744. items.back().content.append(data, data_length);
  13745. return true;
  13746. });
  13747. EXPECT_TRUE(std::string(items[0].name) == "document");
  13748. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13749. EXPECT_TRUE(items[0].filename == "2MB_data");
  13750. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13751. EXPECT_TRUE(items[1].name == "hello");
  13752. EXPECT_TRUE(items[1].content == "world");
  13753. EXPECT_TRUE(items[1].filename == "");
  13754. EXPECT_TRUE(items[1].content_type == "");
  13755. } else {
  13756. std::string body;
  13757. content_reader([&](const char *data, size_t data_length) {
  13758. body.append(data, data_length);
  13759. return true;
  13760. });
  13761. }
  13762. });
  13763. auto port = svr.bind_to_any_port("localhost");
  13764. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13765. auto se = detail::scope_exit([&] {
  13766. svr.stop();
  13767. t.join();
  13768. ASSERT_FALSE(svr.is_running());
  13769. });
  13770. svr.wait_until_ready();
  13771. {
  13772. std::string data(1024 * 1024 * 2, '.');
  13773. std::stringstream buffer;
  13774. buffer << data;
  13775. SSLClient cli("localhost", port);
  13776. cli.enable_server_certificate_verification(false);
  13777. UploadFormDataItems items{
  13778. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13779. {"hello", "world", "", ""},
  13780. };
  13781. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13783. ASSERT_EQ(StatusCode::OK_200, res->status);
  13784. }
  13785. }
  13786. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13787. std::string data(1024 * 1024 * 2, '&');
  13788. std::stringstream buffer;
  13789. buffer << data;
  13790. Client cli("https://localhost:8080");
  13791. UploadFormDataItems items{
  13792. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13793. {"hello", "world", "", ""},
  13794. };
  13795. for (const char &c : " \t\r\n") {
  13796. auto res =
  13797. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13798. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13799. ASSERT_FALSE(res);
  13800. }
  13801. }
  13802. TEST(MultipartFormDataTest, PutFormData) {
  13803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13804. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13805. const ContentReader &content_reader) {
  13806. if (req.is_multipart_form_data()) {
  13807. std::vector<FormData> items;
  13808. content_reader(
  13809. [&](const FormData &file) {
  13810. items.push_back(file);
  13811. return true;
  13812. },
  13813. [&](const char *data, size_t data_length) {
  13814. items.back().content.append(data, data_length);
  13815. return true;
  13816. });
  13817. EXPECT_TRUE(std::string(items[0].name) == "document");
  13818. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13819. EXPECT_TRUE(items[0].filename == "2MB_data");
  13820. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13821. EXPECT_TRUE(items[1].name == "hello");
  13822. EXPECT_TRUE(items[1].content == "world");
  13823. EXPECT_TRUE(items[1].filename == "");
  13824. EXPECT_TRUE(items[1].content_type == "");
  13825. } else {
  13826. std::string body;
  13827. content_reader([&](const char *data, size_t data_length) {
  13828. body.append(data, data_length);
  13829. return true;
  13830. });
  13831. }
  13832. });
  13833. auto port = svr.bind_to_any_port("localhost");
  13834. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13835. auto se = detail::scope_exit([&] {
  13836. svr.stop();
  13837. t.join();
  13838. ASSERT_FALSE(svr.is_running());
  13839. });
  13840. svr.wait_until_ready();
  13841. {
  13842. std::string data(1024 * 1024 * 2, '&');
  13843. std::stringstream buffer;
  13844. buffer << data;
  13845. SSLClient cli("localhost", port);
  13846. cli.enable_server_certificate_verification(false);
  13847. UploadFormDataItems items{
  13848. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13849. {"hello", "world", "", ""},
  13850. };
  13851. auto res = cli.Put("/put", items);
  13852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13853. ASSERT_EQ(StatusCode::OK_200, res->status);
  13854. }
  13855. }
  13856. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13857. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13858. svr.Put("/put_customboundary",
  13859. [&](const Request &req, const Response & /*res*/,
  13860. const ContentReader &content_reader) {
  13861. if (req.is_multipart_form_data()) {
  13862. std::vector<FormData> items;
  13863. content_reader(
  13864. [&](const FormData &file) {
  13865. items.push_back(file);
  13866. return true;
  13867. },
  13868. [&](const char *data, size_t data_length) {
  13869. items.back().content.append(data, data_length);
  13870. return true;
  13871. });
  13872. EXPECT_TRUE(std::string(items[0].name) == "document");
  13873. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13874. EXPECT_TRUE(items[0].filename == "2MB_data");
  13875. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13876. EXPECT_TRUE(items[1].name == "hello");
  13877. EXPECT_TRUE(items[1].content == "world");
  13878. EXPECT_TRUE(items[1].filename == "");
  13879. EXPECT_TRUE(items[1].content_type == "");
  13880. } else {
  13881. std::string body;
  13882. content_reader([&](const char *data, size_t data_length) {
  13883. body.append(data, data_length);
  13884. return true;
  13885. });
  13886. }
  13887. });
  13888. auto port = svr.bind_to_any_port("localhost");
  13889. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13890. auto se = detail::scope_exit([&] {
  13891. svr.stop();
  13892. t.join();
  13893. ASSERT_FALSE(svr.is_running());
  13894. });
  13895. svr.wait_until_ready();
  13896. {
  13897. std::string data(1024 * 1024 * 2, '&');
  13898. std::stringstream buffer;
  13899. buffer << data;
  13900. SSLClient cli("localhost", port);
  13901. cli.enable_server_certificate_verification(false);
  13902. UploadFormDataItems items{
  13903. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13904. {"hello", "world", "", ""},
  13905. };
  13906. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13908. ASSERT_EQ(StatusCode::OK_200, res->status);
  13909. }
  13910. }
  13911. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13912. std::string data(1024 * 1024 * 2, '&');
  13913. std::stringstream buffer;
  13914. buffer << data;
  13915. Client cli("https://localhost:8080");
  13916. cli.enable_server_certificate_verification(false);
  13917. UploadFormDataItems items{
  13918. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13919. {"hello", "world", "", ""},
  13920. };
  13921. for (const char &c : " \t\r\n") {
  13922. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13923. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13924. ASSERT_FALSE(res);
  13925. }
  13926. }
  13927. TEST(MultipartFormDataTest, AlternateFilename) {
  13928. auto handled = false;
  13929. Server svr;
  13930. svr.Post("/test", [&](const Request &req, Response &res) {
  13931. ASSERT_EQ(2u, req.form.files.size());
  13932. ASSERT_EQ(1u, req.form.fields.size());
  13933. // Test files
  13934. const auto &file1 = req.form.get_file("file1");
  13935. ASSERT_EQ("file1", file1.name);
  13936. ASSERT_EQ("A.txt", file1.filename);
  13937. ASSERT_EQ("text/plain", file1.content_type);
  13938. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13939. const auto &file2 = req.form.get_file("file2");
  13940. ASSERT_EQ("file2", file2.name);
  13941. ASSERT_EQ("a.html", file2.filename);
  13942. ASSERT_EQ("text/html", file2.content_type);
  13943. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13944. file2.content);
  13945. // Test text field
  13946. const auto &text = req.form.get_field("text");
  13947. ASSERT_EQ("text default", text);
  13948. res.set_content("ok", "text/plain");
  13949. handled = true;
  13950. });
  13951. thread t = thread([&] { svr.listen(HOST, PORT); });
  13952. auto se = detail::scope_exit([&] {
  13953. svr.stop();
  13954. t.join();
  13955. ASSERT_FALSE(svr.is_running());
  13956. ASSERT_TRUE(handled);
  13957. });
  13958. svr.wait_until_ready();
  13959. auto req = "POST /test HTTP/1.1\r\n"
  13960. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13961. "Content-Length: 399\r\n"
  13962. "\r\n"
  13963. "----------\r\n"
  13964. "Content-Disposition: form-data; name=\"text\"\r\n"
  13965. "\r\n"
  13966. "text default\r\n"
  13967. "----------\r\n"
  13968. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13969. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13970. "Content-Type: text/plain\r\n"
  13971. "\r\n"
  13972. "Content of a.txt.\r\n"
  13973. "\r\n"
  13974. "----------\r\n"
  13975. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13976. "\"a.html\"\r\n"
  13977. "Content-Type: text/html\r\n"
  13978. "\r\n"
  13979. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13980. "\r\n"
  13981. "------------\r\n";
  13982. ASSERT_TRUE(send_request(1, req));
  13983. }
  13984. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13985. auto handled = false;
  13986. Server svr;
  13987. svr.Post("/test", [&](const Request &req, Response &res) {
  13988. // Case-insensitive "utf-8''" prefix with a long value
  13989. const auto &file = req.form.get_file("file1");
  13990. ASSERT_EQ("file1", file.name);
  13991. // 8000 chars exercises both the Content-Disposition parser and the
  13992. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13993. // Prior to the fix, std::regex_match on this header would cause O(N)
  13994. // stack recursion in libstdc++, leading to SIGSEGV.
  13995. std::string expected_filename(8000, 'A');
  13996. ASSERT_EQ(expected_filename, file.filename);
  13997. res.set_content("ok", "text/plain");
  13998. handled = true;
  13999. });
  14000. thread t = thread([&] { svr.listen(HOST, PORT); });
  14001. auto se = detail::scope_exit([&] {
  14002. svr.stop();
  14003. t.join();
  14004. ASSERT_FALSE(svr.is_running());
  14005. ASSERT_TRUE(handled);
  14006. });
  14007. svr.wait_until_ready();
  14008. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14009. // Regression test for GHSA-qq6v-r583-3h69
  14010. std::string long_filename(8000, 'A');
  14011. std::string body = "----------\r\n"
  14012. "Content-Disposition: form-data; name=\"file1\"; "
  14013. "filename*=\"Utf-8''" +
  14014. long_filename +
  14015. "\"\r\n"
  14016. "\r\n"
  14017. "hello\r\n"
  14018. "------------\r\n";
  14019. auto req = "POST /test HTTP/1.1\r\n"
  14020. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14021. "Content-Length: " +
  14022. std::to_string(body.size()) + "\r\n\r\n" + body;
  14023. ASSERT_TRUE(send_request(1, req));
  14024. }
  14025. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14026. auto handled = false;
  14027. Server svr;
  14028. svr.Post("/test", [&](const Request &req, Response &) {
  14029. ASSERT_EQ(2u, req.form.fields.size());
  14030. const auto &text1 = req.form.get_field("text1");
  14031. ASSERT_EQ("text1", text1);
  14032. const auto &text2 = req.form.get_field("text2");
  14033. ASSERT_EQ("text2", text2);
  14034. handled = true;
  14035. });
  14036. thread t = thread([&] { svr.listen(HOST, PORT); });
  14037. auto se = detail::scope_exit([&] {
  14038. svr.stop();
  14039. t.join();
  14040. ASSERT_FALSE(svr.is_running());
  14041. ASSERT_TRUE(handled);
  14042. });
  14043. svr.wait_until_ready();
  14044. auto req = "POST /test HTTP/1.1\r\n"
  14045. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14046. "Content-Length: 146\r\n"
  14047. "\r\n----------\r\n"
  14048. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14049. "\r\n"
  14050. "text1"
  14051. "\r\n----------\r\n"
  14052. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14053. "\r\n"
  14054. "text2"
  14055. "\r\n------------";
  14056. std::string response;
  14057. ASSERT_TRUE(send_request(1, req, &response));
  14058. ASSERT_EQ("200", response.substr(9, 3));
  14059. }
  14060. TEST(MultipartFormDataTest, ContentLength) {
  14061. auto handled = false;
  14062. Server svr;
  14063. svr.Post("/test", [&](const Request &req, Response &) {
  14064. ASSERT_EQ(2u, req.form.fields.size());
  14065. const auto &text1 = req.form.get_field("text1");
  14066. ASSERT_EQ("text1", text1);
  14067. const auto &text2 = req.form.get_field("text2");
  14068. ASSERT_EQ("text2", text2);
  14069. handled = true;
  14070. });
  14071. thread t = thread([&] { svr.listen(HOST, PORT); });
  14072. auto se = detail::scope_exit([&] {
  14073. svr.stop();
  14074. t.join();
  14075. ASSERT_FALSE(svr.is_running());
  14076. ASSERT_TRUE(handled);
  14077. });
  14078. svr.wait_until_ready();
  14079. auto req = "POST /test HTTP/1.1\r\n"
  14080. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14081. "Content-Length: 167\r\n"
  14082. "\r\n----------\r\n"
  14083. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14084. "Content-Length: 5\r\n"
  14085. "\r\n"
  14086. "text1"
  14087. "\r\n----------\r\n"
  14088. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14089. "\r\n"
  14090. "text2"
  14091. "\r\n------------\r\n";
  14092. std::string response;
  14093. ASSERT_TRUE(send_request(1, req, &response));
  14094. ASSERT_EQ("200", response.substr(9, 3));
  14095. }
  14096. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14097. auto handled = false;
  14098. Server svr;
  14099. svr.Post("/test", [&](const Request &req, Response &) {
  14100. ASSERT_EQ(2u, req.form.fields.size());
  14101. const auto &text1 = req.form.get_field("text1");
  14102. ASSERT_EQ("text1", text1);
  14103. // TODO: Add header access for text fields if needed
  14104. const auto &text2 = req.form.get_field("text2");
  14105. ASSERT_EQ("text2", text2);
  14106. // TODO: Header access for text fields needs to be implemented
  14107. // auto &headers = it->second.headers;
  14108. // ASSERT_EQ(3U, headers.size());
  14109. // auto custom_header = headers.find("x-whatever");
  14110. // ASSERT_TRUE(custom_header != headers.end());
  14111. // ASSERT_NE("customvalue", custom_header->second);
  14112. // ASSERT_EQ("CustomValue", custom_header->second);
  14113. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14114. handled = true;
  14115. });
  14116. thread t = thread([&] { svr.listen(HOST, PORT); });
  14117. auto se = detail::scope_exit([&] {
  14118. svr.stop();
  14119. t.join();
  14120. ASSERT_FALSE(svr.is_running());
  14121. ASSERT_TRUE(handled);
  14122. });
  14123. svr.wait_until_ready();
  14124. auto req = "POST /test HTTP/1.1\r\n"
  14125. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14126. "Content-Length: 232\r\n"
  14127. "\r\n----------\r\n"
  14128. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14129. "Content-Length: 5\r\n"
  14130. "X-Test: 1\r\n"
  14131. "\r\n"
  14132. "text1"
  14133. "\r\n----------\r\n"
  14134. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14135. "Content-Type: text/plain\r\n"
  14136. "X-Whatever: CustomValue\r\n"
  14137. "\r\n"
  14138. "text2"
  14139. "\r\n------------\r\n"
  14140. "That should be disregarded. Not even read";
  14141. std::string response;
  14142. ASSERT_TRUE(send_request(1, req, &response));
  14143. ASSERT_EQ("200", response.substr(9, 3));
  14144. }
  14145. TEST(MultipartFormDataTest, LargeHeader) {
  14146. auto handled = false;
  14147. Server svr;
  14148. svr.Post("/test", [&](const Request &req, Response &) {
  14149. ASSERT_EQ(1u, req.form.fields.size());
  14150. const auto &text = req.form.get_field("name1");
  14151. ASSERT_EQ("text1", text);
  14152. handled = true;
  14153. });
  14154. thread t = thread([&] { svr.listen(HOST, PORT); });
  14155. auto se = detail::scope_exit([&] {
  14156. svr.stop();
  14157. t.join();
  14158. ASSERT_FALSE(svr.is_running());
  14159. ASSERT_TRUE(handled);
  14160. });
  14161. svr.wait_until_ready();
  14162. auto boundary = std::string("cpp-httplib-multipart-data");
  14163. std::string content = "--" + boundary +
  14164. "\r\n"
  14165. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14166. "\r\n"
  14167. "text1\r\n"
  14168. "--" +
  14169. boundary + "--\r\n";
  14170. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14171. "Content-Type: multipart/form-data;boundary=" +
  14172. boundary +
  14173. "\r\n"
  14174. "Content-Length: " +
  14175. std::to_string(content.size()) +
  14176. "\r\n"
  14177. "Dummy-Header: ";
  14178. std::string header_suffix = "\r\n"
  14179. "\r\n";
  14180. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14181. size_t header_dummy_size =
  14182. read_buff_size -
  14183. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14184. auto header_dummy = std::string(header_dummy_size, '@');
  14185. auto req = header_prefix + header_dummy + header_suffix + content;
  14186. std::string response;
  14187. ASSERT_TRUE(send_request(1, req, &response));
  14188. ASSERT_EQ("200", response.substr(9, 3));
  14189. }
  14190. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14191. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14192. // (not chunked Transfer-Encoding) after the streaming refactor.
  14193. auto handled = false;
  14194. Server svr;
  14195. svr.Post("/upload", [&](const Request &req, Response &res) {
  14196. auto cl_it = req.headers.find("Content-Length");
  14197. EXPECT_TRUE(cl_it != req.headers.end());
  14198. auto te_it = req.headers.find("Transfer-Encoding");
  14199. EXPECT_TRUE(te_it == req.headers.end());
  14200. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14201. res.set_content("ok", "text/plain");
  14202. handled = true;
  14203. });
  14204. auto port = svr.bind_to_any_port(HOST);
  14205. auto t = thread([&] { svr.listen_after_bind(); });
  14206. auto se = detail::scope_exit([&] {
  14207. svr.stop();
  14208. t.join();
  14209. ASSERT_FALSE(svr.is_running());
  14210. ASSERT_TRUE(handled);
  14211. });
  14212. svr.wait_until_ready();
  14213. UploadFormDataItems items = {
  14214. {"field1", "hello", "", "text/plain"},
  14215. {"file1", "world", "test.txt", "application/octet-stream"},
  14216. };
  14217. Client cli(HOST, port);
  14218. auto res = cli.Post("/upload", {}, items);
  14219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14220. EXPECT_EQ(StatusCode::OK_200, res->status);
  14221. }
  14222. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14223. // Verify that make_multipart_content_provider coalesces many small segments
  14224. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14225. constexpr size_t kItemCount = 1000;
  14226. UploadFormDataItems items;
  14227. items.reserve(kItemCount);
  14228. for (size_t i = 0; i < kItemCount; i++) {
  14229. items.push_back(
  14230. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14231. }
  14232. const std::string boundary = "----test-boundary";
  14233. auto content_length = detail::get_multipart_content_length(items, boundary);
  14234. auto provider = detail::make_multipart_content_provider(items, boundary);
  14235. // Drive the provider the same way write_content_with_progress does
  14236. size_t write_count = 0;
  14237. size_t total_bytes = 0;
  14238. DataSink sink;
  14239. size_t offset = 0;
  14240. sink.write = [&](const char *d, size_t l) -> bool {
  14241. (void)d;
  14242. write_count++;
  14243. total_bytes += l;
  14244. offset += l;
  14245. return true;
  14246. };
  14247. sink.is_writable = []() -> bool { return true; };
  14248. while (offset < content_length) {
  14249. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14250. }
  14251. EXPECT_EQ(content_length, total_bytes);
  14252. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14253. // With buffering into 64KB blocks, write_count should be much smaller.
  14254. auto segment_count = 3 * kItemCount + 1;
  14255. EXPECT_LT(write_count, segment_count / 10);
  14256. }
  14257. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14258. // Integration test: send many UploadFormDataItems and verify the server
  14259. // receives all of them correctly (#2410).
  14260. constexpr size_t kItemCount = 500;
  14261. auto handled = false;
  14262. Server svr;
  14263. svr.Post("/upload", [&](const Request &req, Response &res) {
  14264. EXPECT_EQ(kItemCount, req.form.fields.size());
  14265. for (size_t i = 0; i < kItemCount; i++) {
  14266. auto key = "field" + std::to_string(i);
  14267. auto val = "value" + std::to_string(i);
  14268. auto it = req.form.fields.find(key);
  14269. if (it != req.form.fields.end()) {
  14270. EXPECT_EQ(val, it->second.content);
  14271. } else {
  14272. ADD_FAILURE() << "Missing field: " << key;
  14273. }
  14274. }
  14275. res.set_content("ok", "text/plain");
  14276. handled = true;
  14277. });
  14278. auto port = svr.bind_to_any_port(HOST);
  14279. auto t = thread([&] { svr.listen_after_bind(); });
  14280. auto se = detail::scope_exit([&] {
  14281. svr.stop();
  14282. t.join();
  14283. ASSERT_FALSE(svr.is_running());
  14284. ASSERT_TRUE(handled);
  14285. });
  14286. svr.wait_until_ready();
  14287. UploadFormDataItems items;
  14288. items.reserve(kItemCount);
  14289. for (size_t i = 0; i < kItemCount; i++) {
  14290. items.push_back(
  14291. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14292. }
  14293. Client cli(HOST, port);
  14294. auto res = cli.Post("/upload", items);
  14295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14296. EXPECT_EQ(StatusCode::OK_200, res->status);
  14297. }
  14298. TEST(MultipartFormDataTest, MakeFileProvider) {
  14299. // Verify make_file_provider sends a file's contents correctly.
  14300. const std::string file_content(4096, 'Z');
  14301. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14302. {
  14303. std::ofstream ofs(tmp_path, std::ios::binary);
  14304. ofs.write(file_content.data(),
  14305. static_cast<std::streamsize>(file_content.size()));
  14306. }
  14307. auto handled = false;
  14308. Server svr;
  14309. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14310. const ContentReader &content_reader) {
  14311. ASSERT_TRUE(req.is_multipart_form_data());
  14312. std::vector<FormData> items;
  14313. content_reader(
  14314. [&](const FormData &file) {
  14315. items.push_back(file);
  14316. return true;
  14317. },
  14318. [&](const char *data, size_t data_length) {
  14319. items.back().content.append(data, data_length);
  14320. return true;
  14321. });
  14322. ASSERT_EQ(1u, items.size());
  14323. EXPECT_EQ("myfile", items[0].name);
  14324. EXPECT_EQ("data.bin", items[0].filename);
  14325. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14326. EXPECT_EQ(file_content, items[0].content);
  14327. handled = true;
  14328. });
  14329. auto port = svr.bind_to_any_port(HOST);
  14330. auto t = thread([&] { svr.listen_after_bind(); });
  14331. auto se = detail::scope_exit([&] {
  14332. svr.stop();
  14333. t.join();
  14334. ASSERT_FALSE(svr.is_running());
  14335. ASSERT_TRUE(handled);
  14336. std::remove(tmp_path.c_str());
  14337. });
  14338. svr.wait_until_ready();
  14339. FormDataProviderItems providers;
  14340. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14341. "application/octet-stream"));
  14342. Client cli(HOST, port);
  14343. auto res = cli.Post("/upload", {}, {}, providers);
  14344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14345. EXPECT_EQ(StatusCode::OK_200, res->status);
  14346. }
  14347. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14348. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14349. // (100) headers is rejected with a 400 Bad Request response.
  14350. Server svr;
  14351. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14352. res.set_content("ok", "text/plain");
  14353. });
  14354. thread t = thread([&] { svr.listen(HOST, PORT); });
  14355. auto se = detail::scope_exit([&] {
  14356. svr.stop();
  14357. t.join();
  14358. ASSERT_FALSE(svr.is_running());
  14359. });
  14360. svr.wait_until_ready();
  14361. // Build a multipart part with 101 custom headers (exceeding
  14362. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14363. std::stringstream body;
  14364. body << "--simpleboundary\r\n"
  14365. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14366. for (int i = 0; i < 101; i++) {
  14367. body << "X-Custom-Header-" << i << ": value\r\n";
  14368. }
  14369. body << "\r\n"
  14370. << "value1\r\n"
  14371. << "--simpleboundary--\r\n";
  14372. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14373. Client cli(HOST, PORT);
  14374. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14376. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14377. }
  14378. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14379. // A body that never contains the declared boundary must not be accumulated
  14380. // while the parser waits for it. Buffering it would also make every read
  14381. // rescan everything seen so far, which is quadratic in the body size.
  14382. Server svr;
  14383. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14384. res.set_content("ok", "text/plain");
  14385. });
  14386. auto port = svr.bind_to_any_port(HOST);
  14387. thread t = thread([&] { svr.listen_after_bind(); });
  14388. auto se = detail::scope_exit([&] {
  14389. svr.stop();
  14390. t.join();
  14391. ASSERT_FALSE(svr.is_running());
  14392. });
  14393. svr.wait_until_ready();
  14394. Client cli(HOST, port);
  14395. cli.set_read_timeout(60, 0);
  14396. cli.set_write_timeout(60, 0);
  14397. // '-' is the worst case: it matches the first character of the boundary, so
  14398. // every position has to be checked against it.
  14399. auto post_dashes = [&](size_t size) {
  14400. const std::string body(size, '-');
  14401. auto start = std::chrono::steady_clock::now();
  14402. auto res =
  14403. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14404. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14405. std::chrono::steady_clock::now() - start)
  14406. .count();
  14407. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14408. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14409. return ms;
  14410. };
  14411. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14412. // Windows.
  14413. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14414. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14415. // Comparing the two sizes rather than checking an absolute duration keeps
  14416. // this meaningful across build types and CI load, both of which move the
  14417. // absolute numbers by more than an order of magnitude. Four times the bytes
  14418. // costs about four times the time when parsing is linear, and about sixteen
  14419. // times when the body is buffered and rescanned.
  14420. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14421. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14422. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14423. << "ms, which suggests the body is being buffered and rescanned";
  14424. }
  14425. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14426. // A boundary can only be followed by CRLF or by "--", so anything else is
  14427. // malformed no matter what comes next. The parser must say so right away
  14428. // instead of buffering the rest of the declared body.
  14429. Server svr;
  14430. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14431. res.set_content("ok", "text/plain");
  14432. });
  14433. auto port = svr.bind_to_any_port(HOST);
  14434. thread t = thread([&] { svr.listen_after_bind(); });
  14435. auto se = detail::scope_exit([&] {
  14436. svr.stop();
  14437. t.join();
  14438. ASSERT_FALSE(svr.is_running());
  14439. });
  14440. svr.wait_until_ready();
  14441. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14442. // buffers instead of failing would still be waiting for the remaining bytes.
  14443. const std::string body = "--zzzz\r\n"
  14444. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14445. "\r\n"
  14446. "text1"
  14447. "\r\n--zzzzXX";
  14448. const std::string req = "POST /post HTTP/1.1\r\n"
  14449. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14450. "Content-Length: 1048576\r\n"
  14451. "\r\n" +
  14452. body;
  14453. std::string response;
  14454. ASSERT_TRUE(send_request(3, req, &response, port));
  14455. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14456. EXPECT_EQ("400", response.substr(9, 3));
  14457. }
  14458. // Posts a multipart body split into two writes, so that the server sees the
  14459. // split at whatever offset the caller chose, and expects the single "text1"
  14460. // field to come through.
  14461. static void expect_split_multipart_ok(const std::string &body1,
  14462. const std::string &body2) {
  14463. auto handled = false;
  14464. Server svr;
  14465. svr.Post("/post", [&](const Request &req, Response &) {
  14466. EXPECT_EQ(1u, req.form.fields.size());
  14467. EXPECT_EQ("text1", req.form.get_field("text1"));
  14468. handled = true;
  14469. });
  14470. auto port = svr.bind_to_any_port(HOST);
  14471. thread t = thread([&] { svr.listen_after_bind(); });
  14472. auto se = detail::scope_exit([&] {
  14473. svr.stop();
  14474. t.join();
  14475. ASSERT_FALSE(svr.is_running());
  14476. ASSERT_TRUE(handled);
  14477. });
  14478. svr.wait_until_ready();
  14479. // "Connection: close" makes the server close once it has answered, so the
  14480. // response drain ends immediately instead of idling until the read timeout.
  14481. const std::string head =
  14482. "POST /post HTTP/1.1\r\n"
  14483. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14484. "Connection: close\r\n"
  14485. "Content-Length: " +
  14486. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14487. std::string response;
  14488. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14489. ASSERT_GE(response.size(), 12u) << "no response";
  14490. EXPECT_EQ("200", response.substr(9, 3));
  14491. }
  14492. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14493. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14494. // ignored, including when it does not arrive in the same read as the
  14495. // close-delimiter itself.
  14496. expect_split_multipart_ok("--zzzz\r\n"
  14497. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14498. "\r\n"
  14499. "text1"
  14500. "\r\n--zzzz--",
  14501. "\r\nthis epilogue must be ignored\r\n");
  14502. }
  14503. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14504. // The initial boundary may be preceded by a preamble of any length and may
  14505. // straddle a read boundary. Discarding data while waiting for it must not
  14506. // throw away a partial boundary sitting at the end of the buffer.
  14507. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14508. "zz\r\n"
  14509. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14510. "\r\n"
  14511. "text1"
  14512. "\r\n--zzzz--\r\n");
  14513. }
  14514. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14515. // The received boundary was only checked for being non-empty, so it could be
  14516. // as long as a header is allowed to be. The parser scans the body for
  14517. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14518. // costs a nearly full comparison at nearly every position, making the
  14519. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14520. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14521. Server svr;
  14522. svr.Post("/post", [](const Request &req, Response &res) {
  14523. EXPECT_EQ(1u, req.form.fields.size());
  14524. EXPECT_EQ("text1", req.form.get_field("text1"));
  14525. res.set_content("ok", "text/plain");
  14526. });
  14527. auto port = svr.bind_to_any_port(HOST);
  14528. thread t = thread([&] { svr.listen_after_bind(); });
  14529. auto se = detail::scope_exit([&] {
  14530. svr.stop();
  14531. t.join();
  14532. ASSERT_FALSE(svr.is_running());
  14533. });
  14534. svr.wait_until_ready();
  14535. Client cli(HOST, port);
  14536. auto post_with_boundary_of_length = [&](size_t len) {
  14537. const std::string boundary(len, 'a');
  14538. const std::string body =
  14539. "--" + boundary +
  14540. "\r\n"
  14541. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14542. "\r\n"
  14543. "text1"
  14544. "\r\n--" +
  14545. boundary + "--\r\n";
  14546. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14547. };
  14548. auto res = post_with_boundary_of_length(70);
  14549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14550. EXPECT_EQ(StatusCode::OK_200, res->status);
  14551. res = post_with_boundary_of_length(71);
  14552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14553. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14554. }
  14555. TEST(MakeFileBodyTest, Basic) {
  14556. const std::string file_content(4096, 'Z');
  14557. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14558. {
  14559. std::ofstream ofs(tmp_path, std::ios::binary);
  14560. ofs.write(file_content.data(),
  14561. static_cast<std::streamsize>(file_content.size()));
  14562. }
  14563. auto handled = false;
  14564. Server svr;
  14565. svr.Post("/upload", [&](const Request &req, Response &res) {
  14566. EXPECT_EQ(file_content, req.body);
  14567. handled = true;
  14568. res.status = StatusCode::OK_200;
  14569. });
  14570. auto port = svr.bind_to_any_port(HOST);
  14571. auto t = thread([&] { svr.listen_after_bind(); });
  14572. auto se = detail::scope_exit([&] {
  14573. svr.stop();
  14574. t.join();
  14575. ASSERT_FALSE(svr.is_running());
  14576. ASSERT_TRUE(handled);
  14577. std::remove(tmp_path.c_str());
  14578. });
  14579. svr.wait_until_ready();
  14580. auto fb = make_file_body(tmp_path);
  14581. ASSERT_GT(fb.first, 0u);
  14582. Client cli(HOST, port);
  14583. auto res =
  14584. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14586. EXPECT_EQ(StatusCode::OK_200, res->status);
  14587. }
  14588. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14589. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14590. {
  14591. std::ofstream ofs(path, std::ios::binary);
  14592. const std::string content(100, 'A');
  14593. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14594. }
  14595. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14596. auto body = make_file_body(path);
  14597. ASSERT_EQ(100u, body.first);
  14598. ASSERT_TRUE(static_cast<bool>(body.second));
  14599. // Rewritten shorter after its length was measured - and, on a server, after
  14600. // that length has already gone out as Content-Length.
  14601. {
  14602. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14603. const std::string content(10, 'A');
  14604. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14605. }
  14606. std::string written;
  14607. DataSink sink;
  14608. sink.write = [&](const char *d, size_t l) {
  14609. written.append(d, l);
  14610. return true;
  14611. };
  14612. // The provider has to report failure. write_content_with_progress() advances
  14613. // its offset only by what was written, so a provider that returns true
  14614. // without completing the length it promised is called again straight away,
  14615. // and again.
  14616. EXPECT_FALSE(body.second(0, body.first, sink));
  14617. EXPECT_EQ(std::string(10, 'A'), written);
  14618. }
  14619. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14620. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14621. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14622. {
  14623. std::ofstream ofs(path, std::ios::binary);
  14624. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14625. }
  14626. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14627. auto body = make_file_body(path);
  14628. ASSERT_EQ(content.size(), body.first);
  14629. ASSERT_TRUE(static_cast<bool>(body.second));
  14630. std::string written;
  14631. DataSink sink;
  14632. sink.write = [&](const char *d, size_t l) {
  14633. written.append(d, l);
  14634. return true;
  14635. };
  14636. EXPECT_TRUE(body.second(0, body.first, sink));
  14637. EXPECT_EQ(content, written);
  14638. }
  14639. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14640. static constexpr unsigned int number_of_tasks{1000000};
  14641. std::atomic_uint count{0};
  14642. std::unique_ptr<TaskQueue> task_queue{
  14643. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14644. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14645. auto queued = task_queue->enqueue(
  14646. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14647. EXPECT_TRUE(queued);
  14648. }
  14649. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14650. task_queue->shutdown();
  14651. #else
  14652. EXPECT_NO_THROW(task_queue->shutdown());
  14653. #endif
  14654. EXPECT_EQ(number_of_tasks, count.load());
  14655. }
  14656. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14657. static constexpr unsigned int number_of_tasks{1000000};
  14658. static constexpr unsigned int qlimit{2};
  14659. unsigned int queued_count{0};
  14660. std::atomic_uint count{0};
  14661. std::unique_ptr<TaskQueue> task_queue{
  14662. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14663. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14664. if (task_queue->enqueue(
  14665. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14666. queued_count++;
  14667. }
  14668. }
  14669. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14670. task_queue->shutdown();
  14671. #else
  14672. EXPECT_NO_THROW(task_queue->shutdown());
  14673. #endif
  14674. EXPECT_EQ(queued_count, count.load());
  14675. EXPECT_TRUE(queued_count <= number_of_tasks);
  14676. EXPECT_TRUE(queued_count >= qlimit);
  14677. }
  14678. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14679. // Use a short idle timeout so a dynamic thread spawns, times out and
  14680. // exits during the test, and the pool keeps working afterwards.
  14681. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14682. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14683. /*idle_timeout_sec=*/1}};
  14684. std::atomic_uint count{0};
  14685. std::condition_variable cv;
  14686. std::mutex mtx;
  14687. bool release = false;
  14688. // Block the base thread so the second task spawns a dynamic thread.
  14689. EXPECT_TRUE(task_queue->enqueue([&] {
  14690. std::unique_lock<std::mutex> lock(mtx);
  14691. while (!release) {
  14692. cv.wait(lock);
  14693. }
  14694. count++;
  14695. }));
  14696. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14697. // Let the dynamic thread finish its task and exceed the idle timeout.
  14698. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14699. {
  14700. std::unique_lock<std::mutex> lock(mtx);
  14701. release = true;
  14702. }
  14703. cv.notify_all();
  14704. // The pool must still accept and run tasks after the dynamic thread exited.
  14705. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14706. task_queue->shutdown();
  14707. EXPECT_EQ(3u, count.load());
  14708. }
  14709. TEST(TaskQueueTest, MaxQueuedRequests) {
  14710. static constexpr unsigned int qlimit{3};
  14711. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14712. std::condition_variable sem_cv;
  14713. std::mutex sem_mtx;
  14714. int credits = 0;
  14715. bool queued;
  14716. /* Fill up the queue with tasks that will block until we give them credits to
  14717. * complete. */
  14718. for (unsigned int n = 0; n <= qlimit;) {
  14719. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14720. std::unique_lock<std::mutex> lock(sem_mtx);
  14721. while (credits <= 0) {
  14722. sem_cv.wait(lock);
  14723. }
  14724. /* Consume the credit and signal the test code if they are all gone. */
  14725. if (--credits == 0) { sem_cv.notify_one(); }
  14726. });
  14727. if (n < qlimit) {
  14728. /* The first qlimit enqueues must succeed. */
  14729. EXPECT_TRUE(queued);
  14730. } else {
  14731. /* The last one will succeed only when the worker thread
  14732. * starts and dequeues the first blocking task. Although
  14733. * not necessary for the correctness of this test, we sleep for
  14734. * a short while to avoid busy waiting. */
  14735. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14736. }
  14737. if (queued) { n++; }
  14738. }
  14739. /* Further enqueues must fail since the queue is full. */
  14740. for (auto i = 0; i < 4; i++) {
  14741. queued = task_queue->enqueue([] {});
  14742. EXPECT_FALSE(queued);
  14743. }
  14744. /* Give the credits to allow the previous tasks to complete. */
  14745. {
  14746. std::unique_lock<std::mutex> lock(sem_mtx);
  14747. credits += qlimit + 1;
  14748. }
  14749. sem_cv.notify_all();
  14750. /* Wait for all the credits to be consumed. */
  14751. {
  14752. std::unique_lock<std::mutex> lock(sem_mtx);
  14753. while (credits > 0) {
  14754. sem_cv.wait(lock);
  14755. }
  14756. }
  14757. /* Check that we are able again to enqueue at least qlimit tasks. */
  14758. for (unsigned int i = 0; i < qlimit; i++) {
  14759. queued = task_queue->enqueue([] {});
  14760. EXPECT_TRUE(queued);
  14761. }
  14762. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14763. task_queue->shutdown();
  14764. #else
  14765. EXPECT_NO_THROW(task_queue->shutdown());
  14766. #endif
  14767. }
  14768. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  14769. Server svr;
  14770. std::string method;
  14771. std::string body;
  14772. auto has_content_length = false;
  14773. auto has_transfer_encoding = false;
  14774. std::atomic<int> bad_requests{0};
  14775. // Leftover body bytes get parsed as a malformed request and answered with
  14776. // 400
  14777. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  14778. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  14779. });
  14780. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  14781. res.set_redirect("/down", StatusCode::SeeOther_303);
  14782. });
  14783. svr.Get("/down", [&](const Request &req, Response &res) {
  14784. method = req.method;
  14785. body = req.body;
  14786. has_content_length = req.has_header("Content-Length");
  14787. has_transfer_encoding = req.has_header("Transfer-Encoding");
  14788. res.set_content("ok", "text/plain");
  14789. });
  14790. auto port = svr.bind_to_any_port(HOST);
  14791. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14792. auto se = detail::scope_exit([&] {
  14793. svr.stop();
  14794. thread.join();
  14795. ASSERT_FALSE(svr.is_running());
  14796. });
  14797. svr.wait_until_ready();
  14798. const std::string payload = "SECRET-BODY";
  14799. auto check = [&](Client &cli, const Result &res) {
  14800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14801. EXPECT_EQ(StatusCode::OK_200, res->status);
  14802. EXPECT_EQ("ok", res->body);
  14803. EXPECT_EQ("GET", method);
  14804. EXPECT_TRUE(body.empty());
  14805. EXPECT_FALSE(has_content_length);
  14806. EXPECT_FALSE(has_transfer_encoding);
  14807. // Nothing of the original body may be left on the connection
  14808. auto res2 = cli.Get("/down");
  14809. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  14810. EXPECT_EQ(StatusCode::OK_200, res2->status);
  14811. EXPECT_EQ("ok", res2->body);
  14812. EXPECT_EQ(0, bad_requests);
  14813. };
  14814. // With content length
  14815. {
  14816. Client cli(HOST, port);
  14817. cli.set_keep_alive(true);
  14818. cli.set_follow_location(true);
  14819. auto res = cli.Post(
  14820. "/up", payload.size(),
  14821. [&](size_t offset, size_t length, DataSink &sink) {
  14822. return sink.write(payload.data() + offset, length);
  14823. },
  14824. "text/plain");
  14825. check(cli, res);
  14826. }
  14827. // Without content length (chunked)
  14828. {
  14829. Client cli(HOST, port);
  14830. cli.set_keep_alive(true);
  14831. cli.set_follow_location(true);
  14832. auto res = cli.Post(
  14833. "/up",
  14834. [&](size_t /*offset*/, DataSink &sink) {
  14835. sink.write(payload.data(), payload.size());
  14836. sink.done();
  14837. return true;
  14838. },
  14839. "text/plain");
  14840. check(cli, res);
  14841. }
  14842. }
  14843. TEST(RedirectTest, LocationPathIsNotDecoded) {
  14844. Server svr;
  14845. std::string target;
  14846. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  14847. // Echo the still-encoded name back in the Location
  14848. const std::string prefix = "/start/";
  14849. res.status = StatusCode::Found_302;
  14850. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  14851. });
  14852. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  14853. target = req.target;
  14854. res.set_content("ok", "text/plain");
  14855. });
  14856. auto port = svr.bind_to_any_port(HOST);
  14857. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14858. auto se = detail::scope_exit([&] {
  14859. svr.stop();
  14860. thread.join();
  14861. ASSERT_FALSE(svr.is_running());
  14862. });
  14863. svr.wait_until_ready();
  14864. // Decoding the Location path would turn the first four into a path
  14865. // separator, a query delimiter, a fragment delimiter and a different
  14866. // percent-encoded octet. The rest must keep reaching the server as they are.
  14867. const std::vector<std::string> names = {
  14868. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  14869. };
  14870. for (auto path_encode : {true, false}) {
  14871. Client cli(HOST, port);
  14872. cli.set_follow_location(true);
  14873. cli.set_path_encode(path_encode);
  14874. for (const auto &name : names) {
  14875. target.clear();
  14876. auto res = cli.Get("/start/" + name);
  14877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14878. EXPECT_EQ(StatusCode::OK_200, res->status);
  14879. EXPECT_EQ("/dest/" + name, target);
  14880. }
  14881. }
  14882. }
  14883. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14884. Server svr;
  14885. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14886. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14887. });
  14888. svr.Get("/hello", [](const Request &req, Response &res) {
  14889. res.set_content(req.get_param_value("key"), "text/plain");
  14890. });
  14891. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14892. auto se = detail::scope_exit([&] {
  14893. svr.stop();
  14894. thread.join();
  14895. ASSERT_FALSE(svr.is_running());
  14896. });
  14897. svr.wait_until_ready();
  14898. {
  14899. Client cli(HOST, PORT);
  14900. cli.set_follow_location(true);
  14901. auto res = cli.Get("/");
  14902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14903. EXPECT_EQ(StatusCode::OK_200, res->status);
  14904. EXPECT_EQ("val&key2=val2", res->body);
  14905. }
  14906. }
  14907. #endif
  14908. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14909. Server svr;
  14910. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14911. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14912. });
  14913. svr.Get("/hello", [](const Request &req, Response &res) {
  14914. res.set_content(req.get_param_value("key"), "text/plain");
  14915. });
  14916. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14917. auto se = detail::scope_exit([&] {
  14918. svr.stop();
  14919. thread.join();
  14920. ASSERT_FALSE(svr.is_running());
  14921. });
  14922. svr.wait_until_ready();
  14923. {
  14924. Client cli(HOST, PORT);
  14925. cli.set_follow_location(true);
  14926. auto res = cli.Get("/");
  14927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14928. EXPECT_EQ(StatusCode::OK_200, res->status);
  14929. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14930. }
  14931. }
  14932. TEST(RedirectTest, RedirectWithPlusInPath) {
  14933. Server svr;
  14934. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14935. res.set_redirect("/a+b");
  14936. });
  14937. // Route pattern uses regex; escape + as \\+
  14938. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14939. res.set_content(req.path, "text/plain");
  14940. });
  14941. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14942. auto se = detail::scope_exit([&] {
  14943. svr.stop();
  14944. thread.join();
  14945. ASSERT_FALSE(svr.is_running());
  14946. });
  14947. svr.wait_until_ready();
  14948. {
  14949. Client cli(HOST, PORT);
  14950. cli.set_follow_location(true);
  14951. auto res = cli.Get("/");
  14952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14953. EXPECT_EQ(StatusCode::OK_200, res->status);
  14954. EXPECT_EQ("/a+b", res->body);
  14955. }
  14956. }
  14957. TEST(RedirectTest, ResolveRelativeLocation) {
  14958. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  14959. const std::vector<std::pair<std::string, std::string>> cases = {
  14960. {"g", "/b/c/g"},
  14961. {"./g", "/b/c/g"},
  14962. {"g/", "/b/c/g/"},
  14963. {"?y", "/b/c/d;p?y"},
  14964. {"g?y", "/b/c/g?y"},
  14965. {"#s", "/b/c/d;p?q#s"},
  14966. {"g#s", "/b/c/g#s"},
  14967. {"g?y#s", "/b/c/g?y#s"},
  14968. {";x", "/b/c/;x"},
  14969. {"g;x", "/b/c/g;x"},
  14970. {".", "/b/c/"},
  14971. {"./", "/b/c/"},
  14972. {"..", "/b/"},
  14973. {"../", "/b/"},
  14974. {"../g", "/b/g"},
  14975. {"../..", "/"},
  14976. {"../../", "/"},
  14977. {"../../g", "/g"},
  14978. {"../../../g", "/g"},
  14979. {"g.", "/b/c/g."},
  14980. {".g", "/b/c/.g"},
  14981. {"g..", "/b/c/g.."},
  14982. {"..g", "/b/c/..g"},
  14983. {"./../g", "/b/g"},
  14984. {"./g/.", "/b/c/g/"},
  14985. {"g/./h", "/b/c/g/h"},
  14986. {"g/../h", "/b/c/h"},
  14987. {"g;x=1/./y", "/b/c/g;x=1/y"},
  14988. {"g;x=1/../y", "/b/c/y"},
  14989. {"g?y/./x", "/b/c/g?y/./x"},
  14990. {"g#s/../x", "/b/c/g#s/../x"},
  14991. // Not relative-path references, so left for parse_url.
  14992. {"/g", "/g"},
  14993. {"//g", "//g"},
  14994. {"http://g/x", "http://g/x"},
  14995. {"g:h", "g:h"},
  14996. };
  14997. for (const auto &c : cases) {
  14998. EXPECT_EQ(c.second,
  14999. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15000. << c.first;
  15001. }
  15002. }
  15003. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15004. Server svr;
  15005. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15006. res.set_redirect(req.get_param_value("to"));
  15007. });
  15008. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15009. res.set_content(req.target, "text/plain");
  15010. });
  15011. svr.Get("/other", [](const Request &req, Response &res) {
  15012. res.set_content(req.target, "text/plain");
  15013. });
  15014. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15015. auto se = detail::scope_exit([&] {
  15016. svr.stop();
  15017. thread.join();
  15018. ASSERT_FALSE(svr.is_running());
  15019. });
  15020. svr.wait_until_ready();
  15021. const std::vector<std::pair<std::string, std::string>> cases = {
  15022. {"next", "/dir/next"},
  15023. {"./next?x=1", "/dir/next?x=1"},
  15024. {"../other", "/other"},
  15025. };
  15026. for (const auto &c : cases) {
  15027. Client cli(HOST, PORT);
  15028. cli.set_follow_location(true);
  15029. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15030. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15031. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15032. EXPECT_EQ(c.second, res->body) << c.first;
  15033. }
  15034. }
  15035. #ifdef CPPHTTPLIB_SSL_ENABLED
  15036. TEST(RedirectTest, Issue2185_Online) {
  15037. SSLClient client("github.com");
  15038. client.set_follow_location(true);
  15039. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15040. "Coollab-Windows.zip");
  15041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15042. EXPECT_EQ(StatusCode::OK_200, res->status);
  15043. EXPECT_EQ(9920427U, res->body.size());
  15044. }
  15045. #endif
  15046. TEST(VulnerabilityTest, CRLFInjection) {
  15047. Server svr;
  15048. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15049. res.set_content("Hello 1", "text/plain");
  15050. });
  15051. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15052. res.set_content("Hello 2", "text/plain");
  15053. });
  15054. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15055. res.set_content("Hello 3", "text/plain");
  15056. });
  15057. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15058. res.set_content("Hello 4", "text/plain");
  15059. });
  15060. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15061. for (const auto &x : req.headers) {
  15062. auto key = x.first;
  15063. EXPECT_STRNE("evil", key.c_str());
  15064. }
  15065. });
  15066. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15067. auto se = detail::scope_exit([&] {
  15068. svr.stop();
  15069. thread.join();
  15070. ASSERT_FALSE(svr.is_running());
  15071. });
  15072. svr.wait_until_ready();
  15073. {
  15074. Client cli(HOST, PORT);
  15075. cli.Post("/test1", "A=B",
  15076. "application/x-www-form-urlencoded\r\nevil: hello1");
  15077. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15078. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15079. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15080. }
  15081. }
  15082. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15083. auto server_thread = std::thread([] {
  15084. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15085. default_socket_options(srv);
  15086. sockaddr_in addr{};
  15087. addr.sin_family = AF_INET;
  15088. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15089. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15090. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15091. ::listen(srv, 1);
  15092. sockaddr_in cli_addr{};
  15093. socklen_t cli_len = sizeof(cli_addr);
  15094. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15095. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15096. std::string buf_all;
  15097. char buf[2048];
  15098. ssize_t n;
  15099. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15100. buf_all.append(buf, static_cast<size_t>(n));
  15101. size_t pos;
  15102. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15103. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15104. auto e = request_block.find("\r\n");
  15105. if (e != std::string::npos) {
  15106. auto request_line = request_block.substr(0, e);
  15107. std::string msg =
  15108. "CRLF injection detected in request line: '" + request_line + "'";
  15109. EXPECT_FALSE(true) << msg;
  15110. }
  15111. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15112. ::send(cli,
  15113. #ifdef _WIN32
  15114. static_cast<const char *>(resp.c_str()),
  15115. static_cast<int>(resp.size()),
  15116. #else
  15117. resp.c_str(), resp.size(),
  15118. #endif
  15119. 0);
  15120. buf_all.erase(0, pos + 4);
  15121. }
  15122. }
  15123. detail::close_socket(cli);
  15124. detail::close_socket(srv);
  15125. });
  15126. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15127. auto cli = Client("127.0.0.1", PORT + 1);
  15128. auto headers = Headers{
  15129. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15130. {"Connection", "keep-alive"}};
  15131. auto res = cli.Get("/hi", headers);
  15132. EXPECT_FALSE(res);
  15133. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15134. server_thread.join();
  15135. }
  15136. // A request rejected before any byte reaches the socket must fail right away
  15137. // instead of waiting for a response the server will never send.
  15138. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15139. // The kernel completes the TCP handshake from the listen backlog, so the
  15140. // client connects, but nothing ever reads, responds or closes.
  15141. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15142. default_socket_options(srv);
  15143. sockaddr_in addr{};
  15144. addr.sin_family = AF_INET;
  15145. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15146. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15147. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15148. ASSERT_EQ(0, ::listen(srv, 8));
  15149. auto cli = Client("127.0.0.1", PORT + 1);
  15150. cli.set_read_timeout(10, 0);
  15151. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15152. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15153. std::chrono::steady_clock::now() - start)
  15154. .count();
  15155. };
  15156. {
  15157. Request req;
  15158. req.method = "GE T";
  15159. req.path = "/";
  15160. auto start = std::chrono::steady_clock::now();
  15161. auto res = cli.send(req);
  15162. EXPECT_FALSE(res);
  15163. EXPECT_EQ(Error::Write, res.error());
  15164. EXPECT_LT(elapsed_ms(start), 1000);
  15165. }
  15166. {
  15167. auto start = std::chrono::steady_clock::now();
  15168. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15169. EXPECT_FALSE(res);
  15170. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15171. EXPECT_LT(elapsed_ms(start), 1000);
  15172. }
  15173. EXPECT_FALSE(cli.is_socket_open());
  15174. detail::close_socket(srv);
  15175. }
  15176. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15177. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15178. default_socket_options(srv);
  15179. sockaddr_in addr{};
  15180. addr.sin_family = AF_INET;
  15181. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15182. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15183. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15184. ASSERT_EQ(0, ::listen(srv, 1));
  15185. std::string received;
  15186. auto server_thread = std::thread([&] {
  15187. auto sock = ::accept(srv, nullptr, nullptr);
  15188. if (sock == INVALID_SOCKET) { return; }
  15189. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15190. char buf[2048];
  15191. ssize_t n;
  15192. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15193. received.append(buf, static_cast<size_t>(n));
  15194. }
  15195. detail::close_socket(sock);
  15196. });
  15197. {
  15198. auto cli = Client("127.0.0.1", PORT + 1);
  15199. // "Z" sorts after the default headers, so writing straight to the socket
  15200. // would have sent the request line and those headers before the rejection.
  15201. auto handle =
  15202. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15203. EXPECT_FALSE(handle.is_valid());
  15204. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15205. }
  15206. server_thread.join();
  15207. detail::close_socket(srv);
  15208. EXPECT_TRUE(received.empty()) << received;
  15209. }
  15210. TEST(PathParamsTest, StaticMatch) {
  15211. const auto pattern = "/users/all";
  15212. detail::PathParamsMatcher matcher(pattern);
  15213. Request request;
  15214. request.path = "/users/all";
  15215. ASSERT_TRUE(matcher.match(request));
  15216. std::unordered_map<std::string, std::string> expected_params = {};
  15217. EXPECT_EQ(request.path_params, expected_params);
  15218. }
  15219. TEST(PathParamsTest, StaticMismatch) {
  15220. const auto pattern = "/users/all";
  15221. detail::PathParamsMatcher matcher(pattern);
  15222. Request request;
  15223. request.path = "/users/1";
  15224. ASSERT_FALSE(matcher.match(request));
  15225. }
  15226. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15227. const auto pattern = "/users/:id/subscriptions";
  15228. detail::PathParamsMatcher matcher(pattern);
  15229. Request request;
  15230. request.path = "/users/42/subscriptions";
  15231. ASSERT_TRUE(matcher.match(request));
  15232. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15233. EXPECT_EQ(request.path_params, expected_params);
  15234. }
  15235. TEST(PathParamsTest, SingleParamInTheEnd) {
  15236. const auto pattern = "/users/:id";
  15237. detail::PathParamsMatcher matcher(pattern);
  15238. Request request;
  15239. request.path = "/users/24";
  15240. ASSERT_TRUE(matcher.match(request));
  15241. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15242. EXPECT_EQ(request.path_params, expected_params);
  15243. }
  15244. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15245. const auto pattern = "/users/:id/";
  15246. detail::PathParamsMatcher matcher(pattern);
  15247. Request request;
  15248. request.path = "/users/42/";
  15249. ASSERT_TRUE(matcher.match(request));
  15250. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15251. EXPECT_EQ(request.path_params, expected_params);
  15252. }
  15253. TEST(PathParamsTest, EmptyParam) {
  15254. const auto pattern = "/users/:id/";
  15255. detail::PathParamsMatcher matcher(pattern);
  15256. Request request;
  15257. request.path = "/users//";
  15258. ASSERT_TRUE(matcher.match(request));
  15259. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15260. EXPECT_EQ(request.path_params, expected_params);
  15261. }
  15262. TEST(PathParamsTest, FragmentMismatch) {
  15263. const auto pattern = "/users/:id/";
  15264. detail::PathParamsMatcher matcher(pattern);
  15265. Request request;
  15266. request.path = "/admins/24/";
  15267. ASSERT_FALSE(matcher.match(request));
  15268. }
  15269. TEST(PathParamsTest, ExtraFragments) {
  15270. const auto pattern = "/users/:id";
  15271. detail::PathParamsMatcher matcher(pattern);
  15272. Request request;
  15273. request.path = "/users/42/subscriptions";
  15274. ASSERT_FALSE(matcher.match(request));
  15275. }
  15276. TEST(PathParamsTest, MissingTrailingParam) {
  15277. const auto pattern = "/users/:id";
  15278. detail::PathParamsMatcher matcher(pattern);
  15279. Request request;
  15280. request.path = "/users";
  15281. ASSERT_FALSE(matcher.match(request));
  15282. }
  15283. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15284. const auto pattern = "/users/:id/subscriptions";
  15285. detail::PathParamsMatcher matcher(pattern);
  15286. Request request;
  15287. request.path = "/users/subscriptions";
  15288. ASSERT_FALSE(matcher.match(request));
  15289. }
  15290. TEST(PathParamsTest, MultipleParams) {
  15291. const auto pattern = "/users/:userid/subscriptions/:subid";
  15292. detail::PathParamsMatcher matcher(pattern);
  15293. Request request;
  15294. request.path = "/users/42/subscriptions/2";
  15295. ASSERT_TRUE(matcher.match(request));
  15296. std::unordered_map<std::string, std::string> expected_params = {
  15297. {"userid", "42"}, {"subid", "2"}};
  15298. EXPECT_EQ(request.path_params, expected_params);
  15299. }
  15300. TEST(PathParamsTest, SequenceOfParams) {
  15301. const auto pattern = "/values/:x/:y/:z";
  15302. detail::PathParamsMatcher matcher(pattern);
  15303. Request request;
  15304. request.path = "/values/1/2/3";
  15305. ASSERT_TRUE(matcher.match(request));
  15306. std::unordered_map<std::string, std::string> expected_params = {
  15307. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15308. EXPECT_EQ(request.path_params, expected_params);
  15309. }
  15310. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15311. const auto pattern = "/prefix:suffix";
  15312. detail::PathParamsMatcher matcher(pattern);
  15313. Request request;
  15314. request.path = "/prefix:suffix";
  15315. ASSERT_TRUE(matcher.match(request));
  15316. const std::unordered_map<std::string, std::string> expected_params = {};
  15317. EXPECT_EQ(request.path_params, expected_params);
  15318. }
  15319. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15320. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15321. // calling thread's stack on a long enough path for a quantified pattern;
  15322. // RegexMatcher must refuse to run regex matching on paths beyond
  15323. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15324. detail::RegexMatcher matcher("/files/(.*)");
  15325. Request within_limit;
  15326. within_limit.path = "/files/" + std::string(10, 'A');
  15327. EXPECT_TRUE(matcher.match(within_limit));
  15328. Request over_limit;
  15329. over_limit.path =
  15330. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15331. EXPECT_FALSE(matcher.match(over_limit));
  15332. }
  15333. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15334. Server svr;
  15335. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15336. res.set_content("ok", "text/plain");
  15337. });
  15338. auto port = svr.bind_to_any_port(HOST);
  15339. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15340. auto se = detail::scope_exit([&] {
  15341. svr.stop();
  15342. thread.join();
  15343. ASSERT_FALSE(svr.is_running());
  15344. });
  15345. svr.wait_until_ready();
  15346. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15347. // request URI limit; this used to be able to crash the process.
  15348. std::string path =
  15349. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15350. std::string req = "GET " + path +
  15351. " HTTP/1.1\r\n"
  15352. "Host: " +
  15353. std::string(HOST) + ":" + std::to_string(port) +
  15354. "\r\n"
  15355. "Connection: close\r\n"
  15356. "\r\n";
  15357. std::string response;
  15358. ASSERT_TRUE(send_request(5, req, &response, port));
  15359. EXPECT_NE(std::string::npos, response.find("404"));
  15360. }
  15361. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15362. Server svr;
  15363. auto handler = [](const Request & /*req*/, Response &res) {
  15364. res.set_content("hit", "text/plain");
  15365. };
  15366. // No regex metacharacter, so this one is compared literally
  15367. svr.Get("/literal/route", handler);
  15368. // '.' is a regex metacharacter, so this one must keep regex semantics
  15369. svr.Get("/a.c", handler);
  15370. auto port = svr.bind_to_any_port(HOST);
  15371. std::thread t([&]() { svr.listen_after_bind(); });
  15372. auto se = detail::scope_exit([&] {
  15373. svr.stop();
  15374. t.join();
  15375. ASSERT_FALSE(svr.is_running());
  15376. });
  15377. svr.wait_until_ready();
  15378. Client cli(HOST, port);
  15379. struct {
  15380. const char *path;
  15381. int status;
  15382. } cases[] = {
  15383. {"/literal/route", StatusCode::OK_200},
  15384. {"/literal/routes", StatusCode::NotFound_404},
  15385. {"/literal/rout", StatusCode::NotFound_404},
  15386. {"/abc", StatusCode::OK_200},
  15387. {"/a.c", StatusCode::OK_200},
  15388. };
  15389. for (const auto &x : cases) {
  15390. auto res = cli.Get(x.path);
  15391. ASSERT_TRUE(res) << x.path;
  15392. EXPECT_EQ(x.status, res->status) << x.path;
  15393. }
  15394. }
  15395. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15396. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15397. // from exhausting the stack, so it must only constrain routes that actually
  15398. // run a regular expression. A literal route is matched by comparison and
  15399. // stays usable at any length.
  15400. Server svr;
  15401. const std::string pattern =
  15402. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15403. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15404. res.set_content("hit", "text/plain");
  15405. });
  15406. auto port = svr.bind_to_any_port(HOST);
  15407. std::thread t([&]() { svr.listen_after_bind(); });
  15408. auto se = detail::scope_exit([&] {
  15409. svr.stop();
  15410. t.join();
  15411. ASSERT_FALSE(svr.is_running());
  15412. });
  15413. svr.wait_until_ready();
  15414. Client cli(HOST, port);
  15415. auto res = cli.Get(pattern);
  15416. ASSERT_TRUE(res);
  15417. EXPECT_EQ(StatusCode::OK_200, res->status);
  15418. }
  15419. TEST(ParseUrlTest, VariousPatterns) {
  15420. {
  15421. detail::UrlComponents uc;
  15422. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15423. EXPECT_EQ("http", uc.scheme);
  15424. EXPECT_EQ("example.com", uc.host);
  15425. EXPECT_EQ("8080", uc.port);
  15426. EXPECT_EQ("/path", uc.path);
  15427. EXPECT_EQ("?q=1", uc.query);
  15428. }
  15429. {
  15430. detail::UrlComponents uc;
  15431. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15432. EXPECT_EQ("https", uc.scheme);
  15433. EXPECT_EQ("example.com", uc.host);
  15434. EXPECT_TRUE(uc.port.empty());
  15435. EXPECT_EQ("/path", uc.path);
  15436. }
  15437. {
  15438. detail::UrlComponents uc;
  15439. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15440. EXPECT_EQ("::1", uc.host);
  15441. EXPECT_EQ("8080", uc.port);
  15442. EXPECT_EQ("/path", uc.path);
  15443. }
  15444. {
  15445. detail::UrlComponents uc;
  15446. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15447. }
  15448. {
  15449. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15450. // the path while the connection still targets the bracketed host.
  15451. detail::UrlComponents uc;
  15452. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15453. }
  15454. {
  15455. detail::UrlComponents uc;
  15456. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15457. }
  15458. {
  15459. detail::UrlComponents uc;
  15460. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15461. EXPECT_EQ("::1", uc.host);
  15462. EXPECT_TRUE(uc.port.empty());
  15463. EXPECT_EQ("/path", uc.path);
  15464. }
  15465. {
  15466. detail::UrlComponents uc;
  15467. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15468. EXPECT_TRUE(uc.scheme.empty());
  15469. EXPECT_EQ("example.com", uc.host);
  15470. EXPECT_EQ("/path", uc.path);
  15471. EXPECT_EQ("?q=1", uc.query);
  15472. }
  15473. {
  15474. detail::UrlComponents uc;
  15475. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15476. EXPECT_TRUE(uc.host.empty());
  15477. EXPECT_EQ("/path", uc.path);
  15478. EXPECT_EQ("?q=1", uc.query);
  15479. }
  15480. {
  15481. detail::UrlComponents uc;
  15482. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15483. EXPECT_EQ("example.com", uc.host);
  15484. EXPECT_EQ("8080", uc.port);
  15485. }
  15486. {
  15487. // Unix socket path — must not be parsed as host
  15488. detail::UrlComponents uc;
  15489. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15490. EXPECT_TRUE(uc.host.empty());
  15491. }
  15492. {
  15493. detail::UrlComponents uc;
  15494. ASSERT_TRUE(detail::parse_url("", uc));
  15495. EXPECT_TRUE(uc.host.empty());
  15496. EXPECT_TRUE(uc.path.empty());
  15497. }
  15498. {
  15499. detail::UrlComponents uc;
  15500. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15501. }
  15502. {
  15503. detail::UrlComponents uc;
  15504. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15505. }
  15506. {
  15507. // Accepted by parse_url; callers restrict to http/https
  15508. detail::UrlComponents uc;
  15509. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15510. EXPECT_EQ("ftp", uc.scheme);
  15511. }
  15512. {
  15513. detail::UrlComponents uc;
  15514. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15515. }
  15516. {
  15517. detail::UrlComponents uc;
  15518. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15519. }
  15520. }
  15521. TEST(ParseUrlTest, FragmentHandling) {
  15522. {
  15523. detail::UrlComponents uc;
  15524. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15525. EXPECT_EQ("/path", uc.path);
  15526. EXPECT_TRUE(uc.query.empty());
  15527. }
  15528. {
  15529. detail::UrlComponents uc;
  15530. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15531. EXPECT_TRUE(uc.path.empty());
  15532. EXPECT_TRUE(uc.query.empty());
  15533. }
  15534. }
  15535. TEST(ParseUrlTest, UserinfoHandling) {
  15536. // Userinfo with @ but no colon — host includes @
  15537. detail::UrlComponents uc;
  15538. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15539. EXPECT_EQ("user@host.com", uc.host);
  15540. EXPECT_EQ("/path", uc.path);
  15541. }
  15542. TEST(ParseUrlTest, IPv6EdgeCases) {
  15543. {
  15544. detail::UrlComponents uc;
  15545. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15546. EXPECT_TRUE(uc.scheme.empty());
  15547. EXPECT_EQ("::1", uc.host);
  15548. EXPECT_EQ("8080", uc.port);
  15549. }
  15550. {
  15551. // Zone ID '%25' is not in [a-fA-F0-9:]
  15552. detail::UrlComponents uc;
  15553. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15554. }
  15555. }
  15556. TEST(ParseUrlTest, SchemeEdgeCases) {
  15557. {
  15558. detail::UrlComponents uc;
  15559. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15560. }
  15561. {
  15562. detail::UrlComponents uc;
  15563. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15564. }
  15565. {
  15566. detail::UrlComponents uc;
  15567. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15568. }
  15569. }
  15570. TEST(ParseUrlTest, PortEdgeCases) {
  15571. {
  15572. detail::UrlComponents uc;
  15573. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15574. EXPECT_TRUE(uc.port.empty());
  15575. EXPECT_EQ("/path", uc.path);
  15576. }
  15577. {
  15578. // parse_url accepts any port string; validation is done by parse_port
  15579. detail::UrlComponents uc;
  15580. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15581. EXPECT_EQ("abc", uc.port);
  15582. }
  15583. }
  15584. TEST(ParseUrlTest, WebSocketPatterns) {
  15585. {
  15586. detail::UrlComponents uc;
  15587. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15588. EXPECT_EQ("ws", uc.scheme);
  15589. EXPECT_EQ("echo.example.com", uc.host);
  15590. EXPECT_EQ("8080", uc.port);
  15591. EXPECT_EQ("/ws", uc.path);
  15592. }
  15593. {
  15594. detail::UrlComponents uc;
  15595. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15596. EXPECT_EQ("wss", uc.scheme);
  15597. EXPECT_EQ("echo.example.com", uc.host);
  15598. EXPECT_TRUE(uc.port.empty());
  15599. EXPECT_EQ("/ws", uc.path);
  15600. }
  15601. }
  15602. TEST(ParseUrlTest, QueryOnly) {
  15603. detail::UrlComponents uc;
  15604. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15605. EXPECT_TRUE(uc.host.empty());
  15606. EXPECT_TRUE(uc.path.empty());
  15607. EXPECT_EQ("?q=1&r=2", uc.query);
  15608. }
  15609. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15610. detail::UrlComponents uc;
  15611. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15612. EXPECT_TRUE(uc.scheme.empty());
  15613. EXPECT_EQ("example.com", uc.host);
  15614. EXPECT_EQ("443", uc.port);
  15615. EXPECT_EQ("/path", uc.path);
  15616. }
  15617. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15618. // If ipv6 regex working, regex match codepath is taken.
  15619. // else port will default to 80 in Client impl
  15620. int clientImplMagicPort = 80;
  15621. int port = 4321;
  15622. // above ports must be different to avoid false negative
  15623. EXPECT_NE(clientImplMagicPort, port);
  15624. std::string ipV6TestURL = "http://[ff06::c3]";
  15625. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15626. CLIENT_PRIVATE_KEY_FILE);
  15627. EXPECT_EQ(cli.port(), port);
  15628. }
  15629. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15630. auto file_path = "./www/dir/index.html";
  15631. auto dir_path = "./www/dir";
  15632. detail::FileStat stat_file(file_path);
  15633. EXPECT_TRUE(stat_file.is_file());
  15634. EXPECT_FALSE(stat_file.is_dir());
  15635. detail::FileStat stat_dir(dir_path);
  15636. EXPECT_FALSE(stat_dir.is_file());
  15637. EXPECT_TRUE(stat_dir.is_dir());
  15638. }
  15639. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15640. // IPv4 with default HTTP port (80)
  15641. EXPECT_EQ("example.com",
  15642. detail::make_host_and_port_string("example.com", 80, false));
  15643. // IPv4 with default HTTPS port (443)
  15644. EXPECT_EQ("example.com",
  15645. detail::make_host_and_port_string("example.com", 443, true));
  15646. // IPv4 with non-default HTTP port
  15647. EXPECT_EQ("example.com:8080",
  15648. detail::make_host_and_port_string("example.com", 8080, false));
  15649. // IPv4 with non-default HTTPS port
  15650. EXPECT_EQ("example.com:8443",
  15651. detail::make_host_and_port_string("example.com", 8443, true));
  15652. // IPv6 with default HTTP port (80)
  15653. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15654. // IPv6 with default HTTPS port (443)
  15655. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15656. // IPv6 with non-default HTTP port
  15657. EXPECT_EQ("[::1]:8080",
  15658. detail::make_host_and_port_string("::1", 8080, false));
  15659. // IPv6 with non-default HTTPS port
  15660. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15661. // IPv6 full address with default port
  15662. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15663. detail::make_host_and_port_string(
  15664. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15665. // IPv6 full address with non-default port
  15666. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15667. detail::make_host_and_port_string(
  15668. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15669. // IPv6 localhost with non-default port
  15670. EXPECT_EQ("[::1]:3000",
  15671. detail::make_host_and_port_string("::1", 3000, false));
  15672. // IPv6 with zone ID (link-local address) with default port
  15673. EXPECT_EQ("[fe80::1%eth0]",
  15674. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15675. // IPv6 with zone ID (link-local address) with non-default port
  15676. EXPECT_EQ("[fe80::1%eth0]:8080",
  15677. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15678. // Edge case: Port 443 with is_ssl=false (should add port)
  15679. EXPECT_EQ("example.com:443",
  15680. detail::make_host_and_port_string("example.com", 443, false));
  15681. // Edge case: Port 80 with is_ssl=true (should add port)
  15682. EXPECT_EQ("example.com:80",
  15683. detail::make_host_and_port_string("example.com", 80, true));
  15684. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15685. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15686. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15687. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15688. // Security fix: Already bracketed IPv6 should not get double brackets
  15689. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15690. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15691. EXPECT_EQ("[::1]:8080",
  15692. detail::make_host_and_port_string("[::1]", 8080, false));
  15693. EXPECT_EQ("[2001:db8::1]:8080",
  15694. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15695. EXPECT_EQ("[fe80::1%eth0]",
  15696. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15697. EXPECT_EQ("[fe80::1%eth0]:8080",
  15698. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15699. // Edge case: Empty host (should return as-is)
  15700. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15701. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15702. // This is a known limitation but shouldn't crash
  15703. EXPECT_EQ("[host:name]",
  15704. detail::make_host_and_port_string("host:name", 80, false));
  15705. // Port number edge cases (no validation, but should not crash)
  15706. EXPECT_EQ("example.com:0",
  15707. detail::make_host_and_port_string("example.com", 0, false));
  15708. EXPECT_EQ("example.com:-1",
  15709. detail::make_host_and_port_string("example.com", -1, false));
  15710. EXPECT_EQ("example.com:65535",
  15711. detail::make_host_and_port_string("example.com", 65535, false));
  15712. EXPECT_EQ("example.com:65536",
  15713. detail::make_host_and_port_string("example.com", 65536, false));
  15714. }
  15715. #ifdef CPPHTTPLIB_SSL_ENABLED
  15716. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15717. httplib::SSLClient cli("roblox.com", 443);
  15718. cli.set_follow_location(true);
  15719. auto res = cli.Get("/");
  15720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15721. EXPECT_EQ(StatusCode::OK_200, res->status);
  15722. }
  15723. #endif
  15724. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15725. Server svr;
  15726. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15727. EXPECT_EQ(res.status, 400);
  15728. });
  15729. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15730. auto se = detail::scope_exit([&] {
  15731. svr.stop();
  15732. thread.join();
  15733. ASSERT_FALSE(svr.is_running());
  15734. });
  15735. svr.wait_until_ready();
  15736. Client cli(HOST, PORT);
  15737. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15738. }
  15739. TEST(InvalidHeaderCharsTest, is_field_name) {
  15740. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15741. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15742. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15743. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15744. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15745. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15746. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15747. EXPECT_FALSE(detail::fields::is_field_name(""));
  15748. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15749. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15750. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15751. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15752. }
  15753. TEST(InvalidHeaderCharsTest, is_field_value) {
  15754. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15755. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15756. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15757. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15758. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15759. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15760. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15761. EXPECT_TRUE(detail::fields::is_field_value(""));
  15762. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15763. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15764. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15765. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15766. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15767. }
  15768. TEST(InvalidHeaderCharsTest, OnServer) {
  15769. Server svr;
  15770. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15771. std::string header = "Not Set";
  15772. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15773. res.set_header(header, "value");
  15774. res.set_content("Page Content Page Content", "text/plain");
  15775. });
  15776. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15777. std::string header = "Not Set";
  15778. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15779. res.set_header("X-Test", header);
  15780. res.set_content("Page Content Page Content", "text/plain");
  15781. });
  15782. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15783. auto se = detail::scope_exit([&] {
  15784. svr.stop();
  15785. thread.join();
  15786. ASSERT_FALSE(svr.is_running());
  15787. });
  15788. svr.wait_until_ready();
  15789. Client cli(HOST, PORT);
  15790. {
  15791. auto res = cli.Get(
  15792. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15794. EXPECT_EQ("Page Content Page Content", res->body);
  15795. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15796. }
  15797. {
  15798. auto res = cli.Get(
  15799. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15801. EXPECT_EQ("Page Content Page Content", res->body);
  15802. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15803. }
  15804. }
  15805. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15806. auto handled = false;
  15807. Server svr;
  15808. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15809. thread t = thread([&] { svr.listen(HOST, PORT); });
  15810. auto se = detail::scope_exit([&] {
  15811. svr.stop();
  15812. t.join();
  15813. ASSERT_FALSE(svr.is_running());
  15814. ASSERT_FALSE(handled);
  15815. });
  15816. svr.wait_until_ready();
  15817. auto req = "POST /test HTTP/1.1\r\n"
  15818. "Content-Length: x\r\n"
  15819. "\r\n";
  15820. std::string response;
  15821. ASSERT_TRUE(send_request(1, req, &response));
  15822. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15823. response.substr(0, response.find("\r\n")));
  15824. }
  15825. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15826. // case-insensitive, and a server that receives a 100-continue expectation in
  15827. // an HTTP/1.0 request MUST ignore it.
  15828. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15829. std::string response;
  15830. ASSERT_TRUE(send_request(1, req, &response, port));
  15831. *got_100 = response.find("100 Continue") != std::string::npos;
  15832. }
  15833. class ExpectTokenTest : public ::testing::Test {
  15834. protected:
  15835. void SetUp() override {
  15836. svr_.Post("/p", [](const Request &, Response &res) {
  15837. res.set_content("ok", "text/plain");
  15838. });
  15839. port_ = svr_.bind_to_any_port(HOST);
  15840. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15841. svr_.wait_until_ready();
  15842. }
  15843. void TearDown() override {
  15844. svr_.stop();
  15845. if (thread_.joinable()) { thread_.join(); }
  15846. }
  15847. std::string request(const char *version, const char *expect_value) const {
  15848. return std::string("POST /p ") + version +
  15849. "\r\n"
  15850. "Host: localhost\r\n"
  15851. "Content-Length: 2\r\n"
  15852. "Connection: close\r\n"
  15853. "Expect: " +
  15854. expect_value +
  15855. "\r\n"
  15856. "\r\n"
  15857. "hi";
  15858. }
  15859. Server svr_;
  15860. int port_ = 0;
  15861. thread thread_;
  15862. };
  15863. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15864. bool got_100 = false;
  15865. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15866. EXPECT_TRUE(got_100);
  15867. }
  15868. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15869. bool got_100 = true;
  15870. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15871. EXPECT_FALSE(got_100);
  15872. }
  15873. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15874. bool got_100 = false;
  15875. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15876. EXPECT_TRUE(got_100);
  15877. }
  15878. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15879. bool got_100 = false;
  15880. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15881. EXPECT_TRUE(got_100);
  15882. }
  15883. // `100 Continue` is sent only when the server starts reading the body, so a
  15884. // request rejected before that never invites the client to send it. The
  15885. // requests below carry the expectation but withhold the body, as a client
  15886. // waiting for `100 Continue` would.
  15887. // A POST that expects `100 Continue` and withholds its two-byte body.
  15888. static std::string expect_headers_only(const std::string &path) {
  15889. return "POST " + path +
  15890. " HTTP/1.1\r\n"
  15891. "Host: localhost\r\n"
  15892. "Content-Length: 2\r\n"
  15893. "Expect: 100-continue\r\n"
  15894. "\r\n";
  15895. }
  15896. class ExpectLazyContinueTest : public ::testing::Test {
  15897. protected:
  15898. void SetUp() override {
  15899. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15900. if (req.path == "/pre-routing") {
  15901. res.status = StatusCode::Unauthorized_401;
  15902. return Server::HandlerResponse::Handled;
  15903. }
  15904. return Server::HandlerResponse::Unhandled;
  15905. });
  15906. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15907. if (req.matched_route == "/pre-request") {
  15908. res.status = StatusCode::Forbidden_403;
  15909. return Server::HandlerResponse::Handled;
  15910. }
  15911. return Server::HandlerResponse::Unhandled;
  15912. });
  15913. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15914. res.set_content("ok", "text/plain");
  15915. });
  15916. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15917. res.set_content("ok", "text/plain");
  15918. });
  15919. svr_.Post("/reader-used", [](const Request &, Response &res,
  15920. const ContentReader &content_reader) {
  15921. std::string body;
  15922. content_reader([&](const char *data, size_t len) {
  15923. body.append(data, len);
  15924. return true;
  15925. });
  15926. res.set_content(body, "text/plain");
  15927. });
  15928. svr_.Post("/reader-unused",
  15929. [](const Request &, Response &res, const ContentReader &) {
  15930. res.set_content("ignored", "text/plain");
  15931. });
  15932. port_ = svr_.bind_to_any_port(HOST);
  15933. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15934. svr_.wait_until_ready();
  15935. }
  15936. void TearDown() override {
  15937. svr_.stop();
  15938. if (thread_.joinable()) { thread_.join(); }
  15939. }
  15940. // Sends `req` and reads until the server closes the connection. Returns
  15941. // false if the read had to wait for the client-side timeout instead.
  15942. bool send_until_closed(const std::string &req, std::string *resp) const {
  15943. auto start = std::chrono::steady_clock::now();
  15944. if (!send_request(3, req, resp, port_)) { return false; }
  15945. auto elapsed = std::chrono::steady_clock::now() - start;
  15946. return elapsed < std::chrono::seconds(2);
  15947. }
  15948. // The final response comes without `100 Continue`, and the server closes
  15949. // the connection since the body may or may not follow.
  15950. void expect_final_without_interim(const std::string &path,
  15951. const char *status_line) const {
  15952. std::string resp;
  15953. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15954. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15955. EXPECT_EQ(0u, resp.find(status_line));
  15956. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15957. }
  15958. Server svr_;
  15959. int port_ = 0;
  15960. thread thread_;
  15961. };
  15962. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15963. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15964. }
  15965. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15966. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15967. }
  15968. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15969. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15970. }
  15971. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15972. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15973. }
  15974. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15975. // The body follows once `100 Continue` has had time to arrive.
  15976. auto req = expect_headers_only("/reader-used");
  15977. req.insert(req.size() - 2, "Connection: close\r\n");
  15978. std::string resp;
  15979. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15980. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15981. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15982. EXPECT_NE(std::string::npos, resp.find("hi"));
  15983. }
  15984. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15985. // Large enough for the client to add `Expect: 100-continue` itself.
  15986. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15987. std::atomic<bool> body_sent{false};
  15988. Client cli(HOST, port_);
  15989. auto res = cli.Post(
  15990. "/pre-request", length,
  15991. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15992. body_sent = true;
  15993. std::string chunk(len, 'x');
  15994. sink.write(chunk.data(), chunk.size());
  15995. return true;
  15996. },
  15997. "application/octet-stream");
  15998. ASSERT_TRUE(res);
  15999. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16000. EXPECT_FALSE(body_sent);
  16001. }
  16002. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16003. Server svr;
  16004. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16005. return StatusCode::ExpectationFailed_417;
  16006. });
  16007. svr.Post("/p", [](const Request &, Response &res) {
  16008. res.set_content("ok", "text/plain");
  16009. });
  16010. auto port = svr.bind_to_any_port(HOST);
  16011. thread t = thread([&] { svr.listen_after_bind(); });
  16012. auto se = detail::scope_exit([&] {
  16013. svr.stop();
  16014. t.join();
  16015. });
  16016. svr.wait_until_ready();
  16017. std::string resp;
  16018. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16019. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16020. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16021. // Exactly one response: the route handler must not run after the 417.
  16022. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16023. }
  16024. #ifndef _WIN32
  16025. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16026. static constexpr char reject[] = "Unauthorized";
  16027. static constexpr char accept[] = "Upload accepted";
  16028. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16029. Server svr;
  16030. svr.set_expect_100_continue_handler(
  16031. [](const Request & /*req*/, Response &res) {
  16032. res.status = StatusCode::Unauthorized_401;
  16033. res.set_content(reject, "text/plain");
  16034. return res.status;
  16035. });
  16036. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16037. res.set_content(accept, "text/plain");
  16038. });
  16039. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16040. auto se = detail::scope_exit([&] {
  16041. svr.stop();
  16042. thread.join();
  16043. ASSERT_FALSE(svr.is_running());
  16044. });
  16045. svr.wait_until_ready();
  16046. {
  16047. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16048. curl_easy_init(), &curl_easy_cleanup};
  16049. ASSERT_NE(curl, nullptr);
  16050. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16051. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16052. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16053. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16054. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16055. &curl_slist_free_all};
  16056. ASSERT_NE(list, nullptr);
  16057. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16058. struct read_data {
  16059. size_t read_size;
  16060. size_t total_size;
  16061. } data = {0, total_size};
  16062. using read_callback_t =
  16063. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16064. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16065. void *userdata) -> size_t {
  16066. read_data *d = (read_data *)userdata;
  16067. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16068. std::fill_n(ptr, size * nmemb, 'A');
  16069. d->read_size += size * nmemb;
  16070. return size * nmemb;
  16071. };
  16072. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16073. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16074. std::vector<char> buffer;
  16075. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16076. using write_callback_t =
  16077. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16078. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16079. void *userdata) -> size_t {
  16080. std::vector<char> *buf = (std::vector<char> *)userdata;
  16081. buf->reserve(buf->size() + size * nmemb + 1);
  16082. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16083. return size * nmemb;
  16084. };
  16085. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16086. {
  16087. const auto res = curl_easy_perform(curl.get());
  16088. ASSERT_EQ(res, CURLE_OK);
  16089. }
  16090. {
  16091. auto response_code = long{};
  16092. const auto res =
  16093. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16094. ASSERT_EQ(res, CURLE_OK);
  16095. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16096. }
  16097. {
  16098. auto dl = curl_off_t{};
  16099. const auto res =
  16100. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16101. ASSERT_EQ(res, CURLE_OK);
  16102. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16103. }
  16104. {
  16105. buffer.push_back('\0');
  16106. ASSERT_STRCASEEQ(buffer.data(), reject);
  16107. }
  16108. }
  16109. }
  16110. #endif
  16111. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16112. // Regression test for #2458.
  16113. //
  16114. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16115. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16116. // ticket can make the client socket spuriously readable during the
  16117. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16118. // the client withholds the body and then blocks reading a response that never
  16119. // comes, failing with `Failed to read connection`.
  16120. //
  16121. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16122. // within the timeout. This raw OpenSSL server deliberately never sends
  16123. // `100 Continue`; the client must still deliver the body and receive 200.
  16124. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16125. signal(SIGPIPE, SIG_IGN);
  16126. const auto port = PORT + 4;
  16127. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16128. ASSERT_NE(srv, INVALID_SOCKET);
  16129. int opt = 1;
  16130. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16131. sockaddr_in addr{};
  16132. addr.sin_family = AF_INET;
  16133. addr.sin_port = htons(static_cast<uint16_t>(port));
  16134. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16135. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16136. ASSERT_EQ(0, ::listen(srv, 1));
  16137. std::atomic<size_t> server_body_bytes{0};
  16138. auto server_thread = std::thread([&] {
  16139. sockaddr_in cli_addr{};
  16140. socklen_t cli_len = sizeof(cli_addr);
  16141. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16142. if (cli == INVALID_SOCKET) { return; }
  16143. // Bound the lifetime of the server side so a buggy client (which never
  16144. // sends the body) cannot make this thread block forever on join.
  16145. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16146. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16147. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16148. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16149. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16150. SSL *ssl = SSL_new(ctx);
  16151. SSL_set_fd(ssl, static_cast<int>(cli));
  16152. if (SSL_accept(ssl) > 0) {
  16153. // Read the request headers. Reading here also flushes the TLS 1.3
  16154. // session tickets to the client. Deliberately do NOT send
  16155. // `100 Continue`.
  16156. std::string buf;
  16157. char tmp[1024];
  16158. while (buf.find("\r\n\r\n") == std::string::npos) {
  16159. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16160. if (n <= 0) { break; }
  16161. buf.append(tmp, static_cast<size_t>(n));
  16162. }
  16163. // A correct client sends the body now; count what arrives.
  16164. auto pos = buf.find("\r\n\r\n");
  16165. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16166. while (body < 4096) {
  16167. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16168. if (n <= 0) { break; }
  16169. body += static_cast<size_t>(n);
  16170. }
  16171. server_body_bytes = body;
  16172. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16173. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16174. SSL_shutdown(ssl);
  16175. }
  16176. SSL_free(ssl);
  16177. detail::close_socket(cli);
  16178. SSL_CTX_free(ctx);
  16179. });
  16180. auto se = detail::scope_exit([&] {
  16181. server_thread.join();
  16182. detail::close_socket(srv);
  16183. });
  16184. SSLClient cli("127.0.0.1", port);
  16185. cli.enable_server_certificate_verification(false);
  16186. cli.set_connection_timeout(5, 0);
  16187. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16188. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16189. std::string body(4096, 'A');
  16190. auto res = cli.Put("/api/test", body, "application/json");
  16191. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16192. EXPECT_EQ(StatusCode::OK_200, res->status);
  16193. EXPECT_EQ(body.size(), server_body_bytes.load());
  16194. }
  16195. #endif
  16196. template <typename S, typename C>
  16197. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16198. svr.Get("/stream", [&](const Request &, Response &res) {
  16199. auto data = new std::string("01234567890123456789");
  16200. res.set_content_provider(
  16201. data->size(), "text/plain",
  16202. [&, data](size_t offset, size_t length, DataSink &sink) {
  16203. const size_t DATA_CHUNK_SIZE = 4;
  16204. const auto &d = *data;
  16205. std::this_thread::sleep_for(std::chrono::seconds(1));
  16206. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16207. return true;
  16208. },
  16209. [data](bool success) {
  16210. EXPECT_FALSE(success);
  16211. delete data;
  16212. });
  16213. });
  16214. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16215. auto i = new size_t(0);
  16216. res.set_content_provider(
  16217. "text/plain",
  16218. [i](size_t, DataSink &sink) {
  16219. if (*i < 5) {
  16220. std::this_thread::sleep_for(std::chrono::seconds(1));
  16221. sink.write("abcd", 4);
  16222. (*i)++;
  16223. } else {
  16224. sink.done();
  16225. }
  16226. return true;
  16227. },
  16228. [i](bool success) {
  16229. EXPECT_FALSE(success);
  16230. delete i;
  16231. });
  16232. });
  16233. svr.Get("/chunked", [&](const Request &, Response &res) {
  16234. auto i = new size_t(0);
  16235. res.set_chunked_content_provider(
  16236. "text/plain",
  16237. [i](size_t, DataSink &sink) {
  16238. if (*i < 5) {
  16239. std::this_thread::sleep_for(std::chrono::seconds(1));
  16240. sink.os << "abcd";
  16241. (*i)++;
  16242. } else {
  16243. sink.done();
  16244. }
  16245. return true;
  16246. },
  16247. [i](bool success) {
  16248. EXPECT_FALSE(success);
  16249. delete i;
  16250. });
  16251. });
  16252. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16253. auto se = detail::scope_exit([&] {
  16254. svr.stop();
  16255. listen_thread.join();
  16256. ASSERT_FALSE(svr.is_running());
  16257. });
  16258. svr.wait_until_ready();
  16259. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16260. {
  16261. auto start = std::chrono::steady_clock::now();
  16262. auto res = cli.Get("/stream");
  16263. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16264. std::chrono::steady_clock::now() - start)
  16265. .count();
  16266. ASSERT_FALSE(res);
  16267. EXPECT_EQ(Error::Read, res.error());
  16268. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16269. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16270. }
  16271. {
  16272. auto start = std::chrono::steady_clock::now();
  16273. auto res = cli.Get("/stream_without_length");
  16274. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16275. std::chrono::steady_clock::now() - start)
  16276. .count();
  16277. ASSERT_FALSE(res);
  16278. EXPECT_EQ(Error::Read, res.error());
  16279. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16280. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16281. }
  16282. {
  16283. auto start = std::chrono::steady_clock::now();
  16284. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16285. EXPECT_EQ("abcd", string(data, data_length));
  16286. return true;
  16287. });
  16288. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16289. std::chrono::steady_clock::now() - start)
  16290. .count();
  16291. ASSERT_FALSE(res);
  16292. EXPECT_EQ(Error::Read, res.error());
  16293. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16294. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16295. }
  16296. }
  16297. TEST(MaxTimeoutTest, ContentStream) {
  16298. time_t timeout = 2000;
  16299. time_t threshold = 200;
  16300. Server svr;
  16301. Client cli("localhost", PORT);
  16302. max_timeout_test(svr, cli, timeout, threshold);
  16303. }
  16304. #ifdef CPPHTTPLIB_SSL_ENABLED
  16305. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16306. time_t timeout = 2000;
  16307. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16308. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16309. SSLClient cli("localhost", PORT);
  16310. cli.enable_server_certificate_verification(false);
  16311. max_timeout_test(svr, cli, timeout, threshold);
  16312. }
  16313. #endif
  16314. class EventDispatcher {
  16315. public:
  16316. EventDispatcher() {}
  16317. bool wait_event(DataSink *sink) {
  16318. unique_lock<mutex> lk(m_);
  16319. int id = id_;
  16320. // Wait with timeout to prevent hanging if client disconnects
  16321. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16322. [&] { return cid_ == id; })) {
  16323. return false; // Timeout occurred
  16324. }
  16325. sink->write(message_.data(), message_.size());
  16326. return true;
  16327. }
  16328. void send_event(const string &message) {
  16329. lock_guard<mutex> lk(m_);
  16330. cid_ = id_++;
  16331. message_ = message;
  16332. cv_.notify_all();
  16333. }
  16334. private:
  16335. mutex m_;
  16336. condition_variable cv_;
  16337. atomic_int id_{0};
  16338. atomic_int cid_{-1};
  16339. string message_;
  16340. };
  16341. TEST(ClientInThreadTest, Issue2068) {
  16342. EventDispatcher ed;
  16343. Server svr;
  16344. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16345. res.set_chunked_content_provider("text/event-stream",
  16346. [&](size_t /*offset*/, DataSink &sink) {
  16347. return ed.wait_event(&sink);
  16348. });
  16349. });
  16350. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16351. svr.wait_until_ready();
  16352. thread event_thread([&] {
  16353. int id = 0;
  16354. while (svr.is_running()) {
  16355. this_thread::sleep_for(chrono::milliseconds(500));
  16356. std::stringstream ss;
  16357. ss << "data: " << id << "\n\n";
  16358. ed.send_event(ss.str());
  16359. id++;
  16360. }
  16361. });
  16362. auto se = detail::scope_exit([&] {
  16363. svr.stop();
  16364. listen_thread.join();
  16365. event_thread.join();
  16366. ASSERT_FALSE(svr.is_running());
  16367. });
  16368. {
  16369. auto client = detail::make_unique<Client>(HOST, PORT);
  16370. client->set_read_timeout(std::chrono::minutes(10));
  16371. std::atomic<bool> stop{false};
  16372. std::thread t([&] {
  16373. client->Get("/event1",
  16374. [&](const char *, size_t) -> bool { return !stop; });
  16375. });
  16376. std::this_thread::sleep_for(std::chrono::seconds(2));
  16377. stop = true;
  16378. client->stop();
  16379. t.join();
  16380. // Reset client after thread has finished
  16381. client.reset();
  16382. }
  16383. }
  16384. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16385. auto handled = false;
  16386. Server svr;
  16387. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16388. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16389. auto se = detail::scope_exit([&] {
  16390. svr.stop();
  16391. t.join();
  16392. ASSERT_FALSE(svr.is_running());
  16393. ASSERT_FALSE(handled);
  16394. });
  16395. svr.wait_until_ready();
  16396. // Two Content-Length headers with different values — must be rejected
  16397. auto req = "POST /test HTTP/1.1\r\n"
  16398. "Content-Length: 5\r\n"
  16399. "Content-Length: 10\r\n"
  16400. "\r\n"
  16401. "hello";
  16402. std::string response;
  16403. ASSERT_TRUE(send_request(1, req, &response));
  16404. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16405. response.substr(0, response.find("\r\n")));
  16406. }
  16407. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16408. auto handled = false;
  16409. Server svr;
  16410. svr.Post("/test", [&](const Request &, Response &res) {
  16411. handled = true;
  16412. res.set_content("ok", "text/plain");
  16413. });
  16414. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16415. auto se = detail::scope_exit([&] {
  16416. svr.stop();
  16417. t.join();
  16418. ASSERT_FALSE(svr.is_running());
  16419. ASSERT_TRUE(handled);
  16420. });
  16421. svr.wait_until_ready();
  16422. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16423. auto req = "POST /test HTTP/1.1\r\n"
  16424. "Content-Length: 5\r\n"
  16425. "Content-Length: 5\r\n"
  16426. "\r\n"
  16427. "hello";
  16428. std::string response;
  16429. ASSERT_TRUE(send_request(1, req, &response));
  16430. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16431. }
  16432. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16433. Server svr;
  16434. svr.Get("/", [](const Request &req, Response &res) {
  16435. EXPECT_EQ(2U, req.trailers.size());
  16436. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16437. // Denied
  16438. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16439. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16440. // Accepted
  16441. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16442. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16443. EXPECT_TRUE(req.has_trailer("X-World"));
  16444. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16445. res.set_content("ok", "text/plain");
  16446. });
  16447. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16448. auto se = detail::scope_exit([&] {
  16449. svr.stop();
  16450. t.join();
  16451. ASSERT_FALSE(svr.is_running());
  16452. });
  16453. svr.wait_until_ready();
  16454. const std::string req = "GET / HTTP/1.1\r\n"
  16455. "Transfer-Encoding: chunked\r\n"
  16456. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16457. "\r\n"
  16458. "0\r\n"
  16459. "Content-Length: 10\r\n"
  16460. "Host: internal.local\r\n"
  16461. "Content-Type: malicious/content\r\n"
  16462. "Cookie: any\r\n"
  16463. "Set-Cookie: any\r\n"
  16464. "X-Forwarded-For: attacker.com\r\n"
  16465. "X-Real-Ip: 1.1.1.1\r\n"
  16466. "X-Hello: hello\r\n"
  16467. "X-World: world\r\n"
  16468. "\r\n";
  16469. std::string res;
  16470. ASSERT_TRUE(send_request(1, req, &res));
  16471. }
  16472. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16473. // several field lines, and the combined value is what has to be parsed. A
  16474. // Trailer field split across lines therefore declares every name it lists;
  16475. // reading only the first line silently drops the trailers the later lines
  16476. // declare. The prohibited-trailer filter still applies to every line.
  16477. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16478. Server svr;
  16479. size_t observed_trailer_count = 0;
  16480. std::string observed_hello;
  16481. std::string observed_world;
  16482. bool observed_content_length = true;
  16483. svr.Get("/", [&](const Request &req, Response &res) {
  16484. observed_trailer_count = req.trailers.size();
  16485. observed_hello = req.get_trailer_value("X-Hello");
  16486. observed_world = req.get_trailer_value("X-World");
  16487. observed_content_length = req.has_trailer("Content-Length");
  16488. res.set_content("ok", "text/plain");
  16489. });
  16490. auto port = svr.bind_to_any_port(HOST);
  16491. thread t = thread([&]() { svr.listen_after_bind(); });
  16492. auto se = detail::scope_exit([&] {
  16493. svr.stop();
  16494. t.join();
  16495. ASSERT_FALSE(svr.is_running());
  16496. });
  16497. svr.wait_until_ready();
  16498. const std::string req = "GET / HTTP/1.1\r\n"
  16499. "Transfer-Encoding: chunked\r\n"
  16500. "Trailer: X-Hello\r\n"
  16501. "Trailer: X-World, Content-Length\r\n"
  16502. "\r\n"
  16503. "0\r\n"
  16504. "X-Hello: hello\r\n"
  16505. "X-World: world\r\n"
  16506. "Content-Length: 10\r\n"
  16507. "\r\n";
  16508. std::string res;
  16509. ASSERT_TRUE(send_request(1, req, &res, port));
  16510. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16511. // Accepted: both field lines contribute to the declared set
  16512. EXPECT_EQ(2U, observed_trailer_count);
  16513. EXPECT_EQ(observed_hello, "hello");
  16514. EXPECT_EQ(observed_world, "world");
  16515. // Denied: a prohibited name stays prohibited on a later field line
  16516. EXPECT_FALSE(observed_content_length);
  16517. }
  16518. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16519. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16520. // unbounded run of fields that are never declared, because the counter would
  16521. // only advance for declared fields.
  16522. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16523. Server svr;
  16524. bool handler_called = false;
  16525. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16526. handler_called = true;
  16527. res.set_content("ok", "text/plain");
  16528. });
  16529. auto port = svr.bind_to_any_port(HOST);
  16530. thread t = thread([&]() { svr.listen_after_bind(); });
  16531. auto se = detail::scope_exit([&] {
  16532. svr.stop();
  16533. t.join();
  16534. ASSERT_FALSE(svr.is_running());
  16535. });
  16536. svr.wait_until_ready();
  16537. // Declare nothing, then send far more undeclared trailer fields than the
  16538. // header-count limit. Parsing must stop and reject the request rather than
  16539. // read every line.
  16540. std::string req = "GET / HTTP/1.1\r\n"
  16541. "Transfer-Encoding: chunked\r\n"
  16542. "\r\n"
  16543. "0\r\n";
  16544. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16545. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16546. }
  16547. req += "\r\n";
  16548. std::string res;
  16549. ASSERT_TRUE(send_request(1, req, &res, port));
  16550. // The request is rejected before the handler runs.
  16551. EXPECT_FALSE(handler_called);
  16552. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16553. }
  16554. // The set of declared trailer names is capped so a peer cannot grow it without
  16555. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16556. // declared past the cap is not honored, even if the field is actually sent.
  16557. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16558. Server svr;
  16559. // One name inside the cap and one past it, so the test tracks the cap rather
  16560. // than a fixed count.
  16561. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16562. const std::string within_cap_name = "X-T-0";
  16563. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16564. bool observed_within_cap = false;
  16565. bool observed_past_cap = false;
  16566. svr.Get("/", [&](const Request &req, Response &res) {
  16567. observed_within_cap = req.has_trailer(within_cap_name);
  16568. observed_past_cap = req.has_trailer(past_cap_name);
  16569. res.set_content("ok", "text/plain");
  16570. });
  16571. auto port = svr.bind_to_any_port(HOST);
  16572. thread t = thread([&]() { svr.listen_after_bind(); });
  16573. auto se = detail::scope_exit([&] {
  16574. svr.stop();
  16575. t.join();
  16576. ASSERT_FALSE(svr.is_running());
  16577. });
  16578. svr.wait_until_ready();
  16579. // Declare more trailer names than the cap in a single Trailer field, then
  16580. // actually send the first (within the cap) and the last (past it).
  16581. std::string trailer_decl = "Trailer: ";
  16582. for (int i = 0; i < declared_count; i++) {
  16583. if (i != 0) { trailer_decl += ", "; }
  16584. trailer_decl += "X-T-" + std::to_string(i);
  16585. }
  16586. trailer_decl += "\r\n";
  16587. const std::string req = "GET / HTTP/1.1\r\n"
  16588. "Transfer-Encoding: chunked\r\n" +
  16589. trailer_decl +
  16590. "\r\n"
  16591. "0\r\n" +
  16592. within_cap_name + ": a\r\n" + past_cap_name +
  16593. ": b\r\n"
  16594. "\r\n";
  16595. std::string res;
  16596. ASSERT_TRUE(send_request(1, req, &res, port));
  16597. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16598. // A name within the cap is honored; one declared past the cap is dropped.
  16599. EXPECT_TRUE(observed_within_cap);
  16600. EXPECT_FALSE(observed_past_cap);
  16601. }
  16602. // A direct client that is not listed in trusted_proxies must not be able to
  16603. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16604. // the peer address on the actual TCP connection determines whether the
  16605. // header is honored.
  16606. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16607. Server svr;
  16608. // Deliberately does NOT include the loopback address the test client
  16609. // actually connects from, so the direct connection is not a trusted proxy.
  16610. svr.set_trusted_proxies({"203.0.113.66"});
  16611. std::string observed_remote_addr;
  16612. svr.Get("/ip", [&](const Request &req, Response &res) {
  16613. observed_remote_addr = req.remote_addr;
  16614. res.set_content("ok", "text/plain");
  16615. });
  16616. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16617. auto se = detail::scope_exit([&] {
  16618. svr.stop();
  16619. t.join();
  16620. ASSERT_FALSE(svr.is_running());
  16621. });
  16622. svr.wait_until_ready();
  16623. Client cli(HOST, PORT);
  16624. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16626. EXPECT_EQ(StatusCode::OK_200, res->status);
  16627. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16628. // ignored entirely and the real connection-level address retained.
  16629. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16630. observed_remote_addr == "127.0.0.1");
  16631. }
  16632. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16633. Server svr;
  16634. std::string observed_remote_addr;
  16635. std::string observed_xff;
  16636. svr.Get("/ip", [&](const Request &req, Response &res) {
  16637. observed_remote_addr = req.remote_addr;
  16638. observed_xff = req.get_header_value("X-Forwarded-For");
  16639. res.set_content("ok", "text/plain");
  16640. });
  16641. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16642. auto se = detail::scope_exit([&] {
  16643. svr.stop();
  16644. t.join();
  16645. ASSERT_FALSE(svr.is_running());
  16646. });
  16647. svr.wait_until_ready();
  16648. Client cli(HOST, PORT);
  16649. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16651. EXPECT_EQ(StatusCode::OK_200, res->status);
  16652. EXPECT_EQ(observed_xff, "203.0.113.66");
  16653. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16654. observed_remote_addr == "127.0.0.1");
  16655. }
  16656. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16657. Server svr;
  16658. svr.set_trusted_proxies({"203.0.113.66"});
  16659. std::string observed_remote_addr;
  16660. std::string observed_xff;
  16661. svr.Get("/ip", [&](const Request &req, Response &res) {
  16662. observed_remote_addr = req.remote_addr;
  16663. observed_xff = req.get_header_value("X-Forwarded-For");
  16664. res.set_content("ok", "text/plain");
  16665. });
  16666. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16667. auto se = detail::scope_exit([&] {
  16668. svr.stop();
  16669. t.join();
  16670. ASSERT_FALSE(svr.is_running());
  16671. });
  16672. svr.wait_until_ready();
  16673. Client cli(HOST, PORT);
  16674. auto res = cli.Get("/ip");
  16675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16676. EXPECT_EQ(StatusCode::OK_200, res->status);
  16677. EXPECT_EQ(observed_xff, "");
  16678. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16679. observed_remote_addr == "127.0.0.1");
  16680. }
  16681. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16682. Server svr;
  16683. // Include the loopback address the test client actually connects from, so
  16684. // the direct connection itself is recognized as the trusted proxy hop.
  16685. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16686. std::string observed_remote_addr;
  16687. std::string observed_xff;
  16688. svr.Get("/ip", [&](const Request &req, Response &res) {
  16689. observed_remote_addr = req.remote_addr;
  16690. observed_xff = req.get_header_value("X-Forwarded-For");
  16691. res.set_content("ok", "text/plain");
  16692. });
  16693. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16694. auto se = detail::scope_exit([&] {
  16695. svr.stop();
  16696. t.join();
  16697. ASSERT_FALSE(svr.is_running());
  16698. });
  16699. svr.wait_until_ready();
  16700. Client cli(HOST, PORT);
  16701. auto res = cli.Get(
  16702. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16704. EXPECT_EQ(StatusCode::OK_200, res->status);
  16705. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16706. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16707. }
  16708. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16709. Server svr;
  16710. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16711. std::string observed_remote_addr;
  16712. std::string observed_xff;
  16713. svr.Get("/ip", [&](const Request &req, Response &res) {
  16714. observed_remote_addr = req.remote_addr;
  16715. observed_xff = req.get_header_value("X-Forwarded-For");
  16716. res.set_content("ok", "text/plain");
  16717. });
  16718. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16719. auto se = detail::scope_exit([&] {
  16720. svr.stop();
  16721. t.join();
  16722. ASSERT_FALSE(svr.is_running());
  16723. });
  16724. svr.wait_until_ready();
  16725. Client cli(HOST, PORT);
  16726. auto res = cli.Get(
  16727. "/ip",
  16728. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16730. EXPECT_EQ(StatusCode::OK_200, res->status);
  16731. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16732. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16733. }
  16734. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16735. Server svr;
  16736. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16737. std::string observed_remote_addr;
  16738. std::string observed_xff;
  16739. svr.Get("/ip", [&](const Request &req, Response &res) {
  16740. observed_remote_addr = req.remote_addr;
  16741. observed_xff = req.get_header_value("X-Forwarded-For");
  16742. res.set_content("ok", "text/plain");
  16743. });
  16744. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16745. auto se = detail::scope_exit([&] {
  16746. svr.stop();
  16747. t.join();
  16748. ASSERT_FALSE(svr.is_running());
  16749. });
  16750. svr.wait_until_ready();
  16751. Client cli(HOST, PORT);
  16752. auto res = cli.Get(
  16753. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16755. EXPECT_EQ(StatusCode::OK_200, res->status);
  16756. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16757. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16758. // and must not be selected.
  16759. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16760. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16761. }
  16762. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16763. Server svr;
  16764. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16765. std::string observed_remote_addr;
  16766. svr.Get("/ip", [&](const Request &req, Response &res) {
  16767. observed_remote_addr = req.remote_addr;
  16768. res.set_content("ok", "text/plain");
  16769. });
  16770. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16771. auto se = detail::scope_exit([&] {
  16772. svr.stop();
  16773. t.join();
  16774. ASSERT_FALSE(svr.is_running());
  16775. });
  16776. svr.wait_until_ready();
  16777. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16778. // a forged address and the trusted proxy's own address; the forged value must
  16779. // not win over the address the trusted proxy actually recorded.
  16780. Client cli(HOST, PORT);
  16781. auto res = cli.Get(
  16782. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16784. EXPECT_EQ(StatusCode::OK_200, res->status);
  16785. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16786. }
  16787. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16788. Server svr;
  16789. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16790. std::string observed_remote_addr;
  16791. std::string observed_xff;
  16792. svr.Get("/ip", [&](const Request &req, Response &res) {
  16793. observed_remote_addr = req.remote_addr;
  16794. observed_xff = req.get_header_value("X-Forwarded-For");
  16795. res.set_content("ok", "text/plain");
  16796. });
  16797. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16798. auto se = detail::scope_exit([&] {
  16799. svr.stop();
  16800. t.join();
  16801. ASSERT_FALSE(svr.is_running());
  16802. });
  16803. svr.wait_until_ready();
  16804. Client cli(HOST, PORT);
  16805. auto res = cli.Get(
  16806. "/ip",
  16807. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16809. EXPECT_EQ(StatusCode::OK_200, res->status);
  16810. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16811. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16812. }
  16813. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16814. Server svr;
  16815. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16816. std::string observed_remote_addr;
  16817. std::string observed_xff;
  16818. svr.Get("/ip", [&](const Request &req, Response &res) {
  16819. observed_remote_addr = req.remote_addr;
  16820. observed_xff = req.get_header_value("X-Forwarded-For");
  16821. res.set_content("ok", "text/plain");
  16822. });
  16823. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16824. auto se = detail::scope_exit([&] {
  16825. svr.stop();
  16826. t.join();
  16827. ASSERT_FALSE(svr.is_running());
  16828. });
  16829. svr.wait_until_ready();
  16830. std::string raw_req =
  16831. "GET /ip HTTP/1.1\r\n"
  16832. "Host: localhost\r\n"
  16833. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16834. "Connection: close\r\n"
  16835. "\r\n";
  16836. std::string out;
  16837. ASSERT_TRUE(send_request(5, raw_req, &out));
  16838. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16839. // Header parser trims surrounding whitespace of the header value
  16840. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16841. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16842. }
  16843. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16844. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16845. // their own X-Forwarded-For as a separate field line rather than extending the
  16846. // one the client sent, so every occurrence has to be taken into account.
  16847. // Reading only the first one hands back the address the client chose.
  16848. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16849. Server svr;
  16850. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16851. std::string observed_remote_addr;
  16852. size_t observed_xff_count = 0;
  16853. svr.Get("/ip", [&](const Request &req, Response &res) {
  16854. observed_remote_addr = req.remote_addr;
  16855. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16856. res.set_content("ok", "text/plain");
  16857. });
  16858. auto port = svr.bind_to_any_port(HOST);
  16859. thread t = thread([&]() { svr.listen_after_bind(); });
  16860. auto se = detail::scope_exit([&] {
  16861. svr.stop();
  16862. t.join();
  16863. ASSERT_FALSE(svr.is_running());
  16864. });
  16865. svr.wait_until_ready();
  16866. // The client supplies the first field line; the trusted proxy appends the
  16867. // address it observed as a second one.
  16868. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16869. "Host: localhost\r\n"
  16870. "X-Forwarded-For: 1.2.3.4\r\n"
  16871. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16872. "Connection: close\r\n"
  16873. "\r\n";
  16874. std::string out;
  16875. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16876. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16877. EXPECT_EQ(observed_xff_count, 2U);
  16878. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16879. // The same chain spread over one field line per hop derives the same client
  16880. // address, i.e. the split and the comma-joined representations agree.
  16881. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16882. "Host: localhost\r\n"
  16883. "X-Forwarded-For: 1.2.3.4\r\n"
  16884. "X-Forwarded-For: 198.51.100.23\r\n"
  16885. "X-Forwarded-For: 192.0.2.45\r\n"
  16886. "Connection: close\r\n"
  16887. "\r\n";
  16888. out.clear();
  16889. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16890. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16891. EXPECT_EQ(observed_xff_count, 3U);
  16892. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16893. }
  16894. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16895. // crash the server (it used to call front() on an empty vector inside
  16896. // get_client_ip). The connection-level remote address must be retained instead.
  16897. static void run_malformed_xff_test(const std::string &xff_value) {
  16898. Server svr;
  16899. svr.set_trusted_proxies({"192.0.2.45"});
  16900. std::string observed_remote_addr;
  16901. svr.Get("/ip", [&](const Request &req, Response &res) {
  16902. observed_remote_addr = req.remote_addr;
  16903. res.set_content("ok", "text/plain");
  16904. });
  16905. int port = 0;
  16906. thread t = thread([&]() {
  16907. port = svr.bind_to_any_port(HOST);
  16908. svr.listen_after_bind();
  16909. });
  16910. auto se = detail::scope_exit([&] {
  16911. svr.stop();
  16912. t.join();
  16913. ASSERT_FALSE(svr.is_running());
  16914. });
  16915. svr.wait_until_ready();
  16916. Client cli(HOST, port);
  16917. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16919. EXPECT_EQ(StatusCode::OK_200, res->status);
  16920. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16921. observed_remote_addr == "127.0.0.1");
  16922. }
  16923. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16924. run_malformed_xff_test("");
  16925. }
  16926. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16927. run_malformed_xff_test(",");
  16928. }
  16929. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16930. run_malformed_xff_test(", , ,");
  16931. }
  16932. // The same rule applies to Accept: a request whose acceptable types are spread
  16933. // over several field lines must be negotiated against all of them.
  16934. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16935. // case-insensitive connection options. Comparing the whole field value against
  16936. // one option misses a client that sends several of them, and misses every
  16937. // casing but the one written in the comparison.
  16938. //
  16939. // Sends req, reads the response, then reuses the same socket for a second
  16940. // request to find out whether the server kept the connection.
  16941. static void probe_connection_reuse(int port, const std::string &req,
  16942. bool *announced_close, bool *reusable) {
  16943. auto error = Error::Success;
  16944. auto sock = detail::create_client_socket(
  16945. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16946. /*connection_timeout_sec=*/5, 0,
  16947. /*read_timeout_sec=*/1, 0,
  16948. /*write_timeout_sec=*/5, 0, std::string(), error);
  16949. ASSERT_NE(sock, INVALID_SOCKET);
  16950. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16951. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16952. "Host: localhost\r\n"
  16953. "Connection: close\r\n"
  16954. "\r\n";
  16955. std::string first_response;
  16956. std::string second_response;
  16957. detail::process_client_socket(
  16958. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16959. [&](Stream &strm) {
  16960. if (strm.write(req.data(), req.size()) !=
  16961. static_cast<ssize_t>(req.size())) {
  16962. return false;
  16963. }
  16964. char buf[512];
  16965. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16966. // Headers plus the two-byte body of the handler below
  16967. while (reader.getline()) {
  16968. first_response += reader.ptr();
  16969. if (first_response.find("ok") != std::string::npos) { break; }
  16970. }
  16971. if (strm.write(second.data(), second.size()) !=
  16972. static_cast<ssize_t>(second.size())) {
  16973. return true;
  16974. }
  16975. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16976. while (reader2.getline()) {
  16977. second_response += reader2.ptr();
  16978. if (second_response.find("ok") != std::string::npos) { break; }
  16979. }
  16980. return true;
  16981. });
  16982. *announced_close =
  16983. first_response.find("Connection: close") != std::string::npos;
  16984. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16985. }
  16986. class ConnectionTokenTest : public ::testing::Test {
  16987. protected:
  16988. void SetUp() override {
  16989. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16990. res.set_content("ok", "text/plain");
  16991. });
  16992. port_ = svr_.bind_to_any_port(HOST);
  16993. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16994. svr_.wait_until_ready();
  16995. }
  16996. void TearDown() override {
  16997. svr_.stop();
  16998. if (thread_.joinable()) { thread_.join(); }
  16999. }
  17000. Server svr_;
  17001. int port_ = 0;
  17002. thread thread_;
  17003. };
  17004. // "close" alongside another option still closes the connection, and the
  17005. // response says so rather than leaving the peer to discover it.
  17006. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17007. bool announced_close = false;
  17008. bool reusable = true;
  17009. probe_connection_reuse(port_,
  17010. "GET /keepalive HTTP/1.1\r\n"
  17011. "Host: localhost\r\n"
  17012. "Connection: keep-alive, close\r\n"
  17013. "\r\n",
  17014. &announced_close, &reusable);
  17015. EXPECT_TRUE(announced_close);
  17016. EXPECT_FALSE(reusable);
  17017. }
  17018. // "close" split over two field lines is the same list, so it is honored too.
  17019. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17020. bool announced_close = false;
  17021. bool reusable = true;
  17022. probe_connection_reuse(port_,
  17023. "GET /keepalive HTTP/1.1\r\n"
  17024. "Host: localhost\r\n"
  17025. "Connection: keep-alive\r\n"
  17026. "Connection: close\r\n"
  17027. "\r\n",
  17028. &announced_close, &reusable);
  17029. EXPECT_TRUE(announced_close);
  17030. EXPECT_FALSE(reusable);
  17031. }
  17032. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17033. // keep-alive in the spelling everyone actually sends keeps its connection.
  17034. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17035. bool announced_close = false;
  17036. bool reusable = false;
  17037. probe_connection_reuse(port_,
  17038. "GET /keepalive HTTP/1.0\r\n"
  17039. "Host: localhost\r\n"
  17040. "Connection: keep-alive\r\n"
  17041. "\r\n",
  17042. &announced_close, &reusable);
  17043. EXPECT_FALSE(announced_close);
  17044. EXPECT_TRUE(reusable);
  17045. }
  17046. // A token the value merely contains is not the token itself.
  17047. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17048. bool announced_close = false;
  17049. bool reusable = false;
  17050. probe_connection_reuse(port_,
  17051. "GET /keepalive HTTP/1.1\r\n"
  17052. "Host: localhost\r\n"
  17053. "Connection: notclose\r\n"
  17054. "\r\n",
  17055. &announced_close, &reusable);
  17056. EXPECT_FALSE(announced_close);
  17057. EXPECT_TRUE(reusable);
  17058. }
  17059. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17060. Server svr;
  17061. std::vector<std::string> observed_types;
  17062. svr.Get("/", [&](const Request &req, Response &res) {
  17063. observed_types = req.accept_content_types;
  17064. res.set_content("ok", "text/plain");
  17065. });
  17066. auto port = svr.bind_to_any_port(HOST);
  17067. thread t = thread([&]() { svr.listen_after_bind(); });
  17068. auto se = detail::scope_exit([&] {
  17069. svr.stop();
  17070. t.join();
  17071. ASSERT_FALSE(svr.is_running());
  17072. });
  17073. svr.wait_until_ready();
  17074. Client cli(HOST, port);
  17075. Headers headers;
  17076. headers.emplace("Accept", "text/plain;q=0.5");
  17077. headers.emplace("Accept", "application/json");
  17078. auto res = cli.Get("/", headers);
  17079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17080. EXPECT_EQ(StatusCode::OK_200, res->status);
  17081. // Sorted by q-value, so the second field line's type comes first
  17082. ASSERT_EQ(2U, observed_types.size());
  17083. EXPECT_EQ("application/json", observed_types[0]);
  17084. EXPECT_EQ("text/plain", observed_types[1]);
  17085. }
  17086. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17087. // empty field line must not contribute a bare comma to the combined value.
  17088. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17089. Server svr;
  17090. std::vector<std::string> observed_types;
  17091. svr.Get("/", [&](const Request &req, Response &res) {
  17092. observed_types = req.accept_content_types;
  17093. res.set_content("ok", "text/plain");
  17094. });
  17095. auto port = svr.bind_to_any_port(HOST);
  17096. thread t = thread([&]() { svr.listen_after_bind(); });
  17097. auto se = detail::scope_exit([&] {
  17098. svr.stop();
  17099. t.join();
  17100. ASSERT_FALSE(svr.is_running());
  17101. });
  17102. svr.wait_until_ready();
  17103. // Empty first field line, then a real one
  17104. std::string raw_req = "GET / HTTP/1.1\r\n"
  17105. "Host: localhost\r\n"
  17106. "Accept:\r\n"
  17107. "Accept: application/json\r\n"
  17108. "Connection: close\r\n"
  17109. "\r\n";
  17110. std::string out;
  17111. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17112. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17113. ASSERT_EQ(1U, observed_types.size());
  17114. EXPECT_EQ("application/json", observed_types[0]);
  17115. }
  17116. // The skip in get_combined_header_value() is what keeps an empty field line
  17117. // from contributing a bare comma. Only a trailing empty field line exercises
  17118. // it: a leading one is already covered by the "combined is still empty" check,
  17119. // and parse_accept_header() now ignores the empty element either way, so the
  17120. // request-level test above can no longer tell the two apart.
  17121. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17122. Headers headers;
  17123. headers.emplace("Accept", "text/html");
  17124. headers.emplace("Accept", "");
  17125. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17126. headers.clear();
  17127. headers.emplace("Accept", "");
  17128. headers.emplace("Accept", "application/json");
  17129. EXPECT_EQ("application/json",
  17130. detail::get_combined_header_value(headers, "Accept"));
  17131. }
  17132. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17133. // An encoding offered on a later Accept-Encoding field line is still offered.
  17134. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17135. Server svr;
  17136. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17137. res.set_content(std::string(1024, 'x'), "text/plain");
  17138. });
  17139. auto port = svr.bind_to_any_port(HOST);
  17140. thread t = thread([&]() { svr.listen_after_bind(); });
  17141. auto se = detail::scope_exit([&] {
  17142. svr.stop();
  17143. t.join();
  17144. ASSERT_FALSE(svr.is_running());
  17145. });
  17146. svr.wait_until_ready();
  17147. Client cli(HOST, port);
  17148. cli.set_decompress(false);
  17149. Headers headers;
  17150. headers.emplace("Accept-Encoding", "identity");
  17151. headers.emplace("Accept-Encoding", "gzip");
  17152. auto res = cli.Get("/", headers);
  17153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17154. EXPECT_EQ(StatusCode::OK_200, res->status);
  17155. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17156. }
  17157. #endif
  17158. #ifndef _WIN32
  17159. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17160. Server svr;
  17161. svr.Post("/post", [&](const Request &req, Response &res) {
  17162. res.set_content(req.body, "text/plain");
  17163. });
  17164. svr.Put("/put", [&](const Request &req, Response &res) {
  17165. res.set_content(req.body, "text/plain");
  17166. });
  17167. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17168. res.set_content(req.body, "text/plain");
  17169. });
  17170. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17171. res.set_content(req.body, "text/plain");
  17172. });
  17173. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17174. auto se = detail::scope_exit([&] {
  17175. svr.stop();
  17176. t.join();
  17177. ASSERT_FALSE(svr.is_running());
  17178. });
  17179. svr.wait_until_ready();
  17180. std::string resp;
  17181. // POST without Content-Length
  17182. ASSERT_TRUE(send_request(5,
  17183. "POST /post HTTP/1.1\r\n"
  17184. "Host: localhost\r\n"
  17185. "Connection: close\r\n"
  17186. "\r\n",
  17187. &resp));
  17188. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17189. // PUT without Content-Length
  17190. resp.clear();
  17191. ASSERT_TRUE(send_request(5,
  17192. "PUT /put HTTP/1.1\r\n"
  17193. "Host: localhost\r\n"
  17194. "Connection: close\r\n"
  17195. "\r\n",
  17196. &resp));
  17197. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17198. // PATCH without Content-Length
  17199. resp.clear();
  17200. ASSERT_TRUE(send_request(5,
  17201. "PATCH /patch HTTP/1.1\r\n"
  17202. "Host: localhost\r\n"
  17203. "Connection: close\r\n"
  17204. "\r\n",
  17205. &resp));
  17206. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17207. // DELETE without Content-Length
  17208. resp.clear();
  17209. ASSERT_TRUE(send_request(5,
  17210. "DELETE /delete HTTP/1.1\r\n"
  17211. "Host: localhost\r\n"
  17212. "Connection: close\r\n"
  17213. "\r\n",
  17214. &resp));
  17215. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17216. }
  17217. #endif
  17218. //==============================================================================
  17219. // open_stream() Tests
  17220. //==============================================================================
  17221. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17222. std::string result;
  17223. char buf[8192];
  17224. ssize_t n;
  17225. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17226. result.append(buf, static_cast<size_t>(n));
  17227. }
  17228. return result;
  17229. }
  17230. // Mock stream for unit tests
  17231. class MockStream : public Stream {
  17232. public:
  17233. std::string data;
  17234. size_t pos = 0;
  17235. ssize_t error_after = -1; // -1 = no error
  17236. explicit MockStream(const std::string &d, ssize_t err = -1)
  17237. : data(d), error_after(err) {}
  17238. bool is_readable() const override { return true; }
  17239. bool wait_readable() const override { return true; }
  17240. bool wait_writable() const override { return true; }
  17241. ssize_t read(char *ptr, size_t size) override {
  17242. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17243. if (pos >= data.size()) return 0;
  17244. size_t limit =
  17245. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17246. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17247. std::memcpy(ptr, data.data() + pos, to_read);
  17248. pos += to_read;
  17249. return static_cast<ssize_t>(to_read);
  17250. }
  17251. ssize_t write(const char *, size_t) override { return -1; }
  17252. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17253. ip = "127.0.0.1";
  17254. port = 0;
  17255. }
  17256. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17257. ip = "127.0.0.1";
  17258. port = 0;
  17259. }
  17260. socket_t socket() const override { return INVALID_SOCKET; }
  17261. time_t duration() const override { return 0; }
  17262. };
  17263. TEST(StreamHandleTest, Basic) {
  17264. ClientImpl::StreamHandle handle;
  17265. EXPECT_FALSE(handle.is_valid());
  17266. handle.response = detail::make_unique<Response>();
  17267. handle.error = Error::Connection;
  17268. EXPECT_FALSE(handle.is_valid());
  17269. handle.error = Error::Success;
  17270. EXPECT_TRUE(handle.is_valid());
  17271. }
  17272. TEST(BodyReaderTest, Basic) {
  17273. MockStream stream("Hello, World!");
  17274. detail::BodyReader reader;
  17275. reader.stream = &stream;
  17276. reader.content_length = 13;
  17277. char buf[32];
  17278. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17279. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17280. EXPECT_TRUE(reader.eof);
  17281. }
  17282. TEST(BodyReaderTest, NoStream) {
  17283. detail::BodyReader reader;
  17284. char buf[32];
  17285. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17286. EXPECT_EQ(Error::Connection, reader.last_error);
  17287. }
  17288. TEST(BodyReaderTest, Error) {
  17289. MockStream stream("Hello, World!", 5);
  17290. detail::BodyReader reader;
  17291. reader.stream = &stream;
  17292. reader.content_length = 13;
  17293. char buf[32];
  17294. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17295. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17296. EXPECT_EQ(Error::Read, reader.last_error);
  17297. }
  17298. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17299. // Mock-based StreamHandle tests relying on private internals are removed.
  17300. class OpenStreamTest : public ::testing::Test {
  17301. protected:
  17302. void SetUp() override {
  17303. svr_.Get("/hello", [](const Request &, Response &res) {
  17304. res.set_content("Hello World!", "text/plain");
  17305. });
  17306. svr_.Get("/large", [](const Request &, Response &res) {
  17307. res.set_content(std::string(10000, 'X'), "text/plain");
  17308. });
  17309. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17310. res.set_content("Hello World!", "image/jpeg");
  17311. res.set_header("Content-Encoding", "UTF-8");
  17312. });
  17313. svr_.Get("/chunked", [](const Request &, Response &res) {
  17314. res.set_chunked_content_provider("text/plain",
  17315. [](size_t offset, DataSink &sink) {
  17316. if (offset < 15) {
  17317. sink.write("chunk", 5);
  17318. return true;
  17319. }
  17320. sink.done();
  17321. return true;
  17322. });
  17323. });
  17324. svr_.Get("/compressible", [](const Request &, Response &res) {
  17325. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17326. DataSink &sink) {
  17327. if (offset < 100 * 1024) {
  17328. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17329. sink.write(chunk.data(), chunk.size());
  17330. return true;
  17331. }
  17332. sink.done();
  17333. return true;
  17334. });
  17335. });
  17336. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17337. [](const Request & /*req*/, Response &res) {
  17338. auto i = new int(0);
  17339. res.set_header("Trailer", "Content-Length, X-Allowed");
  17340. res.set_chunked_content_provider(
  17341. "text/plain",
  17342. [i](size_t /*offset*/, DataSink &sink) {
  17343. switch (*i) {
  17344. case 0: sink.os << "123"; break;
  17345. case 1: sink.os << "456"; break;
  17346. case 2: sink.os << "789"; break;
  17347. case 3: {
  17348. sink.done_with_trailer(
  17349. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17350. } break;
  17351. }
  17352. (*i)++;
  17353. return true;
  17354. },
  17355. [i](bool success) {
  17356. EXPECT_TRUE(success);
  17357. delete i;
  17358. });
  17359. });
  17360. // Echo headers endpoint for header-related tests
  17361. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17362. std::string body;
  17363. for (const auto &h : req.headers) {
  17364. body.append(h.first);
  17365. body.push_back(':');
  17366. body.append(h.second);
  17367. body.push_back('\n');
  17368. }
  17369. res.set_content(body, "text/plain");
  17370. });
  17371. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17372. std::string body;
  17373. for (const auto &h : req.headers) {
  17374. body.append(h.first);
  17375. body.push_back(':');
  17376. body.append(h.second);
  17377. body.push_back('\n');
  17378. }
  17379. res.set_content(body, "text/plain");
  17380. });
  17381. port_ = svr_.bind_to_any_port("127.0.0.1");
  17382. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17383. svr_.wait_until_ready();
  17384. }
  17385. void TearDown() override {
  17386. svr_.stop();
  17387. if (thread_.joinable()) thread_.join();
  17388. }
  17389. Server svr_;
  17390. std::thread thread_;
  17391. int port_ = 0;
  17392. };
  17393. TEST_F(OpenStreamTest, Basic) {
  17394. Client cli("127.0.0.1", port_);
  17395. auto handle = cli.open_stream("GET", "/hello");
  17396. EXPECT_TRUE(handle.is_valid());
  17397. EXPECT_EQ("Hello World!", read_all(handle));
  17398. }
  17399. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17400. Client cli("127.0.0.1", port_);
  17401. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17402. ASSERT_TRUE(handle.is_valid());
  17403. EXPECT_EQ("Hello World!", read_all(handle));
  17404. }
  17405. TEST_F(OpenStreamTest, SmallBuffer) {
  17406. Client cli("127.0.0.1", port_);
  17407. auto handle = cli.open_stream("GET", "/hello");
  17408. std::string result;
  17409. char buf[4];
  17410. ssize_t n;
  17411. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17412. result.append(buf, static_cast<size_t>(n));
  17413. EXPECT_EQ("Hello World!", result);
  17414. }
  17415. TEST_F(OpenStreamTest, DefaultHeaders) {
  17416. Client cli("127.0.0.1", port_);
  17417. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17418. {
  17419. auto handle = cli.open_stream("GET", "/echo-headers");
  17420. ASSERT_TRUE(handle.is_valid());
  17421. auto body = read_all(handle);
  17422. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17423. std::string::npos);
  17424. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17425. std::string::npos);
  17426. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17427. }
  17428. // open_stream POST with body and no explicit content_type should NOT add
  17429. // text/plain Content-Type (behavior differs from non-streaming path), but
  17430. // should include Content-Length
  17431. {
  17432. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17433. ASSERT_TRUE(handle.is_valid());
  17434. auto body = read_all(handle);
  17435. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17436. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17437. }
  17438. // open_stream POST with explicit Content-Type should preserve it
  17439. {
  17440. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17441. {{"Content-Type", "application/custom"}},
  17442. "{}", "application/custom");
  17443. ASSERT_TRUE(handle.is_valid());
  17444. auto body = read_all(handle);
  17445. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17446. }
  17447. // User-specified User-Agent must not be overwritten for stream API
  17448. {
  17449. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17450. {{"User-Agent", "MyAgent/1.2"}});
  17451. ASSERT_TRUE(handle.is_valid());
  17452. auto body = read_all(handle);
  17453. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17454. }
  17455. }
  17456. TEST_F(OpenStreamTest, Large) {
  17457. Client cli("127.0.0.1", port_);
  17458. auto handle = cli.open_stream("GET", "/large");
  17459. EXPECT_EQ(10000u, read_all(handle).size());
  17460. }
  17461. TEST_F(OpenStreamTest, ConnectionError) {
  17462. Client cli("127.0.0.1", 9999);
  17463. auto handle = cli.open_stream("GET", "/hello");
  17464. EXPECT_FALSE(handle.is_valid());
  17465. }
  17466. TEST_F(OpenStreamTest, Chunked) {
  17467. Client cli("127.0.0.1", port_);
  17468. auto handle = cli.open_stream("GET", "/chunked");
  17469. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17470. "Transfer-Encoding") == "chunked");
  17471. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17472. }
  17473. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17474. Client cli("127.0.0.1", port_);
  17475. auto handle =
  17476. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17477. ASSERT_TRUE(handle.is_valid());
  17478. // Consume body to allow trailers to be received/parsed
  17479. auto body = read_all(handle);
  17480. // Explicitly parse trailers (ensure trailers are available for assertion)
  17481. handle.parse_trailers_if_needed();
  17482. EXPECT_EQ(std::string("123456789"), body);
  17483. // The response should include a Trailer header declaring both names
  17484. ASSERT_TRUE(handle.response);
  17485. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17486. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17487. handle.response->get_header_value("Trailer"));
  17488. // Prohibited trailer must not be present
  17489. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17490. // Allowed trailer should be present
  17491. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17492. EXPECT_EQ(std::string("yes"),
  17493. handle.response->get_trailer_value("X-Allowed"));
  17494. // Verify trailers are NOT present as regular headers
  17495. EXPECT_EQ(std::string(""),
  17496. handle.response->get_header_value("Content-Length"));
  17497. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17498. }
  17499. static std::thread serve_single_response(std::promise<int> &port_promise,
  17500. const std::string &response) {
  17501. return std::thread([&port_promise, response] {
  17502. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17503. default_socket_options(srv);
  17504. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17505. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17506. sockaddr_in addr{};
  17507. addr.sin_family = AF_INET;
  17508. addr.sin_port = htons(0); // Let OS assign a free port
  17509. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17510. int opt = 1;
  17511. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17512. #ifdef _WIN32
  17513. reinterpret_cast<const char *>(&opt),
  17514. #else
  17515. &opt,
  17516. #endif
  17517. sizeof(opt));
  17518. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17519. ::listen(srv, 1) != 0) {
  17520. port_promise.set_value(-1);
  17521. detail::close_socket(srv);
  17522. return;
  17523. }
  17524. socklen_t addr_len = sizeof(addr);
  17525. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17526. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17527. sockaddr_in cli_addr{};
  17528. socklen_t cli_len = sizeof(cli_addr);
  17529. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17530. if (cli != INVALID_SOCKET) {
  17531. // Read the complete HTTP request (until the blank line that terminates
  17532. // headers) before sending the response. If the server closes the socket
  17533. // while the client's request data is still unread in the kernel receive
  17534. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17535. // connection on both sides: it discards the client's receive buffer
  17536. // (which already holds our response) and causes any in-progress write on
  17537. // the client to fail with ECONNRESET. Reading all request data first
  17538. // ensures close() emits a graceful FIN.
  17539. {
  17540. char rbuf[256];
  17541. std::string req;
  17542. while (req.find("\r\n\r\n") == std::string::npos) {
  17543. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17544. if (n <= 0) { break; }
  17545. req.append(rbuf, static_cast<size_t>(n));
  17546. }
  17547. }
  17548. ::send(cli,
  17549. #ifdef _WIN32
  17550. static_cast<const char *>(response.c_str()),
  17551. static_cast<int>(response.size()),
  17552. #else
  17553. response.c_str(), response.size(),
  17554. #endif
  17555. 0);
  17556. detail::close_socket(cli);
  17557. }
  17558. detail::close_socket(srv);
  17559. });
  17560. }
  17561. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17562. #ifndef _WIN32
  17563. signal(SIGPIPE, SIG_IGN);
  17564. #endif
  17565. std::promise<int> port_promise;
  17566. auto port_future = port_promise.get_future();
  17567. auto server_thread =
  17568. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17569. "Content-Type: text/plain\r\n"
  17570. "Content-Length: not-a-number\r\n"
  17571. "Connection: close\r\n"
  17572. "\r\n"
  17573. "hello");
  17574. auto port = port_future.get();
  17575. ASSERT_GT(port, 0);
  17576. Client cli("127.0.0.1", port);
  17577. auto handle = cli.open_stream("GET", "/");
  17578. EXPECT_FALSE(handle.is_valid());
  17579. server_thread.join();
  17580. }
  17581. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17582. #ifndef _WIN32
  17583. signal(SIGPIPE, SIG_IGN);
  17584. #endif
  17585. std::promise<int> port_promise;
  17586. auto port_future = port_promise.get_future();
  17587. auto server_thread = serve_single_response(
  17588. port_promise, "HTTP/1.1 200 OK\r\n"
  17589. "Content-Type: text/plain\r\n"
  17590. "Content-Length: 99999999999999999999999999\r\n"
  17591. "Connection: close\r\n"
  17592. "\r\n"
  17593. "hello");
  17594. auto port = port_future.get();
  17595. ASSERT_GT(port, 0);
  17596. // Historically std::stoull would throw std::out_of_range here and crash
  17597. // the process, then parsing silently clamped to a bogus framing length and
  17598. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17599. // so the stream fails to open, matching the not-a-number case above. The
  17600. // process still must NOT terminate.
  17601. Client cli("127.0.0.1", port);
  17602. auto handle = cli.open_stream("GET", "/");
  17603. EXPECT_FALSE(handle.is_valid());
  17604. server_thread.join();
  17605. }
  17606. // Serves `response` to the single request `fn` makes with a fresh client.
  17607. template <typename Fn>
  17608. static void with_single_response(const std::string &response, Fn fn) {
  17609. #ifndef _WIN32
  17610. signal(SIGPIPE, SIG_IGN);
  17611. #endif
  17612. std::promise<int> port_promise;
  17613. auto port_future = port_promise.get_future();
  17614. auto server_thread = serve_single_response(port_promise, response);
  17615. auto se = detail::scope_exit([&] { server_thread.join(); });
  17616. auto port = port_future.get();
  17617. ASSERT_GT(port, 0);
  17618. Client cli("127.0.0.1", port);
  17619. fn(cli);
  17620. }
  17621. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17622. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17623. // the chunked coding and drop Content-Length, so a front-end that trusts
  17624. // Content-Length would disagree about where the body ends (response
  17625. // smuggling). The client must reject such a response.
  17626. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17627. for (const char *te : {"chunked", "gzip, chunked"}) {
  17628. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17629. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17630. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17631. "5\r\nhello\r\n0\r\n\r\n";
  17632. with_single_response(response, [&](Client &cli) {
  17633. auto res = cli.Get("/");
  17634. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17635. EXPECT_EQ(Error::Read, res.error()) << te;
  17636. });
  17637. with_single_response(response, [&](Client &cli) {
  17638. auto handle = cli.open_stream("GET", "/");
  17639. EXPECT_FALSE(handle.is_valid()) << te;
  17640. EXPECT_EQ(Error::Read, handle.error) << te;
  17641. });
  17642. }
  17643. }
  17644. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17645. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17646. // closing the connection (unlike a request, which must be rejected).
  17647. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17648. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17649. "Transfer-Encoding: chunked\r\n"
  17650. "Connection: close\r\n"
  17651. "\r\n"
  17652. "5\r\nhello\r\n0\r\n\r\n",
  17653. "HTTP/1.1 200 OK\r\n"
  17654. "Transfer-Encoding: gzip\r\n"
  17655. "Connection: close\r\n"
  17656. "\r\n"
  17657. "hello"}) {
  17658. with_single_response(response, [&](Client &cli) {
  17659. auto res = cli.Get("/");
  17660. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17661. EXPECT_EQ("hello", res->body);
  17662. });
  17663. with_single_response(response, [&](Client &cli) {
  17664. auto handle = cli.open_stream("GET", "/");
  17665. ASSERT_TRUE(handle.is_valid()) << response;
  17666. EXPECT_EQ("hello", read_all(handle));
  17667. });
  17668. }
  17669. }
  17670. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17671. // framing headers describe nothing to read and must not be rejected.
  17672. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17673. const std::string framing = "Content-Length: 5\r\n"
  17674. "Transfer-Encoding: chunked\r\n"
  17675. "Connection: close\r\n"
  17676. "\r\n";
  17677. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17678. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17679. });
  17680. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17681. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17682. });
  17683. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17684. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17685. with_single_response(response, [&](Client &cli) {
  17686. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17687. });
  17688. with_single_response(response, [&](Client &cli) {
  17689. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17690. });
  17691. }
  17692. }
  17693. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17694. TEST_F(OpenStreamTest, Gzip) {
  17695. Client cli("127.0.0.1", port_);
  17696. auto handle = cli.open_stream("GET", "/compressible", {},
  17697. {{"Accept-Encoding", "gzip"}});
  17698. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17699. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17700. }
  17701. #endif
  17702. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17703. TEST_F(OpenStreamTest, Brotli) {
  17704. Client cli("127.0.0.1", port_);
  17705. auto handle =
  17706. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17707. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17708. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17709. }
  17710. #endif
  17711. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17712. TEST_F(OpenStreamTest, Zstd) {
  17713. Client cli("127.0.0.1", port_);
  17714. auto handle = cli.open_stream("GET", "/compressible", {},
  17715. {{"Accept-Encoding", "zstd"}});
  17716. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17717. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17718. }
  17719. #endif
  17720. #ifdef CPPHTTPLIB_SSL_ENABLED
  17721. class SSLOpenStreamTest : public ::testing::Test {
  17722. protected:
  17723. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17724. void SetUp() override {
  17725. svr_.Get("/hello", [](const Request &, Response &res) {
  17726. res.set_content("Hello SSL World!", "text/plain");
  17727. });
  17728. svr_.Get("/chunked", [](const Request &, Response &res) {
  17729. res.set_chunked_content_provider("text/plain",
  17730. [](size_t offset, DataSink &sink) {
  17731. if (offset < 15) {
  17732. sink.write("chunk", 5);
  17733. return true;
  17734. }
  17735. sink.done();
  17736. return true;
  17737. });
  17738. });
  17739. svr_.Post("/echo", [](const Request &req, Response &res) {
  17740. res.set_content(req.body, req.get_header_value("Content-Type"));
  17741. });
  17742. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17743. std::string body = req.body;
  17744. res.set_chunked_content_provider(
  17745. "text/plain", [body](size_t offset, DataSink &sink) {
  17746. if (offset < body.size()) {
  17747. sink.write(body.data() + offset, body.size() - offset);
  17748. }
  17749. sink.done();
  17750. return true;
  17751. });
  17752. });
  17753. port_ = svr_.bind_to_any_port("127.0.0.1");
  17754. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17755. svr_.wait_until_ready();
  17756. }
  17757. void TearDown() override {
  17758. svr_.stop();
  17759. if (thread_.joinable()) thread_.join();
  17760. }
  17761. SSLServer svr_;
  17762. std::thread thread_;
  17763. int port_ = 0;
  17764. };
  17765. TEST_F(SSLOpenStreamTest, Basic) {
  17766. SSLClient cli("127.0.0.1", port_);
  17767. cli.enable_server_certificate_verification(false);
  17768. auto handle = cli.open_stream("GET", "/hello");
  17769. ASSERT_TRUE(handle.is_valid());
  17770. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17771. }
  17772. TEST_F(SSLOpenStreamTest, Chunked) {
  17773. SSLClient cli("127.0.0.1", port_);
  17774. cli.enable_server_certificate_verification(false);
  17775. auto handle = cli.open_stream("GET", "/chunked");
  17776. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17777. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17778. "Transfer-Encoding") == "chunked");
  17779. auto body = read_all(handle);
  17780. EXPECT_EQ("chunkchunkchunk", body);
  17781. }
  17782. TEST_F(SSLOpenStreamTest, Post) {
  17783. SSLClient cli("127.0.0.1", port_);
  17784. cli.enable_server_certificate_verification(false);
  17785. auto handle =
  17786. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17787. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17788. EXPECT_EQ(200, handle.response->status);
  17789. auto body = read_all(handle);
  17790. EXPECT_EQ("Hello SSL POST", body);
  17791. }
  17792. TEST_F(SSLOpenStreamTest, PostChunked) {
  17793. SSLClient cli("127.0.0.1", port_);
  17794. cli.enable_server_certificate_verification(false);
  17795. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17796. "Chunked SSL Data", "text/plain");
  17797. ASSERT_TRUE(handle.is_valid());
  17798. EXPECT_EQ(200, handle.response->status);
  17799. auto body = read_all(handle);
  17800. EXPECT_EQ("Chunked SSL Data", body);
  17801. }
  17802. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17803. // Content-Length is terminated by the server closing the connection. When the
  17804. // SSL peer sends a close_notify after the body, the client must treat it as a
  17805. // clean EOF and return a successful response rather than an error.
  17806. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17807. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17808. ASSERT_TRUE(svr.is_valid());
  17809. svr.set_keep_alive_max_count(1);
  17810. const std::string expected_body = "Hello from connection-close response!";
  17811. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17812. res.set_content_provider("text/plain",
  17813. [&](size_t offset, DataSink &sink) -> bool {
  17814. if (offset < expected_body.size()) {
  17815. sink.write(expected_body.data() + offset,
  17816. expected_body.size() - offset);
  17817. }
  17818. sink.done();
  17819. return true;
  17820. });
  17821. });
  17822. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17823. auto se = detail::scope_exit([&] {
  17824. svr.stop();
  17825. listen_thread.join();
  17826. ASSERT_FALSE(svr.is_running());
  17827. });
  17828. svr.wait_until_ready();
  17829. SSLClient cli(HOST, PORT);
  17830. cli.enable_server_certificate_verification(false);
  17831. auto res = cli.Get("/no-content-length");
  17832. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17833. EXPECT_EQ(StatusCode::OK_200, res->status);
  17834. EXPECT_EQ(expected_body, res->body);
  17835. }
  17836. #endif // CPPHTTPLIB_SSL_ENABLED
  17837. //==============================================================================
  17838. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17839. // results for various scenarios.
  17840. //==============================================================================
  17841. TEST(ParityTest, GetVsOpenStream) {
  17842. Server svr;
  17843. const std::string path = "/parity";
  17844. const std::string content = "Parity test content: hello world";
  17845. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17846. res.set_content(content, "text/plain");
  17847. });
  17848. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17849. auto se = detail::scope_exit([&] {
  17850. svr.stop();
  17851. t.join();
  17852. ASSERT_FALSE(svr.is_running());
  17853. });
  17854. svr.wait_until_ready();
  17855. Client cli(HOST, PORT);
  17856. // Non-stream path
  17857. auto r1 = cli.Get(path);
  17858. ASSERT_TRUE(r1);
  17859. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17860. // Stream path
  17861. auto h = cli.open_stream("GET", path);
  17862. ASSERT_TRUE(h.is_valid());
  17863. EXPECT_EQ(r1->body, read_all(h));
  17864. }
  17865. // Helper to compress data with provided compressor type T
  17866. template <typename Compressor>
  17867. static std::string compress_payload_for_parity(const std::string &in) {
  17868. std::string out;
  17869. Compressor compressor;
  17870. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17871. [&](const char *data, size_t n) {
  17872. out.append(data, n);
  17873. return true;
  17874. });
  17875. EXPECT_TRUE(ok);
  17876. return out;
  17877. }
  17878. // Helper function for compression parity tests
  17879. template <typename Compressor>
  17880. static void test_compression_parity(const std::string &original,
  17881. const std::string &path,
  17882. const std::string &encoding) {
  17883. const std::string compressed =
  17884. compress_payload_for_parity<Compressor>(original);
  17885. Server svr;
  17886. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17887. res.set_content(compressed, "application/octet-stream");
  17888. res.set_header("Content-Encoding", encoding);
  17889. });
  17890. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17891. auto se = detail::scope_exit([&] {
  17892. svr.stop();
  17893. t.join();
  17894. ASSERT_FALSE(svr.is_running());
  17895. });
  17896. svr.wait_until_ready();
  17897. Client cli(HOST, PORT);
  17898. // Non-streaming
  17899. {
  17900. auto res = cli.Get(path);
  17901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17902. EXPECT_EQ(StatusCode::OK_200, res->status);
  17903. EXPECT_EQ(original, res->body);
  17904. }
  17905. // Streaming
  17906. {
  17907. auto h = cli.open_stream("GET", path);
  17908. ASSERT_TRUE(h.is_valid());
  17909. EXPECT_EQ(original, read_all(h));
  17910. }
  17911. }
  17912. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17913. TEST(ParityTest, Gzip) {
  17914. test_compression_parity<detail::gzip_compressor>(
  17915. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17916. }
  17917. #endif
  17918. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17919. TEST(ParityTest, Brotli) {
  17920. test_compression_parity<detail::brotli_compressor>(
  17921. "Hello, brotli parity test payload", "/parity-br", "br");
  17922. }
  17923. #endif
  17924. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17925. TEST(ParityTest, Zstd) {
  17926. test_compression_parity<detail::zstd_compressor>(
  17927. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17928. }
  17929. #endif
  17930. //==============================================================================
  17931. // New Stream API Tests
  17932. //==============================================================================
  17933. inline std::string read_body(httplib::stream::Result &result) {
  17934. std::string body;
  17935. while (result.next()) {
  17936. body.append(result.data(), result.size());
  17937. }
  17938. return body;
  17939. }
  17940. TEST(ClientConnectionTest, Basic) {
  17941. httplib::ClientConnection conn;
  17942. EXPECT_FALSE(conn.is_open());
  17943. conn.sock = 1;
  17944. EXPECT_TRUE(conn.is_open());
  17945. httplib::ClientConnection conn2(std::move(conn));
  17946. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17947. conn2.sock = INVALID_SOCKET;
  17948. }
  17949. // Unified test server for all stream::* tests
  17950. class StreamApiTest : public ::testing::Test {
  17951. protected:
  17952. void SetUp() override {
  17953. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17954. res.set_content("Hello World!", "text/plain");
  17955. });
  17956. svr_.Get("/echo-params",
  17957. [](const httplib::Request &req, httplib::Response &res) {
  17958. std::string r;
  17959. for (const auto &p : req.params) {
  17960. if (!r.empty()) r += "&";
  17961. r += p.first + "=" + p.second;
  17962. }
  17963. res.set_content(r, "text/plain");
  17964. });
  17965. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17966. res.set_content(req.body, req.get_header_value("Content-Type"));
  17967. });
  17968. svr_.Post("/echo-headers",
  17969. [](const httplib::Request &req, httplib::Response &res) {
  17970. std::string r;
  17971. for (const auto &h : req.headers)
  17972. r += h.first + ": " + h.second + "\n";
  17973. res.set_content(r, "text/plain");
  17974. });
  17975. svr_.Post("/echo-params",
  17976. [](const httplib::Request &req, httplib::Response &res) {
  17977. std::string r = "params:";
  17978. for (const auto &p : req.params)
  17979. r += p.first + "=" + p.second + ";";
  17980. res.set_content(r + " body:" + req.body, "text/plain");
  17981. });
  17982. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17983. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17984. });
  17985. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17986. res.set_content("PUT:" + req.body, "text/plain");
  17987. });
  17988. svr_.Patch("/echo",
  17989. [](const httplib::Request &req, httplib::Response &res) {
  17990. res.set_content("PATCH:" + req.body, "text/plain");
  17991. });
  17992. svr_.Delete(
  17993. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17994. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17995. "text/plain");
  17996. });
  17997. svr_.Get("/head-test",
  17998. [](const httplib::Request &, httplib::Response &res) {
  17999. res.set_content("body for HEAD", "text/plain");
  18000. });
  18001. svr_.Options("/options",
  18002. [](const httplib::Request &, httplib::Response &res) {
  18003. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18004. });
  18005. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18006. svr_.wait_until_ready();
  18007. }
  18008. void TearDown() override {
  18009. svr_.stop();
  18010. if (thread_.joinable()) thread_.join();
  18011. }
  18012. httplib::Server svr_;
  18013. std::thread thread_;
  18014. };
  18015. // stream::Get tests
  18016. TEST_F(StreamApiTest, GetBasic) {
  18017. httplib::Client cli(HOST, PORT);
  18018. auto result = httplib::stream::Get(cli, "/hello");
  18019. ASSERT_TRUE(result.is_valid());
  18020. EXPECT_EQ(200, result.status());
  18021. EXPECT_EQ("Hello World!", read_body(result));
  18022. }
  18023. TEST_F(StreamApiTest, GetWithParams) {
  18024. httplib::Client cli(HOST, PORT);
  18025. httplib::Params params{{"foo", "bar"}};
  18026. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18027. ASSERT_TRUE(result.is_valid());
  18028. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18029. }
  18030. TEST_F(StreamApiTest, GetConnectionError) {
  18031. httplib::Client cli(HOST, 9999);
  18032. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18033. }
  18034. TEST_F(StreamApiTest, Get404) {
  18035. httplib::Client cli(HOST, PORT);
  18036. auto result = httplib::stream::Get(cli, "/nonexistent");
  18037. EXPECT_TRUE(result.is_valid());
  18038. EXPECT_EQ(404, result.status());
  18039. }
  18040. // stream::Post tests
  18041. TEST_F(StreamApiTest, PostBasic) {
  18042. httplib::Client cli(HOST, PORT);
  18043. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18044. "application/json");
  18045. ASSERT_TRUE(result.is_valid());
  18046. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18047. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18048. }
  18049. TEST_F(StreamApiTest, PostWithHeaders) {
  18050. httplib::Client cli(HOST, PORT);
  18051. httplib::Headers headers{{"X-Custom", "value"}};
  18052. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18053. "text/plain");
  18054. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18055. }
  18056. TEST_F(StreamApiTest, PostWithParams) {
  18057. httplib::Client cli(HOST, PORT);
  18058. httplib::Params params{{"k", "v"}};
  18059. auto result =
  18060. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18061. auto body = read_body(result);
  18062. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18063. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18064. }
  18065. TEST_F(StreamApiTest, PostLarge) {
  18066. httplib::Client cli(HOST, PORT);
  18067. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18068. size_t total = 0;
  18069. while (result.next()) {
  18070. total += result.size();
  18071. }
  18072. EXPECT_EQ(100u * 1024u, total);
  18073. }
  18074. // stream::Put/Patch tests
  18075. TEST_F(StreamApiTest, PutAndPatch) {
  18076. httplib::Client cli(HOST, PORT);
  18077. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18078. EXPECT_EQ("PUT:test", read_body(put));
  18079. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18080. EXPECT_EQ("PATCH:test", read_body(patch));
  18081. }
  18082. // stream::Delete tests
  18083. TEST_F(StreamApiTest, Delete) {
  18084. httplib::Client cli(HOST, PORT);
  18085. auto del1 = httplib::stream::Delete(cli, "/resource");
  18086. EXPECT_EQ("Deleted", read_body(del1));
  18087. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18088. EXPECT_EQ("Deleted:data", read_body(del2));
  18089. }
  18090. // stream::Head/Options tests
  18091. TEST_F(StreamApiTest, HeadAndOptions) {
  18092. httplib::Client cli(HOST, PORT);
  18093. auto head = httplib::stream::Head(cli, "/head-test");
  18094. EXPECT_TRUE(head.is_valid());
  18095. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18096. auto opts = httplib::stream::Options(cli, "/options");
  18097. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18098. }
  18099. // SSL stream::* tests
  18100. #ifdef CPPHTTPLIB_SSL_ENABLED
  18101. class SSLStreamApiTest : public ::testing::Test {
  18102. protected:
  18103. void SetUp() override {
  18104. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18105. res.set_content("Hello SSL!", "text/plain");
  18106. });
  18107. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18108. res.set_content(req.body, "text/plain");
  18109. });
  18110. port_ = svr_.bind_to_any_port("127.0.0.1");
  18111. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18112. svr_.wait_until_ready();
  18113. }
  18114. void TearDown() override {
  18115. svr_.stop();
  18116. if (thread_.joinable()) thread_.join();
  18117. }
  18118. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18119. std::thread thread_;
  18120. int port_ = 0;
  18121. };
  18122. TEST_F(SSLStreamApiTest, GetAndPost) {
  18123. httplib::SSLClient cli("127.0.0.1", port_);
  18124. cli.enable_server_certificate_verification(false);
  18125. auto get = httplib::stream::Get(cli, "/hello");
  18126. EXPECT_EQ("Hello SSL!", read_body(get));
  18127. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18128. EXPECT_EQ("test", read_body(post));
  18129. }
  18130. #endif
  18131. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18132. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18133. // BodyReader
  18134. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18135. // Test that read timeout during streaming is detected
  18136. // Use a large content-length response where server delays mid-stream
  18137. Server svr;
  18138. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18139. // Send a large response with delay in the middle
  18140. res.set_content_provider(
  18141. 1000, // content_length
  18142. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18143. if (offset < 100) {
  18144. // Send first 100 bytes immediately
  18145. std::string data(100, 'A');
  18146. sink.write(data.c_str(), data.size());
  18147. return true;
  18148. }
  18149. // Then delay longer than client timeout
  18150. std::this_thread::sleep_for(std::chrono::seconds(3));
  18151. std::string data(900, 'B');
  18152. sink.write(data.c_str(), data.size());
  18153. return true;
  18154. });
  18155. });
  18156. auto port = 8091;
  18157. std::thread t([&]() { svr.listen("localhost", port); });
  18158. svr.wait_until_ready();
  18159. Client cli("localhost", port);
  18160. cli.set_read_timeout(1, 0); // 1 second timeout
  18161. auto handle = cli.open_stream("GET", "/slow-stream");
  18162. ASSERT_TRUE(handle.is_valid());
  18163. char buf[256];
  18164. ssize_t total = 0;
  18165. ssize_t n;
  18166. bool got_error = false;
  18167. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18168. total += n;
  18169. }
  18170. if (n < 0) {
  18171. got_error = true;
  18172. // Should be timeout or read error
  18173. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18174. handle.get_read_error() == Error::Read)
  18175. << "Actual error: " << to_string(handle.get_read_error());
  18176. }
  18177. // Either we got an error, or we got less data than expected
  18178. EXPECT_TRUE(got_error || total < 1000)
  18179. << "Expected timeout but got all " << total << " bytes";
  18180. svr.stop();
  18181. t.join();
  18182. }
  18183. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18184. // Test connection closed detection via BodyReader
  18185. Server svr;
  18186. std::atomic<bool> close_now{false};
  18187. svr.Get("/will-close", [&](const Request &, Response &res) {
  18188. res.set_content_provider(
  18189. 10000, // Large content_length that we won't fully send
  18190. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18191. if (offset < 100) {
  18192. std::string data(100, 'X');
  18193. sink.write(data.c_str(), data.size());
  18194. return true;
  18195. }
  18196. // Wait for signal then abort
  18197. while (!close_now) {
  18198. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18199. }
  18200. return false; // Abort - server will close connection
  18201. });
  18202. });
  18203. auto port = 8092;
  18204. std::thread t([&]() { svr.listen("localhost", port); });
  18205. svr.wait_until_ready();
  18206. Client cli("localhost", port);
  18207. auto handle = cli.open_stream("GET", "/will-close");
  18208. ASSERT_TRUE(handle.is_valid());
  18209. char buf[256];
  18210. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18211. EXPECT_GT(n, 0) << "First read should succeed";
  18212. // Signal server to close
  18213. close_now = true;
  18214. // Keep reading until error or EOF
  18215. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18216. // Keep reading
  18217. }
  18218. // Should get an error since content_length wasn't satisfied
  18219. if (n < 0) {
  18220. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18221. handle.get_read_error() == Error::Read)
  18222. << "Actual error: " << to_string(handle.get_read_error());
  18223. }
  18224. svr.stop();
  18225. t.join();
  18226. }
  18227. #ifdef CPPHTTPLIB_SSL_ENABLED
  18228. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18229. // Test that read timeout during SSL streaming is detected
  18230. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18231. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18232. res.set_content_provider(
  18233. 1000, "text/plain",
  18234. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18235. if (offset < 100) {
  18236. std::string data(100, 'A');
  18237. sink.write(data.c_str(), data.size());
  18238. return true;
  18239. }
  18240. std::this_thread::sleep_for(std::chrono::seconds(3));
  18241. std::string data(900, 'B');
  18242. sink.write(data.c_str(), data.size());
  18243. return true;
  18244. });
  18245. });
  18246. auto port = 8093;
  18247. std::thread t([&]() { svr.listen("localhost", port); });
  18248. svr.wait_until_ready();
  18249. SSLClient cli("localhost", port);
  18250. cli.enable_server_certificate_verification(false);
  18251. cli.set_read_timeout(1, 0); // 1 second timeout
  18252. auto handle = cli.open_stream("GET", "/slow-stream");
  18253. ASSERT_TRUE(handle.is_valid());
  18254. char buf[256];
  18255. ssize_t total = 0;
  18256. ssize_t n;
  18257. bool got_error = false;
  18258. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18259. total += n;
  18260. }
  18261. if (n < 0) {
  18262. got_error = true;
  18263. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18264. handle.get_read_error() == Error::Read)
  18265. << "Actual error: " << to_string(handle.get_read_error());
  18266. }
  18267. EXPECT_TRUE(got_error || total < 1000)
  18268. << "Expected timeout but got all " << total << " bytes";
  18269. svr.stop();
  18270. t.join();
  18271. }
  18272. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18273. // Test SSL connection closed detection
  18274. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18275. std::atomic<bool> close_now{false};
  18276. svr.Get("/will-close", [&](const Request &, Response &res) {
  18277. res.set_content_provider(
  18278. 10000, "text/plain",
  18279. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18280. if (offset < 100) {
  18281. std::string data(100, 'X');
  18282. sink.write(data.c_str(), data.size());
  18283. return true;
  18284. }
  18285. while (!close_now) {
  18286. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18287. }
  18288. return false;
  18289. });
  18290. });
  18291. auto port = 8094;
  18292. std::thread t([&]() { svr.listen("localhost", port); });
  18293. svr.wait_until_ready();
  18294. SSLClient cli("localhost", port);
  18295. cli.enable_server_certificate_verification(false);
  18296. auto handle = cli.open_stream("GET", "/will-close");
  18297. ASSERT_TRUE(handle.is_valid());
  18298. char buf[256];
  18299. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18300. EXPECT_GT(n, 0);
  18301. // Signal server to close
  18302. close_now = true;
  18303. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18304. // Keep reading
  18305. }
  18306. if (n < 0) {
  18307. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18308. handle.get_read_error() == Error::Read)
  18309. << "Actual error: " << to_string(handle.get_read_error());
  18310. }
  18311. svr.stop();
  18312. t.join();
  18313. }
  18314. #endif
  18315. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18316. using namespace httplib;
  18317. // Create a test file
  18318. const char *fname = "etag_testfile.txt";
  18319. const char *content = "etag-content";
  18320. {
  18321. std::ofstream ofs(fname);
  18322. ofs << content;
  18323. ASSERT_TRUE(ofs.good());
  18324. }
  18325. Server svr;
  18326. svr.set_mount_point("/static", ".");
  18327. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18328. svr.wait_until_ready();
  18329. Client cli(HOST, PORT);
  18330. // First request: should get 200 with ETag header
  18331. auto res1 = cli.Get("/static/etag_testfile.txt");
  18332. ASSERT_TRUE(res1);
  18333. ASSERT_EQ(200, res1->status);
  18334. ASSERT_TRUE(res1->has_header("ETag"));
  18335. std::string etag = res1->get_header_value("ETag");
  18336. EXPECT_FALSE(etag.empty());
  18337. // Verify ETag format: W/"hex-hex"
  18338. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18339. EXPECT_EQ('W', etag[0]);
  18340. EXPECT_EQ('/', etag[1]);
  18341. EXPECT_EQ('"', etag[2]);
  18342. EXPECT_EQ('"', etag.back());
  18343. // Exact match: expect 304 Not Modified
  18344. Headers h2 = {{"If-None-Match", etag}};
  18345. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18346. ASSERT_TRUE(res2);
  18347. EXPECT_EQ(304, res2->status);
  18348. // Wildcard match: expect 304 Not Modified
  18349. Headers h3 = {{"If-None-Match", "*"}};
  18350. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18351. ASSERT_TRUE(res3);
  18352. EXPECT_EQ(304, res3->status);
  18353. // Non-matching ETag: expect 200
  18354. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18355. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18356. ASSERT_TRUE(res4);
  18357. EXPECT_EQ(200, res4->status);
  18358. // Multiple ETags with one matching: expect 304
  18359. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18360. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18361. ASSERT_TRUE(res5);
  18362. EXPECT_EQ(304, res5->status);
  18363. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18364. // that equivalent to the single comma-separated list above, so the match on
  18365. // the second line must still be found.
  18366. Headers h6;
  18367. h6.emplace("If-None-Match", "W/\"other\"");
  18368. h6.emplace("If-None-Match", etag);
  18369. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18370. ASSERT_TRUE(res6);
  18371. EXPECT_EQ(304, res6->status);
  18372. svr.stop();
  18373. t.join();
  18374. std::remove(fname);
  18375. }
  18376. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18377. using namespace httplib;
  18378. Server svr;
  18379. svr.set_mount_point("/static", ".");
  18380. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18381. svr.wait_until_ready();
  18382. Client cli(HOST, PORT);
  18383. // Send If-None-Match: * to a non-existent file
  18384. Headers h = {{"If-None-Match", "*"}};
  18385. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18387. EXPECT_EQ(404, res->status);
  18388. svr.stop();
  18389. t.join();
  18390. }
  18391. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18392. using namespace httplib;
  18393. // Create a test file
  18394. const char *fname = "etag_boundary_testfile.txt";
  18395. const char *content = "boundary-test";
  18396. {
  18397. std::ofstream ofs(fname);
  18398. ofs << content;
  18399. ASSERT_TRUE(ofs.good());
  18400. }
  18401. Server svr;
  18402. svr.set_mount_point("/static", ".");
  18403. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18404. svr.wait_until_ready();
  18405. Client cli(HOST, PORT);
  18406. // Get the actual ETag
  18407. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18408. ASSERT_TRUE(res1);
  18409. ASSERT_EQ(200, res1->status);
  18410. ASSERT_TRUE(res1->has_header("ETag"));
  18411. std::string etag = res1->get_header_value("ETag");
  18412. // Test 1: Very long ETag value (longer than actual ETag)
  18413. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18414. Headers h1 = {{"If-None-Match", "W/"
  18415. "\"very-long-etag-value-that-is-much-longer-"
  18416. "than-the-actual-etag-value\""}};
  18417. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18418. ASSERT_TRUE(res2);
  18419. EXPECT_EQ(200, res2->status); // Should not match
  18420. // Test 2: Long string followed by wildcard
  18421. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18422. // string)
  18423. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18424. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18425. ASSERT_TRUE(res3);
  18426. EXPECT_EQ(304, res3->status); // Should match on "*"
  18427. // Test 3: Wildcard followed by long string
  18428. // Should match on "*" immediately and return 304
  18429. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18430. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18431. ASSERT_TRUE(res4);
  18432. EXPECT_EQ(304, res4->status); // Should match on "*"
  18433. // Test 4: Multiple long non-matching values
  18434. // Should NOT match and return 200 (test that all comparisons are safe)
  18435. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18436. "W/\"second-long-non-matching-value\", "
  18437. "W/\"third-long-non-matching-value\""}};
  18438. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18439. ASSERT_TRUE(res5);
  18440. EXPECT_EQ(200, res5->status); // Should not match
  18441. // Test 5: Single character that is not "*" (edge case)
  18442. Headers h5 = {{"If-None-Match", "X"}};
  18443. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18444. ASSERT_TRUE(res6);
  18445. EXPECT_EQ(200, res6->status); // Should not match
  18446. svr.stop();
  18447. t.join();
  18448. std::remove(fname);
  18449. }
  18450. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18451. using namespace httplib;
  18452. // Create a test file
  18453. const char *fname = "ims_testfile.txt";
  18454. const char *content = "if-modified-since-test";
  18455. {
  18456. std::ofstream ofs(fname);
  18457. ofs << content;
  18458. ASSERT_TRUE(ofs.good());
  18459. }
  18460. Server svr;
  18461. svr.set_mount_point("/static", ".");
  18462. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18463. svr.wait_until_ready();
  18464. Client cli(HOST, PORT);
  18465. // First request: should get 200 with Last-Modified header
  18466. auto res1 = cli.Get("/static/ims_testfile.txt");
  18467. ASSERT_TRUE(res1);
  18468. ASSERT_EQ(200, res1->status);
  18469. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18470. std::string last_modified = res1->get_header_value("Last-Modified");
  18471. EXPECT_FALSE(last_modified.empty());
  18472. // If-Modified-Since with same time: expect 304
  18473. Headers h2 = {{"If-Modified-Since", last_modified}};
  18474. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18475. ASSERT_TRUE(res2);
  18476. EXPECT_EQ(304, res2->status);
  18477. // If-Modified-Since with future time: expect 304
  18478. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18479. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18480. ASSERT_TRUE(res3);
  18481. EXPECT_EQ(304, res3->status);
  18482. // If-Modified-Since with past time: expect 200
  18483. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18484. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18485. ASSERT_TRUE(res4);
  18486. EXPECT_EQ(200, res4->status);
  18487. // If-None-Match takes precedence over If-Modified-Since
  18488. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18489. ASSERT_TRUE(res1->has_header("ETag"));
  18490. std::string etag = res1->get_header_value("ETag");
  18491. Headers h5 = {{"If-None-Match", etag},
  18492. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18493. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18494. ASSERT_TRUE(res5);
  18495. EXPECT_EQ(304, res5->status);
  18496. svr.stop();
  18497. t.join();
  18498. std::remove(fname);
  18499. }
  18500. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18501. using namespace httplib;
  18502. Server svr;
  18503. // Endpoint that returns compressible content
  18504. svr.Get("/compressible", [](const Request &, Response &res) {
  18505. // Return a large enough body to trigger compression
  18506. std::string body(1000, 'a');
  18507. res.set_content(body, "text/plain");
  18508. });
  18509. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18510. svr.wait_until_ready();
  18511. Client cli(HOST, PORT);
  18512. // Request with gzip support: should get Vary header when compressed
  18513. cli.set_compress(true);
  18514. auto res1 = cli.Get("/compressible");
  18515. ASSERT_TRUE(res1);
  18516. EXPECT_EQ(200, res1->status);
  18517. // If Content-Encoding is set, Vary should also be set
  18518. if (res1->has_header("Content-Encoding")) {
  18519. EXPECT_TRUE(res1->has_header("Vary"));
  18520. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18521. }
  18522. // Request without Accept-Encoding header: should not have compression
  18523. Headers h_no_compress;
  18524. auto res2 = cli.Get("/compressible", h_no_compress);
  18525. ASSERT_TRUE(res2);
  18526. EXPECT_EQ(200, res2->status);
  18527. // Verify Vary header is present when compression is applied
  18528. // (the exact behavior depends on server configuration)
  18529. svr.stop();
  18530. t.join();
  18531. }
  18532. TEST(ETagTest, IfRangeWithETag) {
  18533. using namespace httplib;
  18534. // Create a test file with known content
  18535. const char *fname = "if_range_testfile.txt";
  18536. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18537. {
  18538. std::ofstream ofs(fname);
  18539. ofs << content;
  18540. ASSERT_TRUE(ofs.good());
  18541. }
  18542. Server svr;
  18543. svr.set_mount_point("/static", ".");
  18544. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18545. svr.wait_until_ready();
  18546. Client cli(HOST, PORT);
  18547. // First request: get ETag
  18548. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18549. ASSERT_TRUE(res1);
  18550. ASSERT_EQ(200, res1->status);
  18551. ASSERT_TRUE(res1->has_header("ETag"));
  18552. std::string etag = res1->get_header_value("ETag");
  18553. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18554. // Since our server generates weak ETags (W/"..."), If-Range with our
  18555. // ETag should NOT result in partial content - it should return full content.
  18556. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18557. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18558. ASSERT_TRUE(res2);
  18559. // Weak ETag in If-Range -> full content (200), not partial (206)
  18560. EXPECT_EQ(200, res2->status);
  18561. EXPECT_EQ(content, res2->body);
  18562. EXPECT_FALSE(res2->has_header("Content-Range"));
  18563. // Range request with non-matching If-Range (ETag): should get 200 (full
  18564. // content)
  18565. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18566. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18567. ASSERT_TRUE(res3);
  18568. EXPECT_EQ(200, res3->status);
  18569. EXPECT_EQ(content, res3->body);
  18570. EXPECT_FALSE(res3->has_header("Content-Range"));
  18571. // Range request with strong ETag (hypothetical - our server doesn't generate
  18572. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18573. // should return full content)
  18574. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18575. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18576. ASSERT_TRUE(res4);
  18577. EXPECT_EQ(200, res4->status);
  18578. EXPECT_EQ(content, res4->body);
  18579. EXPECT_FALSE(res4->has_header("Content-Range"));
  18580. svr.stop();
  18581. t.join();
  18582. std::remove(fname);
  18583. }
  18584. TEST(ETagTest, IfRangeWithDate) {
  18585. using namespace httplib;
  18586. // Create a test file
  18587. const char *fname = "if_range_date_testfile.txt";
  18588. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18589. {
  18590. std::ofstream ofs(fname);
  18591. ofs << content;
  18592. ASSERT_TRUE(ofs.good());
  18593. }
  18594. Server svr;
  18595. svr.set_mount_point("/static", ".");
  18596. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18597. svr.wait_until_ready();
  18598. Client cli(HOST, PORT);
  18599. // First request: get Last-Modified
  18600. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18601. ASSERT_TRUE(res1);
  18602. ASSERT_EQ(200, res1->status);
  18603. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18604. std::string last_modified = res1->get_header_value("Last-Modified");
  18605. // Range request with matching If-Range (date): should get 206
  18606. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18607. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18608. ASSERT_TRUE(res2);
  18609. EXPECT_EQ(206, res2->status);
  18610. EXPECT_EQ("FGHIJ", res2->body);
  18611. // Range request with old If-Range date: should get 200 (full content)
  18612. Headers h3 = {{"Range", "bytes=5-9"},
  18613. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18614. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18615. ASSERT_TRUE(res3);
  18616. EXPECT_EQ(200, res3->status);
  18617. EXPECT_EQ(content, res3->body);
  18618. // Range request with future If-Range date: should get 206
  18619. Headers h4 = {{"Range", "bytes=0-4"},
  18620. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18621. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18622. ASSERT_TRUE(res4);
  18623. EXPECT_EQ(206, res4->status);
  18624. EXPECT_EQ("ABCDE", res4->body);
  18625. svr.stop();
  18626. t.join();
  18627. std::remove(fname);
  18628. }
  18629. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18630. using namespace httplib;
  18631. const char *fname = "etag_malformed.txt";
  18632. const char *content = "malformed-etag";
  18633. {
  18634. std::ofstream ofs(fname);
  18635. ofs << content;
  18636. ASSERT_TRUE(ofs.good());
  18637. }
  18638. Server svr;
  18639. svr.set_mount_point("/static", ".");
  18640. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18641. svr.wait_until_ready();
  18642. Client cli(HOST, PORT);
  18643. // baseline: should get 200 and an ETag
  18644. auto res1 = cli.Get("/static/etag_malformed.txt");
  18645. ASSERT_TRUE(res1);
  18646. ASSERT_EQ(200, res1->status);
  18647. ASSERT_TRUE(res1->has_header("ETag"));
  18648. // Malformed ETag value (missing quotes) should be treated as non-matching
  18649. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18650. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18651. ASSERT_TRUE(res_bad);
  18652. EXPECT_EQ(200, res_bad->status);
  18653. // Whitespace-only header value should be considered invalid / non-matching
  18654. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18655. "Host: localhost\r\n"
  18656. "If-None-Match: \r\n"
  18657. "Connection: close\r\n"
  18658. "\r\n";
  18659. std::string out;
  18660. ASSERT_TRUE(send_request(5, raw_req, &out));
  18661. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18662. svr.stop();
  18663. t.join();
  18664. std::remove(fname);
  18665. }
  18666. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18667. using namespace httplib;
  18668. const char *fname = "ims_invalid_format.txt";
  18669. const char *content = "ims-bad-format";
  18670. {
  18671. std::ofstream ofs(fname);
  18672. ofs << content;
  18673. ASSERT_TRUE(ofs.good());
  18674. }
  18675. Server svr;
  18676. svr.set_mount_point("/static", ".");
  18677. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18678. svr.wait_until_ready();
  18679. Client cli(HOST, PORT);
  18680. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18681. ASSERT_TRUE(res1);
  18682. ASSERT_EQ(200, res1->status);
  18683. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18684. // If-Modified-Since with invalid format should not result in 304
  18685. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18686. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18687. ASSERT_TRUE(res_bad);
  18688. EXPECT_EQ(200, res_bad->status);
  18689. // If-Range with invalid date format should be treated as mismatch -> full
  18690. // content (200)
  18691. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18692. {"If-Range", "invalid-date"}};
  18693. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18694. ASSERT_TRUE(res_ifrange);
  18695. EXPECT_EQ(200, res_ifrange->status);
  18696. svr.stop();
  18697. t.join();
  18698. std::remove(fname);
  18699. }
  18700. TEST(ETagTest, IfRangeWithMalformedETag) {
  18701. using namespace httplib;
  18702. const char *fname = "ifrange_malformed.txt";
  18703. const std::string content = "0123456789";
  18704. {
  18705. std::ofstream ofs(fname);
  18706. ofs << content;
  18707. ASSERT_TRUE(ofs.good());
  18708. }
  18709. Server svr;
  18710. svr.set_mount_point("/static", ".");
  18711. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18712. svr.wait_until_ready();
  18713. Client cli(HOST, PORT);
  18714. // First request: get ETag
  18715. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18716. ASSERT_TRUE(res1);
  18717. ASSERT_EQ(200, res1->status);
  18718. ASSERT_TRUE(res1->has_header("ETag"));
  18719. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18720. // full content (200)
  18721. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18722. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18723. ASSERT_TRUE(res2);
  18724. EXPECT_EQ(200, res2->status);
  18725. EXPECT_EQ(content, res2->body);
  18726. svr.stop();
  18727. t.join();
  18728. std::remove(fname);
  18729. }
  18730. TEST(ETagTest, ExtremeLargeDateValues) {
  18731. using namespace httplib;
  18732. const char *fname = "ims_extreme_date.txt";
  18733. const char *content = "ims-extreme-date";
  18734. {
  18735. std::ofstream ofs(fname);
  18736. ofs << content;
  18737. ASSERT_TRUE(ofs.good());
  18738. }
  18739. Server svr;
  18740. svr.set_mount_point("/static", ".");
  18741. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18742. svr.wait_until_ready();
  18743. Client cli(HOST, PORT);
  18744. auto res1 = cli.Get(std::string("/static/") + fname);
  18745. ASSERT_TRUE(res1);
  18746. ASSERT_EQ(200, res1->status);
  18747. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18748. // Extremely large year that may overflow date parsing routines.
  18749. Headers h_large_date = {
  18750. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18751. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18752. ASSERT_TRUE(res_bad);
  18753. // Expect server to treat this as invalid/mismatch and return full content
  18754. EXPECT_EQ(200, res_bad->status);
  18755. // If-Range with extremely large date should be treated as mismatch -> full
  18756. // content (200)
  18757. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18758. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18759. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18760. ASSERT_TRUE(res_ifrange);
  18761. EXPECT_EQ(200, res_ifrange->status);
  18762. svr.stop();
  18763. t.join();
  18764. std::remove(fname);
  18765. }
  18766. TEST(ETagTest, NegativeFileModificationTime) {
  18767. using namespace httplib;
  18768. const char *fname = "ims_negative_mtime.txt";
  18769. const std::string content = "negative-mtime";
  18770. {
  18771. std::ofstream ofs(fname);
  18772. ofs << content;
  18773. ASSERT_TRUE(ofs.good());
  18774. }
  18775. // Try to set file mtime to a negative value. This may fail on some
  18776. // platforms/filesystems; if it fails, the test will still verify server
  18777. // behaves safely by performing a regular conditional request.
  18778. #if defined(__APPLE__) || defined(__linux__)
  18779. bool set_negative = false;
  18780. do {
  18781. struct timeval times[2];
  18782. // access time: now
  18783. times[0].tv_sec = time(nullptr);
  18784. times[0].tv_usec = 0;
  18785. // modification time: negative (e.g., -1)
  18786. times[1].tv_sec = -1;
  18787. times[1].tv_usec = 0;
  18788. if (utimes(fname, times) == 0) { set_negative = true; }
  18789. } while (0);
  18790. #else
  18791. bool set_negative = false;
  18792. #endif
  18793. Server svr;
  18794. svr.set_mount_point("/static", ".");
  18795. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18796. svr.wait_until_ready();
  18797. Client cli(HOST, PORT);
  18798. auto res1 = cli.Get(std::string("/static/") + fname);
  18799. ASSERT_TRUE(res1);
  18800. ASSERT_EQ(200, res1->status);
  18801. bool has_last_modified = res1->has_header("Last-Modified");
  18802. std::string last_modified;
  18803. if (has_last_modified) {
  18804. last_modified = res1->get_header_value("Last-Modified");
  18805. }
  18806. if (set_negative) {
  18807. // If we successfully set a negative mtime, ensure server returns a
  18808. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18809. // with an old date and ensure server handles it without crash.
  18810. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18811. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18812. ASSERT_TRUE(res2);
  18813. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18814. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18815. } else {
  18816. // Could not set negative mtime on this platform; fall back to verifying
  18817. // that normal invalid/malformed dates are treated safely (non-304).
  18818. Headers h_bad_date = {
  18819. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18820. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18821. ASSERT_TRUE(res_bad);
  18822. EXPECT_EQ(200, res_bad->status);
  18823. }
  18824. svr.stop();
  18825. t.join();
  18826. std::remove(fname);
  18827. }
  18828. //==============================================================================
  18829. // Integration Tests with Server
  18830. //==============================================================================
  18831. class SSEIntegrationTest : public ::testing::Test {
  18832. protected:
  18833. void SetUp() override {
  18834. stop_server_.store(false);
  18835. events_.clear();
  18836. server_ = httplib::detail::make_unique<Server>();
  18837. setup_server();
  18838. start_server();
  18839. }
  18840. void TearDown() override {
  18841. stop_server_.store(true);
  18842. event_cv_.notify_all();
  18843. server_->stop();
  18844. if (server_thread_.joinable()) { server_thread_.join(); }
  18845. }
  18846. void setup_server() {
  18847. // Simple SSE endpoint
  18848. server_->Get("/events", [this](const Request &req, Response &res) {
  18849. auto last_id = req.get_header_value("Last-Event-ID");
  18850. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18851. res.set_chunked_content_provider(
  18852. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18853. std::unique_lock<std::mutex> lock(event_mutex_);
  18854. if (event_cv_.wait_for(
  18855. lock, std::chrono::milliseconds(200), [this] {
  18856. return !events_.empty() || stop_server_.load();
  18857. })) {
  18858. if (stop_server_.load()) { return false; }
  18859. if (!events_.empty()) {
  18860. std::string event = events_.front();
  18861. events_.erase(events_.begin());
  18862. sink.write(event.data(), event.size());
  18863. return true;
  18864. }
  18865. }
  18866. return !stop_server_.load();
  18867. });
  18868. });
  18869. // Endpoint that returns error
  18870. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18871. res.status = 500;
  18872. res.set_content("Internal Server Error", "text/plain");
  18873. });
  18874. // Endpoint for custom event types
  18875. server_->Get("/custom-events", [](const Request &, Response &res) {
  18876. res.set_chunked_content_provider(
  18877. "text/event-stream", [](size_t offset, DataSink &sink) {
  18878. if (offset == 0) {
  18879. std::string event = "event: update\ndata: updated\n\n"
  18880. "event: delete\ndata: deleted\n\n";
  18881. sink.write(event.data(), event.size());
  18882. }
  18883. return false; // End stream after sending
  18884. });
  18885. });
  18886. }
  18887. void start_server() {
  18888. port_ = server_->bind_to_any_port(HOST);
  18889. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18890. // Wait for server to start
  18891. while (!server_->is_running()) {
  18892. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18893. }
  18894. }
  18895. int get_port() const { return port_; }
  18896. void send_event(const std::string &event) {
  18897. std::lock_guard<std::mutex> lock(event_mutex_);
  18898. events_.push_back(event);
  18899. event_cv_.notify_all();
  18900. }
  18901. std::unique_ptr<Server> server_;
  18902. std::thread server_thread_;
  18903. std::mutex event_mutex_;
  18904. std::condition_variable event_cv_;
  18905. std::vector<std::string> events_;
  18906. std::atomic<bool> stop_server_{false};
  18907. std::string last_received_event_id_;
  18908. int port_ = 0;
  18909. };
  18910. //==============================================================================
  18911. // SSE Parsing Tests
  18912. //==============================================================================
  18913. class SSEParsingTest : public SSEIntegrationTest {
  18914. protected:
  18915. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  18916. // A trailing sentinel event tells when the whole stream has been parsed.
  18917. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  18918. auto body = stream + "event: end\ndata: end\n\n";
  18919. server_->Get("/parse", [body](const Request &, Response &res) {
  18920. res.set_content(body, "text/event-stream");
  18921. });
  18922. return collect("/parse");
  18923. }
  18924. // Runs SSEClient against path until an "end" event arrives and returns the
  18925. // messages dispatched before it
  18926. std::vector<sse::SSEMessage> collect(const std::string &path) {
  18927. Client client(HOST, get_port());
  18928. sse::SSEClient sse(client, path);
  18929. std::mutex mutex;
  18930. std::condition_variable cv;
  18931. std::vector<sse::SSEMessage> messages;
  18932. auto done = false;
  18933. sse.on_message([&](const sse::SSEMessage &msg) {
  18934. std::lock_guard<std::mutex> lock(mutex);
  18935. // Ignore a replay from a reconnect that races with stop()
  18936. if (!done) { messages.push_back(msg); }
  18937. });
  18938. sse.on_event("end", [&](const sse::SSEMessage &) {
  18939. std::lock_guard<std::mutex> lock(mutex);
  18940. done = true;
  18941. cv.notify_all();
  18942. });
  18943. sse.set_reconnect_interval(100);
  18944. sse.start_async();
  18945. {
  18946. std::unique_lock<std::mutex> lock(mutex);
  18947. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  18948. }
  18949. sse.stop();
  18950. EXPECT_TRUE(done);
  18951. return messages;
  18952. }
  18953. };
  18954. TEST_F(SSEParsingTest, SingleLineData) {
  18955. auto msgs = parse("data: hello\n\n");
  18956. ASSERT_EQ(msgs.size(), 1u);
  18957. EXPECT_EQ(msgs[0].data, "hello");
  18958. EXPECT_EQ(msgs[0].event, "message");
  18959. }
  18960. TEST_F(SSEParsingTest, MultiLineData) {
  18961. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  18962. ASSERT_EQ(msgs.size(), 1u);
  18963. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  18964. }
  18965. TEST_F(SSEParsingTest, CustomEventType) {
  18966. auto msgs = parse("event: update\ndata: payload\n\n");
  18967. ASSERT_EQ(msgs.size(), 1u);
  18968. EXPECT_EQ(msgs[0].event, "update");
  18969. EXPECT_EQ(msgs[0].data, "payload");
  18970. }
  18971. TEST_F(SSEParsingTest, EventIdHandling) {
  18972. auto msgs = parse("id: 12345\ndata: test\n\n");
  18973. ASSERT_EQ(msgs.size(), 1u);
  18974. EXPECT_EQ(msgs[0].id, "12345");
  18975. }
  18976. TEST_F(SSEParsingTest, EmptyEventId) {
  18977. auto msgs = parse("id:\ndata: test\n\n");
  18978. ASSERT_EQ(msgs.size(), 1u);
  18979. EXPECT_EQ(msgs[0].id, "");
  18980. }
  18981. TEST_F(SSEParsingTest, CommentsIgnored) {
  18982. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  18983. ASSERT_EQ(msgs.size(), 1u);
  18984. EXPECT_EQ(msgs[0].data, "hello");
  18985. EXPECT_EQ(msgs[0].event, "message");
  18986. }
  18987. TEST_F(SSEParsingTest, ColonInValue) {
  18988. auto msgs = parse("data: hello:world:test\n\n");
  18989. ASSERT_EQ(msgs.size(), 1u);
  18990. EXPECT_EQ(msgs[0].data, "hello:world:test");
  18991. }
  18992. TEST_F(SSEParsingTest, FieldNameOnly) {
  18993. // A line without a colon is a field name with an empty value
  18994. auto msgs = parse("data\n\n");
  18995. ASSERT_EQ(msgs.size(), 1u);
  18996. EXPECT_EQ(msgs[0].data, "");
  18997. }
  18998. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18999. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19000. ASSERT_EQ(msgs.size(), 1u);
  19001. EXPECT_EQ(msgs[0].event, "update");
  19002. EXPECT_EQ(msgs[0].data, "hello");
  19003. }
  19004. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19005. auto msgs = parse("data\r\n\r\n");
  19006. ASSERT_EQ(msgs.size(), 1u);
  19007. EXPECT_EQ(msgs[0].data, "");
  19008. }
  19009. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19010. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19011. ASSERT_EQ(msgs.size(), 1u);
  19012. EXPECT_EQ(msgs[0].data, "hello");
  19013. EXPECT_EQ(msgs[0].event, "message");
  19014. }
  19015. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19016. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19017. ASSERT_EQ(msgs.size(), 2u);
  19018. EXPECT_EQ(msgs[0].data, "hello");
  19019. EXPECT_EQ(msgs[1].data, "hello");
  19020. }
  19021. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19022. // An event without data is not dispatched, and its type must not leak
  19023. // into the next event
  19024. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19025. ASSERT_EQ(msgs.size(), 1u);
  19026. EXPECT_EQ(msgs[0].event, "message");
  19027. EXPECT_EQ(msgs[0].data, "hello");
  19028. }
  19029. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19030. // The first connection sends only an id; the second echoes back the
  19031. // Last-Event-ID it was reconnected with
  19032. std::atomic<int> connection_count{0};
  19033. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19034. if (connection_count++ == 0) {
  19035. res.set_content("id: 42\n\n", "text/event-stream");
  19036. } else {
  19037. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19038. "\n\nevent: end\ndata: end\n\n",
  19039. "text/event-stream");
  19040. }
  19041. });
  19042. auto msgs = collect("/id-only");
  19043. ASSERT_EQ(msgs.size(), 1u);
  19044. EXPECT_EQ(msgs[0].data, "42");
  19045. }
  19046. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19047. // The first connection sets an id and then clears it with an empty one; the
  19048. // second reports whether it was reconnected with a Last-Event-ID
  19049. std::atomic<int> connection_count{0};
  19050. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19051. if (connection_count++ == 0) {
  19052. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19053. "text/event-stream");
  19054. } else {
  19055. res.set_content(
  19056. std::string("data: ") +
  19057. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19058. "\n\nevent: end\ndata: end\n\n",
  19059. "text/event-stream");
  19060. }
  19061. });
  19062. auto msgs = collect("/id-clear");
  19063. ASSERT_EQ(msgs.size(), 3u);
  19064. EXPECT_EQ(msgs[0].id, "1");
  19065. EXPECT_EQ(msgs[1].id, "");
  19066. EXPECT_EQ(msgs[2].data, "not sent");
  19067. }
  19068. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19069. auto msgs = parse("event: notification\nid: evt-42\n"
  19070. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19071. ASSERT_EQ(msgs.size(), 1u);
  19072. EXPECT_EQ(msgs[0].event, "notification");
  19073. EXPECT_EQ(msgs[0].id, "evt-42");
  19074. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19075. }
  19076. TEST(SSEMessageTest, Clear) {
  19077. sse::SSEMessage msg;
  19078. msg.event = "custom";
  19079. msg.data = "some data";
  19080. msg.id = "123";
  19081. msg.clear();
  19082. EXPECT_EQ(msg.event, "message");
  19083. EXPECT_EQ(msg.data, "");
  19084. EXPECT_EQ(msg.id, "");
  19085. }
  19086. //==============================================================================
  19087. // SSE Integration Tests
  19088. //==============================================================================
  19089. // Test: Successful connection and on_open callback
  19090. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19091. // Add a simple endpoint that sends one event and closes
  19092. server_->Get("/simple-event", [](const Request &, Response &res) {
  19093. res.set_chunked_content_provider(
  19094. "text/event-stream", [](size_t offset, DataSink &sink) {
  19095. if (offset == 0) {
  19096. std::string event = "data: hello\n\n";
  19097. sink.write(event.data(), event.size());
  19098. }
  19099. return false; // Close stream after sending
  19100. });
  19101. });
  19102. Client client("localhost", get_port());
  19103. sse::SSEClient sse(client, "/simple-event");
  19104. std::atomic<bool> open_called{false};
  19105. std::atomic<bool> message_received{false};
  19106. sse.on_open([&open_called]() { open_called.store(true); });
  19107. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19108. if (msg.data == "hello") { message_received.store(true); }
  19109. });
  19110. sse.set_reconnect_interval(100);
  19111. sse.set_max_reconnect_attempts(1);
  19112. // Start async
  19113. sse.start_async();
  19114. // Wait for message to be processed
  19115. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19116. sse.stop();
  19117. EXPECT_TRUE(open_called.load());
  19118. EXPECT_TRUE(message_received.load());
  19119. }
  19120. // Test: on_message callback
  19121. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19122. // Endpoint that sends multiple events then closes
  19123. server_->Get("/multi-event", [](const Request &, Response &res) {
  19124. res.set_chunked_content_provider(
  19125. "text/event-stream", [](size_t offset, DataSink &sink) {
  19126. if (offset == 0) {
  19127. std::string events = "data: message1\n\ndata: message2\n\n";
  19128. sink.write(events.data(), events.size());
  19129. }
  19130. return false;
  19131. });
  19132. });
  19133. Client client("localhost", get_port());
  19134. sse::SSEClient sse(client, "/multi-event");
  19135. std::vector<std::string> received_messages;
  19136. std::mutex messages_mutex;
  19137. sse.on_message([&](const sse::SSEMessage &msg) {
  19138. std::lock_guard<std::mutex> lock(messages_mutex);
  19139. received_messages.push_back(msg.data);
  19140. });
  19141. sse.set_reconnect_interval(100);
  19142. sse.set_max_reconnect_attempts(1);
  19143. sse.start_async();
  19144. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19145. sse.stop();
  19146. std::lock_guard<std::mutex> lock(messages_mutex);
  19147. EXPECT_GE(received_messages.size(), 2u);
  19148. if (received_messages.size() >= 2) {
  19149. EXPECT_EQ(received_messages[0], "message1");
  19150. EXPECT_EQ(received_messages[1], "message2");
  19151. }
  19152. }
  19153. // Test: on_event for specific types
  19154. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19155. Client client("localhost", get_port());
  19156. sse::SSEClient sse(client, "/custom-events");
  19157. std::atomic<bool> update_received{false};
  19158. std::atomic<bool> delete_received{false};
  19159. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19160. if (msg.data == "updated") { update_received.store(true); }
  19161. });
  19162. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19163. if (msg.data == "deleted") { delete_received.store(true); }
  19164. });
  19165. sse.set_max_reconnect_attempts(1);
  19166. sse.start_async();
  19167. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19168. sse.stop();
  19169. EXPECT_TRUE(update_received.load());
  19170. EXPECT_TRUE(delete_received.load());
  19171. }
  19172. // Test: on_error callback on connection failure
  19173. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19174. // Connect to a non-existent port
  19175. Client client("localhost", 59999);
  19176. sse::SSEClient sse(client, "/events");
  19177. std::atomic<bool> error_called{false};
  19178. Error received_error = Error::Success;
  19179. sse.on_error([&](Error err) {
  19180. error_called.store(true);
  19181. received_error = err;
  19182. });
  19183. sse.set_reconnect_interval(50);
  19184. sse.set_max_reconnect_attempts(1);
  19185. sse.start_async();
  19186. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19187. sse.stop();
  19188. EXPECT_TRUE(error_called.load());
  19189. EXPECT_NE(received_error, Error::Success);
  19190. }
  19191. // Test: Last-Event-ID header sent on reconnect
  19192. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19193. // Endpoint that sends event with ID
  19194. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19195. res.set_chunked_content_provider(
  19196. "text/event-stream", [](size_t offset, DataSink &sink) {
  19197. if (offset == 0) {
  19198. std::string event = "id: evt-123\ndata: test\n\n";
  19199. sink.write(event.data(), event.size());
  19200. }
  19201. return false;
  19202. });
  19203. });
  19204. Client client("localhost", get_port());
  19205. sse::SSEClient sse(client, "/event-with-id");
  19206. std::atomic<bool> id_received{false};
  19207. sse.on_message([&](const sse::SSEMessage &msg) {
  19208. if (!msg.id.empty()) { id_received.store(true); }
  19209. });
  19210. sse.set_reconnect_interval(100);
  19211. sse.set_max_reconnect_attempts(1);
  19212. sse.start_async();
  19213. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19214. sse.stop();
  19215. EXPECT_TRUE(id_received.load());
  19216. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19217. }
  19218. // Test: Manual stop
  19219. TEST_F(SSEIntegrationTest, ManualStop) {
  19220. // Endpoint that sends one event and stays open briefly
  19221. std::atomic<bool> handler_running{true};
  19222. server_->Get("/stay-open", [&handler_running](const Request &,
  19223. Response &res) {
  19224. res.set_chunked_content_provider(
  19225. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19226. if (offset == 0) {
  19227. std::string event = "data: connected\n\n";
  19228. sink.write(event.data(), event.size());
  19229. }
  19230. // Keep connection open while handler_running is true
  19231. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19232. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19233. }
  19234. return false;
  19235. });
  19236. });
  19237. Client client("localhost", get_port());
  19238. sse::SSEClient sse(client, "/stay-open");
  19239. std::atomic<bool> connected{false};
  19240. sse.on_open([&connected]() { connected.store(true); });
  19241. sse.set_reconnect_interval(100);
  19242. sse.set_max_reconnect_attempts(1);
  19243. sse.start_async();
  19244. // Wait for connection to establish
  19245. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19246. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19247. }
  19248. EXPECT_TRUE(connected.load());
  19249. EXPECT_TRUE(sse.is_connected());
  19250. // Signal handler to stop
  19251. handler_running.store(false);
  19252. // Stop SSE client
  19253. sse.stop();
  19254. EXPECT_FALSE(sse.is_connected());
  19255. }
  19256. // Test: SSEClient with custom headers
  19257. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19258. // Setup a server endpoint that checks for custom header
  19259. std::atomic<bool> header_received{false};
  19260. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19261. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19262. header_received.store(true);
  19263. }
  19264. res.set_chunked_content_provider("text/event-stream",
  19265. [](size_t, DataSink &) { return false; });
  19266. });
  19267. Client client("localhost", get_port());
  19268. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19269. sse::SSEClient sse(client, "/header-check", headers);
  19270. sse.set_max_reconnect_attempts(1);
  19271. sse.start_async();
  19272. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19273. sse.stop();
  19274. EXPECT_TRUE(header_received.load());
  19275. }
  19276. // Test: Reconnect interval configuration
  19277. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19278. Client client("localhost", get_port());
  19279. sse::SSEClient sse(client, "/events");
  19280. auto &result = sse.set_reconnect_interval(500);
  19281. // Builder pattern should return reference to self
  19282. EXPECT_EQ(&result, &sse);
  19283. }
  19284. // Test: Max reconnect attempts
  19285. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19286. // Connect to non-existent port to force reconnects
  19287. Client client("localhost", 59998);
  19288. sse::SSEClient sse(client, "/events");
  19289. std::atomic<int> error_count{0};
  19290. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19291. sse.set_reconnect_interval(50);
  19292. sse.set_max_reconnect_attempts(2);
  19293. auto start = std::chrono::steady_clock::now();
  19294. sse.start(); // Blocking call
  19295. auto end = std::chrono::steady_clock::now();
  19296. // Should have stopped after 2 failed attempts
  19297. EXPECT_GE(error_count.load(), 2);
  19298. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19299. auto duration =
  19300. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19301. #ifdef _WIN32
  19302. // Windows is much slower for socket connection failures
  19303. EXPECT_LT(duration.count(), 7000);
  19304. #else
  19305. EXPECT_LT(duration.count(), 1000);
  19306. #endif
  19307. }
  19308. // Test: Multi-line data in integration
  19309. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19310. // Endpoint with multi-line data
  19311. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19312. res.set_chunked_content_provider(
  19313. "text/event-stream", [](size_t offset, DataSink &sink) {
  19314. if (offset == 0) {
  19315. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19316. sink.write(event.data(), event.size());
  19317. }
  19318. return false;
  19319. });
  19320. });
  19321. Client client("localhost", get_port());
  19322. sse::SSEClient sse(client, "/multiline-data");
  19323. std::string received_data;
  19324. std::mutex data_mutex;
  19325. sse.on_message([&](const sse::SSEMessage &msg) {
  19326. std::lock_guard<std::mutex> lock(data_mutex);
  19327. received_data = msg.data;
  19328. });
  19329. sse.set_reconnect_interval(100);
  19330. sse.set_max_reconnect_attempts(1);
  19331. sse.start_async();
  19332. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19333. sse.stop();
  19334. std::lock_guard<std::mutex> lock(data_mutex);
  19335. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19336. }
  19337. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19338. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19339. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19340. DataSink &sink) {
  19341. if (offset == 0) {
  19342. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19343. sink.write(events.data(), events.size());
  19344. }
  19345. return false;
  19346. });
  19347. });
  19348. Client client("localhost", get_port());
  19349. sse::SSEClient sse(client, "/empty-data-lines");
  19350. std::mutex mutex;
  19351. std::condition_variable cv;
  19352. std::vector<std::string> received;
  19353. sse.on_message([&](const sse::SSEMessage &msg) {
  19354. std::lock_guard<std::mutex> lock(mutex);
  19355. received.push_back(msg.data);
  19356. cv.notify_all();
  19357. });
  19358. sse.set_max_reconnect_attempts(1);
  19359. sse.start_async();
  19360. {
  19361. std::unique_lock<std::mutex> lock(mutex);
  19362. cv.wait_for(lock, std::chrono::seconds(2),
  19363. [&] { return received.size() >= 3; });
  19364. }
  19365. sse.stop();
  19366. ASSERT_GE(received.size(), 3u);
  19367. EXPECT_EQ(received[0], "");
  19368. EXPECT_EQ(received[1], "\nhello");
  19369. EXPECT_EQ(received[2], "");
  19370. }
  19371. // Test: Auto-reconnect after server disconnection
  19372. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19373. std::atomic<int> connection_count{0};
  19374. std::atomic<int> message_count{0};
  19375. // Endpoint that sends one event and closes, forcing reconnect
  19376. server_->Get("/reconnect-test",
  19377. [&connection_count](const Request &, Response &res) {
  19378. connection_count.fetch_add(1);
  19379. res.set_chunked_content_provider(
  19380. "text/event-stream", [](size_t offset, DataSink &sink) {
  19381. if (offset == 0) {
  19382. std::string event = "data: hello\n\n";
  19383. sink.write(event.data(), event.size());
  19384. }
  19385. return false; // Close connection after sending
  19386. });
  19387. });
  19388. Client client("localhost", get_port());
  19389. sse::SSEClient sse(client, "/reconnect-test");
  19390. sse.on_message([&message_count](const sse::SSEMessage &) {
  19391. message_count.fetch_add(1);
  19392. });
  19393. sse.set_reconnect_interval(100);
  19394. sse.set_max_reconnect_attempts(3);
  19395. sse.start_async();
  19396. // Wait long enough for multiple reconnects
  19397. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19398. sse.stop();
  19399. // Should have connected multiple times (initial + reconnects)
  19400. EXPECT_GE(connection_count.load(), 2);
  19401. // Should have received messages from multiple connections
  19402. EXPECT_GE(message_count.load(), 2);
  19403. }
  19404. // Test: A retry field that is not all ASCII digits is ignored
  19405. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19406. std::atomic<int> connection_count{0};
  19407. server_->Get("/bad-retry",
  19408. [&connection_count](const Request &, Response &res) {
  19409. connection_count.fetch_add(1);
  19410. res.set_chunked_content_provider(
  19411. "text/event-stream", [](size_t offset, DataSink &sink) {
  19412. if (offset == 0) {
  19413. std::string event = "retry: -1\ndata: hello\n\n";
  19414. sink.write(event.data(), event.size());
  19415. }
  19416. return false;
  19417. });
  19418. });
  19419. Client client("localhost", get_port());
  19420. sse::SSEClient sse(client, "/bad-retry");
  19421. sse.set_reconnect_interval(10000);
  19422. sse.start_async();
  19423. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19424. sse.stop();
  19425. EXPECT_EQ(connection_count.load(), 1);
  19426. }
  19427. // Test: A retry field of all ASCII digits sets the reconnection time
  19428. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19429. std::atomic<int> connection_count{0};
  19430. server_->Get("/zero-retry",
  19431. [&connection_count](const Request &, Response &res) {
  19432. connection_count.fetch_add(1);
  19433. res.set_chunked_content_provider(
  19434. "text/event-stream", [](size_t offset, DataSink &sink) {
  19435. if (offset == 0) {
  19436. std::string event = "retry: 0\ndata: hello\n\n";
  19437. sink.write(event.data(), event.size());
  19438. }
  19439. return false;
  19440. });
  19441. });
  19442. Client client("localhost", get_port());
  19443. sse::SSEClient sse(client, "/zero-retry");
  19444. sse.set_reconnect_interval(10000);
  19445. sse.start_async();
  19446. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19447. sse.stop();
  19448. // The server-supplied interval is applied, but never below 100ms, so
  19449. // "retry: 0" does not cause a busy reconnect loop
  19450. EXPECT_GE(connection_count.load(), 2);
  19451. EXPECT_LE(connection_count.load(), 10);
  19452. }
  19453. // Test: Last-Event-ID sent on reconnect
  19454. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19455. std::atomic<int> connection_count{0};
  19456. std::vector<std::string> received_last_event_ids;
  19457. std::mutex id_mutex;
  19458. // Endpoint that checks Last-Event-ID header and sends event with ID
  19459. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19460. int conn = connection_count.fetch_add(1);
  19461. // Capture the Last-Event-ID header from each connection
  19462. {
  19463. std::lock_guard<std::mutex> lock(id_mutex);
  19464. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19465. }
  19466. res.set_chunked_content_provider(
  19467. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19468. if (offset == 0) {
  19469. std::string event =
  19470. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19471. sink.write(event.data(), event.size());
  19472. }
  19473. return false;
  19474. });
  19475. });
  19476. Client client("localhost", get_port());
  19477. sse::SSEClient sse(client, "/reconnect-with-id");
  19478. sse.set_reconnect_interval(100);
  19479. sse.set_max_reconnect_attempts(3);
  19480. sse.start_async();
  19481. // Wait for at least 2 connections
  19482. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19483. sse.stop();
  19484. // Verify behavior
  19485. std::lock_guard<std::mutex> lock(id_mutex);
  19486. EXPECT_GE(received_last_event_ids.size(), 2u);
  19487. // First connection should have no Last-Event-ID
  19488. if (!received_last_event_ids.empty()) {
  19489. EXPECT_EQ(received_last_event_ids[0], "");
  19490. }
  19491. // Second connection should have Last-Event-ID from first connection
  19492. if (received_last_event_ids.size() >= 2) {
  19493. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19494. }
  19495. }
  19496. // Test: set_headers updates headers used on reconnect
  19497. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19498. std::vector<std::string> received_tokens;
  19499. std::mutex token_mutex;
  19500. // Endpoint that captures Authorization header
  19501. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19502. {
  19503. std::lock_guard<std::mutex> lock(token_mutex);
  19504. received_tokens.push_back(req.get_header_value("Authorization"));
  19505. }
  19506. res.set_chunked_content_provider(
  19507. "text/event-stream", [](size_t offset, DataSink &sink) {
  19508. if (offset == 0) {
  19509. std::string event = "data: hello\n\n";
  19510. sink.write(event.data(), event.size());
  19511. }
  19512. return false; // Close connection to trigger reconnect
  19513. });
  19514. });
  19515. Client client("localhost", get_port());
  19516. Headers headers = {{"Authorization", "Bearer old-token"}};
  19517. sse::SSEClient sse(client, "/auth-check", headers);
  19518. // Update headers on each successful connection
  19519. sse.on_open(
  19520. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19521. sse.set_reconnect_interval(100);
  19522. sse.set_max_reconnect_attempts(3);
  19523. sse.start_async();
  19524. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19525. sse.stop();
  19526. std::lock_guard<std::mutex> lock(token_mutex);
  19527. ASSERT_GE(received_tokens.size(), 2u);
  19528. // First connection uses original header
  19529. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19530. // Second connection uses updated header from set_headers
  19531. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  19532. }
  19533. // Test: 401 allows reconnection (so on_error can refresh headers)
  19534. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  19535. std::atomic<int> connection_count{0};
  19536. // Endpoint: returns 401 on first attempt, 200 on second
  19537. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  19538. int conn = connection_count.fetch_add(1);
  19539. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19540. res.status = StatusCode::Unauthorized_401;
  19541. res.set_content("Unauthorized", "text/plain");
  19542. return;
  19543. }
  19544. res.set_chunked_content_provider(
  19545. "text/event-stream", [](size_t offset, DataSink &sink) {
  19546. if (offset == 0) {
  19547. std::string event = "data: authenticated\n\n";
  19548. sink.write(event.data(), event.size());
  19549. }
  19550. return false;
  19551. });
  19552. });
  19553. Client client("localhost", get_port());
  19554. Headers headers = {{"Authorization", "Bearer expired"}};
  19555. sse::SSEClient sse(client, "/auth-retry", headers);
  19556. std::atomic<bool> message_received{false};
  19557. // Refresh token on error
  19558. sse.on_error(
  19559. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19560. sse.on_message([&](const sse::SSEMessage &msg) {
  19561. if (msg.data == "authenticated") { message_received.store(true); }
  19562. });
  19563. sse.set_reconnect_interval(100);
  19564. sse.set_max_reconnect_attempts(3);
  19565. sse.start_async();
  19566. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19567. sse.stop();
  19568. // Should have reconnected after 401 and succeeded with new token
  19569. EXPECT_GE(connection_count.load(), 2);
  19570. EXPECT_TRUE(message_received.load());
  19571. }
  19572. TEST(Issue2318Test, EmptyHostString) {
  19573. {
  19574. httplib::Client cli_empty("", PORT);
  19575. auto res = cli_empty.Get("/");
  19576. ASSERT_FALSE(res);
  19577. EXPECT_EQ(httplib::Error::Connection, res.error());
  19578. }
  19579. {
  19580. httplib::Client cli(" ", PORT);
  19581. auto res = cli.Get("/");
  19582. ASSERT_FALSE(res);
  19583. EXPECT_EQ(httplib::Error::Connection, res.error());
  19584. }
  19585. }
  19586. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19587. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19588. Server svr;
  19589. // Set a small payload limit (1KB)
  19590. svr.set_payload_max_length(1024);
  19591. svr.Post("/test", [&](const Request &req, Response &res) {
  19592. res.set_content("Body size: " + std::to_string(req.body.size()),
  19593. "text/plain");
  19594. });
  19595. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19596. auto se = detail::scope_exit([&] {
  19597. svr.stop();
  19598. listen_thread.join();
  19599. });
  19600. svr.wait_until_ready();
  19601. // Create data that compresses well but exceeds limit when decompressed
  19602. // 8KB of repeated null bytes compresses to a very small size
  19603. std::string original_data(8 * 1024, '\0');
  19604. // Compress the data using gzip
  19605. std::string compressed_data;
  19606. detail::gzip_compressor compressor;
  19607. compressor.compress(original_data.data(), original_data.size(), true,
  19608. [&](const char *data, size_t size) {
  19609. compressed_data.append(data, size);
  19610. return true;
  19611. });
  19612. // Verify compression worked (compressed should be much smaller)
  19613. ASSERT_LT(compressed_data.size(), original_data.size());
  19614. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19615. // Send compressed data with Content-Encoding: gzip
  19616. Client cli(HOST, PORT);
  19617. Headers headers = {{"Content-Encoding", "gzip"}};
  19618. auto res =
  19619. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19620. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19622. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19623. }
  19624. #endif
  19625. // ============================================================================
  19626. // OpenSSL-Specific Tests
  19627. // ============================================================================
  19628. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19629. X509 *readCertificate(const std::string &strFileName) {
  19630. std::ifstream inStream(strFileName);
  19631. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19632. std::istreambuf_iterator<char>());
  19633. if (strCertPEM.empty()) return (nullptr);
  19634. BIO *pbCert = BIO_new(BIO_s_mem());
  19635. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19636. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19637. BIO_free(pbCert);
  19638. return (pCert);
  19639. }
  19640. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19641. std::ifstream inStream(strFileName);
  19642. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19643. std::istreambuf_iterator<char>());
  19644. if (strPrivateKeyPEM.empty()) return (nullptr);
  19645. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19646. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19647. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19648. BIO_free(pbPrivKey);
  19649. return (pPrivateKey);
  19650. }
  19651. TEST(BindServerTest, UpdateCerts) {
  19652. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19653. int port = svr.bind_to_any_port("0.0.0.0");
  19654. ASSERT_TRUE(svr.is_valid());
  19655. ASSERT_TRUE(port > 0);
  19656. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19657. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19658. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19659. ASSERT_TRUE(cert != nullptr);
  19660. ASSERT_TRUE(ca_cert != nullptr);
  19661. ASSERT_TRUE(key != nullptr);
  19662. X509_STORE *cert_store = X509_STORE_new();
  19663. X509_STORE_add_cert(cert_store, ca_cert);
  19664. // svr.update_certs(cert, key, cert_store); // deprecated
  19665. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19666. CLIENT_CA_CERT_FILE);
  19667. ASSERT_TRUE(svr.is_valid());
  19668. svr.stop();
  19669. X509_STORE_free(cert_store);
  19670. X509_free(cert);
  19671. X509_free(ca_cert);
  19672. EVP_PKEY_free(key);
  19673. }
  19674. // Test that update_certs() updates client CA list correctly
  19675. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19676. // Start with file-based constructor
  19677. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19678. ASSERT_TRUE(svr.is_valid());
  19679. // Initially no client CA list should be set
  19680. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19681. ASSERT_TRUE(ssl_ctx != nullptr);
  19682. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19683. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19684. EXPECT_EQ(0, count_before);
  19685. // Now update with client CA (PEM string)
  19686. std::string cert_pem, key_pem, ca_pem;
  19687. read_file(SERVER_CERT_FILE, cert_pem);
  19688. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19689. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19690. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19691. ASSERT_TRUE(svr.is_valid());
  19692. // Now client CA list should be set
  19693. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19694. ASSERT_TRUE(ca_list_after != nullptr);
  19695. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19696. }
  19697. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19698. // Test that the file-path SSLServer constructor properly sets the client CA
  19699. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19700. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19701. ASSERT_TRUE(svr.is_valid());
  19702. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19703. ASSERT_TRUE(ssl_ctx != nullptr);
  19704. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19705. ASSERT_TRUE(ca_list != nullptr);
  19706. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19707. }
  19708. #endif
  19709. // ============================================================================
  19710. // MbedTLS-Specific Tests
  19711. // ============================================================================
  19712. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19713. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19714. using namespace httplib::tls;
  19715. // Track if callback was invoked
  19716. bool callback_invoked = false;
  19717. // The callback receives void* ctx which is actually MbedTlsContext*
  19718. // We can access the mbedtls_ssl_config via the context
  19719. auto setup_callback = [&callback_invoked](void *ctx) {
  19720. callback_invoked = true;
  19721. // Cast to MbedTlsContext* to access the ssl config
  19722. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19723. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19724. // Use static variables to hold certificate data (simplified for test)
  19725. static mbedtls_x509_crt own_cert;
  19726. static mbedtls_pk_context own_key;
  19727. static mbedtls_x509_crt ca_chain;
  19728. static bool initialized = false;
  19729. if (!initialized) {
  19730. mbedtls_x509_crt_init(&own_cert);
  19731. mbedtls_pk_init(&own_key);
  19732. mbedtls_x509_crt_init(&ca_chain);
  19733. // Load server certificate
  19734. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19735. return false;
  19736. }
  19737. // Load server private key.
  19738. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19739. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19740. #if MBEDTLS_VERSION_MAJOR == 3
  19741. ,
  19742. mbedtls_ctr_drbg_random, nullptr
  19743. #endif
  19744. ) != 0) {
  19745. return false;
  19746. }
  19747. // Load CA chain for client verification
  19748. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19749. return false;
  19750. }
  19751. initialized = true;
  19752. }
  19753. // Configure the SSL config
  19754. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19755. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19756. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19757. // Set minimum TLS version using mbedTLS native API
  19758. #if MBEDTLS_VERSION_MAJOR >= 3
  19759. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19760. #else
  19761. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19762. MBEDTLS_SSL_MINOR_VERSION_3);
  19763. #endif
  19764. return true;
  19765. };
  19766. SSLServer svr(setup_callback);
  19767. ASSERT_TRUE(svr.is_valid());
  19768. ASSERT_TRUE(callback_invoked);
  19769. svr.Get("/test", [&](const Request &req, Response &res) {
  19770. res.set_content("test", "text/plain");
  19771. auto cert = req.peer_cert();
  19772. ASSERT_TRUE(static_cast<bool>(cert));
  19773. auto common_name = cert.subject_cn();
  19774. EXPECT_EQ("Common Name", common_name);
  19775. });
  19776. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19777. auto se = detail::scope_exit([&] {
  19778. svr.stop();
  19779. t.join();
  19780. ASSERT_FALSE(svr.is_running());
  19781. });
  19782. svr.wait_until_ready();
  19783. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19784. cli.enable_server_certificate_verification(false);
  19785. cli.set_connection_timeout(30);
  19786. auto res = cli.Get("/test");
  19787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19788. ASSERT_EQ(StatusCode::OK_200, res->status);
  19789. }
  19790. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19791. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19792. // keep-alive SSL session, which reads through that config in
  19793. // mbedtls_ssl_close_notify.
  19794. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19795. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19796. ASSERT_TRUE(svr.is_valid());
  19797. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19798. res.set_content("test", "text/plain");
  19799. });
  19800. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19801. auto se = detail::scope_exit([&] {
  19802. svr.stop();
  19803. t.join();
  19804. ASSERT_FALSE(svr.is_running());
  19805. });
  19806. svr.wait_until_ready();
  19807. {
  19808. SSLClient cli(HOST, PORT);
  19809. cli.enable_server_certificate_verification(false);
  19810. cli.set_keep_alive(true);
  19811. auto res = cli.Get("/test");
  19812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19813. ASSERT_EQ(StatusCode::OK_200, res->status);
  19814. // cli is destructed here with the keep-alive SSL session still open.
  19815. }
  19816. }
  19817. #endif
  19818. // WebSocket Tests
  19819. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19820. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19821. // defining the meaning of these bits has been negotiated.
  19822. auto make_frame = [](uint8_t first_byte) {
  19823. std::string frame;
  19824. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19825. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19826. frame += "Hello";
  19827. return frame;
  19828. };
  19829. // RSV1 set (0x40)
  19830. {
  19831. detail::BufferStream strm;
  19832. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19833. ws::Opcode opcode;
  19834. std::string payload;
  19835. bool fin;
  19836. EXPECT_EQ(
  19837. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19838. ws::impl::FrameRead::Fail);
  19839. }
  19840. // RSV2 set (0x20)
  19841. {
  19842. detail::BufferStream strm;
  19843. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19844. ws::Opcode opcode;
  19845. std::string payload;
  19846. bool fin;
  19847. EXPECT_EQ(
  19848. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19849. ws::impl::FrameRead::Fail);
  19850. }
  19851. // RSV3 set (0x10)
  19852. {
  19853. detail::BufferStream strm;
  19854. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19855. ws::Opcode opcode;
  19856. std::string payload;
  19857. bool fin;
  19858. EXPECT_EQ(
  19859. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19860. ws::impl::FrameRead::Fail);
  19861. }
  19862. // No RSV bits set - should succeed
  19863. {
  19864. detail::BufferStream strm;
  19865. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19866. ws::Opcode opcode;
  19867. std::string payload;
  19868. bool fin;
  19869. EXPECT_EQ(
  19870. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19871. ws::impl::FrameRead::Ok);
  19872. EXPECT_EQ(ws::Opcode::Text, opcode);
  19873. EXPECT_EQ("Hello", payload);
  19874. EXPECT_TRUE(fin);
  19875. }
  19876. }
  19877. TEST(WebSocketTest, ControlFrameValidation) {
  19878. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19879. // payload length <= 125.
  19880. // Ping with FIN=0 - must be rejected
  19881. {
  19882. detail::BufferStream strm;
  19883. std::string frame;
  19884. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19885. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19886. strm.write(frame.data(), frame.size());
  19887. ws::Opcode opcode;
  19888. std::string payload;
  19889. bool fin;
  19890. EXPECT_EQ(
  19891. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19892. ws::impl::FrameRead::Fail);
  19893. }
  19894. // Close with FIN=0 - must be rejected
  19895. {
  19896. detail::BufferStream strm;
  19897. std::string frame;
  19898. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19899. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19900. strm.write(frame.data(), frame.size());
  19901. ws::Opcode opcode;
  19902. std::string payload;
  19903. bool fin;
  19904. EXPECT_EQ(
  19905. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19906. ws::impl::FrameRead::Fail);
  19907. }
  19908. // Ping with payload_len=126 (extended length) - must be rejected
  19909. {
  19910. detail::BufferStream strm;
  19911. std::string frame;
  19912. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19913. frame += static_cast<char>(126); // payload_len=126 (>125)
  19914. frame += static_cast<char>(0x00); // extended length high byte
  19915. frame += static_cast<char>(126); // extended length low byte
  19916. frame += std::string(126, 'x');
  19917. strm.write(frame.data(), frame.size());
  19918. ws::Opcode opcode;
  19919. std::string payload;
  19920. bool fin;
  19921. EXPECT_EQ(
  19922. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19923. ws::impl::FrameRead::Fail);
  19924. }
  19925. // Ping with FIN=1 and payload_len=125 - should succeed
  19926. {
  19927. detail::BufferStream strm;
  19928. std::string frame;
  19929. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19930. frame += static_cast<char>(125); // payload_len=125
  19931. frame += std::string(125, 'x');
  19932. strm.write(frame.data(), frame.size());
  19933. ws::Opcode opcode;
  19934. std::string payload;
  19935. bool fin;
  19936. EXPECT_EQ(
  19937. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19938. ws::impl::FrameRead::Ok);
  19939. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19940. EXPECT_EQ(125u, payload.size());
  19941. EXPECT_TRUE(fin);
  19942. }
  19943. }
  19944. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19945. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19946. // length MUST be 0.
  19947. // MSB set - must be rejected
  19948. {
  19949. detail::BufferStream strm;
  19950. std::string frame;
  19951. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19952. frame += static_cast<char>(127); // 64-bit extended length
  19953. frame += static_cast<char>(0x80); // MSB set (invalid)
  19954. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19955. strm.write(frame.data(), frame.size());
  19956. ws::Opcode opcode;
  19957. std::string payload;
  19958. bool fin;
  19959. EXPECT_EQ(
  19960. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19961. ws::impl::FrameRead::Fail);
  19962. }
  19963. // MSB clear - should pass length parsing (will be rejected by max_len,
  19964. // but that's a different check; use a small length to verify)
  19965. {
  19966. detail::BufferStream strm;
  19967. std::string frame;
  19968. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19969. frame += static_cast<char>(127); // 64-bit extended length
  19970. frame += std::string(7, '\0'); // high bytes = 0
  19971. frame += static_cast<char>(0x03); // length = 3
  19972. frame += "abc";
  19973. strm.write(frame.data(), frame.size());
  19974. ws::Opcode opcode;
  19975. std::string payload;
  19976. bool fin;
  19977. EXPECT_EQ(
  19978. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19979. ws::impl::FrameRead::Ok);
  19980. EXPECT_EQ(ws::Opcode::Text, opcode);
  19981. EXPECT_EQ("abc", payload);
  19982. }
  19983. }
  19984. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19985. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19986. // Valid UTF-8
  19987. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19988. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19989. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19990. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19991. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19992. // Invalid UTF-8
  19993. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19994. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19995. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19996. EXPECT_FALSE(
  19997. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19998. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19999. }
  20000. TEST(WebSocketTest, ConnectAndDisconnect) {
  20001. Server svr;
  20002. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20003. std::string msg;
  20004. while (ws.read(msg)) {}
  20005. });
  20006. auto port = svr.bind_to_any_port(HOST);
  20007. std::thread t([&]() { svr.listen_after_bind(); });
  20008. svr.wait_until_ready();
  20009. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20010. auto res = client.connect();
  20011. ASSERT_TRUE(res);
  20012. EXPECT_EQ(Error::Success, res.error());
  20013. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20014. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20015. EXPECT_TRUE(client.is_open());
  20016. client.close();
  20017. EXPECT_FALSE(client.is_open());
  20018. svr.stop();
  20019. t.join();
  20020. }
  20021. TEST(WebSocketTest, ValidURL) {
  20022. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20023. EXPECT_TRUE(ws1.is_valid());
  20024. ws::WebSocketClient ws2("ws://example.com/path");
  20025. EXPECT_TRUE(ws2.is_valid());
  20026. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20027. EXPECT_TRUE(ws3.is_valid());
  20028. #ifdef CPPHTTPLIB_SSL_ENABLED
  20029. ws::WebSocketClient wss1("wss://example.com/path");
  20030. EXPECT_TRUE(wss1.is_valid());
  20031. ws::WebSocketClient wss2("wss://example.com:443/path");
  20032. EXPECT_TRUE(wss2.is_valid());
  20033. #endif
  20034. }
  20035. TEST(WebSocketTest, InvalidURL) {
  20036. // No scheme
  20037. ws::WebSocketClient ws1("localhost:8080/path");
  20038. EXPECT_FALSE(ws1.is_valid());
  20039. // No path
  20040. ws::WebSocketClient ws2("ws://localhost:8080");
  20041. EXPECT_FALSE(ws2.is_valid());
  20042. // Empty string
  20043. ws::WebSocketClient ws3("");
  20044. EXPECT_FALSE(ws3.is_valid());
  20045. // Missing host
  20046. ws::WebSocketClient ws4("ws://:8080/path");
  20047. EXPECT_FALSE(ws4.is_valid());
  20048. // Port number overflow — should not crash
  20049. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20050. EXPECT_FALSE(ws5.is_valid());
  20051. // Port out of range
  20052. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20053. EXPECT_FALSE(ws6.is_valid());
  20054. }
  20055. TEST(WebSocketTest, UnsupportedScheme) {
  20056. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20057. ws::WebSocketClient ws1("http://localhost:8080/path");
  20058. EXPECT_FALSE(ws1.is_valid());
  20059. ws::WebSocketClient ws2("https://localhost:8080/path");
  20060. EXPECT_FALSE(ws2.is_valid());
  20061. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20062. EXPECT_FALSE(ws3.is_valid());
  20063. #else
  20064. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20065. std::invalid_argument);
  20066. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20067. std::invalid_argument);
  20068. #endif
  20069. }
  20070. TEST(WebSocketTest, ConnectWhenInvalid) {
  20071. ws::WebSocketClient ws("not a valid url");
  20072. EXPECT_FALSE(ws.is_valid());
  20073. auto res = ws.connect();
  20074. EXPECT_FALSE(res);
  20075. EXPECT_EQ(Error::Connection, res.error());
  20076. EXPECT_EQ(-1, res.status());
  20077. }
  20078. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20079. // Grab a port that is free, then close it again so nothing listens there
  20080. Server svr;
  20081. auto port = svr.bind_to_any_port(HOST);
  20082. svr.stop();
  20083. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20084. auto res = client.connect();
  20085. ASSERT_FALSE(res);
  20086. EXPECT_EQ(Error::Connection, res.error());
  20087. EXPECT_EQ(-1, res.status());
  20088. }
  20089. TEST(WebSocketTest, DefaultPort) {
  20090. ws::WebSocketClient ws1("ws://example.com/path");
  20091. EXPECT_TRUE(ws1.is_valid());
  20092. // ws:// defaults to port 80 (verified by successful parse)
  20093. #ifdef CPPHTTPLIB_SSL_ENABLED
  20094. ws::WebSocketClient ws2("wss://example.com/path");
  20095. EXPECT_TRUE(ws2.is_valid());
  20096. // wss:// defaults to port 443 (verified by successful parse)
  20097. #endif
  20098. }
  20099. TEST(WebSocketTest, IPv6LiteralAddress) {
  20100. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20101. EXPECT_TRUE(ws1.is_valid());
  20102. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20103. EXPECT_TRUE(ws2.is_valid());
  20104. }
  20105. TEST(WebSocketTest, ComplexPath) {
  20106. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20107. EXPECT_TRUE(ws1.is_valid());
  20108. ws::WebSocketClient ws2("ws://localhost:8080/");
  20109. EXPECT_TRUE(ws2.is_valid());
  20110. }
  20111. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20112. Server svr;
  20113. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20114. std::string msg;
  20115. while (ws.read(msg)) {}
  20116. });
  20117. auto port = svr.bind_to_any_port(HOST);
  20118. std::thread t([&]() { svr.listen_after_bind(); });
  20119. svr.wait_until_ready();
  20120. auto another_host = "example.com";
  20121. auto wrong_ip = "192.0.2.1";
  20122. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20123. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20124. ASSERT_TRUE(client.connect());
  20125. EXPECT_TRUE(client.is_open());
  20126. client.close();
  20127. svr.stop();
  20128. t.join();
  20129. }
  20130. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20131. Server svr;
  20132. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20133. std::string msg;
  20134. while (ws.read(msg)) {}
  20135. });
  20136. auto port = svr.bind_to_any_port(HOST);
  20137. std::thread t([&]() { svr.listen_after_bind(); });
  20138. svr.wait_until_ready();
  20139. auto wrong_ip = "192.0.2.1";
  20140. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20141. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20142. client.set_connection_timeout(1);
  20143. client.set_read_timeout(1);
  20144. client.set_write_timeout(1);
  20145. EXPECT_FALSE(client.connect());
  20146. EXPECT_FALSE(client.is_open());
  20147. svr.stop();
  20148. t.join();
  20149. }
  20150. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20151. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20152. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20153. // (RFC 6761) is only a map key and the Host header value.
  20154. auto host = "target.invalid";
  20155. Server svr;
  20156. std::string received_host;
  20157. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20158. received_host = req.get_header_value("Host");
  20159. std::string msg;
  20160. while (ws.read(msg)) {}
  20161. });
  20162. auto port = svr.bind_to_any_port(HOST);
  20163. std::thread t([&]() { svr.listen_after_bind(); });
  20164. // ASSERT_* below returns from the test body, which would leave t joinable
  20165. // and make ~thread call std::terminate.
  20166. auto se = detail::scope_exit([&] {
  20167. svr.stop();
  20168. if (t.joinable()) { t.join(); }
  20169. });
  20170. svr.wait_until_ready();
  20171. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20172. std::to_string(port) + "/ws");
  20173. client.set_hostname_addr_map({{host, HOST}});
  20174. ASSERT_TRUE(client.connect());
  20175. EXPECT_TRUE(client.is_open());
  20176. client.close();
  20177. svr.stop();
  20178. t.join();
  20179. // The mapping only redirects the connection; the identity stays host_.
  20180. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20181. }
  20182. class WebSocketIntegrationTest : public ::testing::Test {
  20183. protected:
  20184. void SetUp() override {
  20185. server_ = httplib::detail::make_unique<Server>();
  20186. setup_server();
  20187. start_server();
  20188. }
  20189. void TearDown() override {
  20190. server_->stop();
  20191. if (server_thread_.joinable()) { server_thread_.join(); }
  20192. }
  20193. void setup_server() {
  20194. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20195. std::string msg;
  20196. ws::ReadResult ret;
  20197. while ((ret = ws.read(msg))) {
  20198. if (ret == ws::Binary) {
  20199. ws.send(msg.data(), msg.size());
  20200. } else {
  20201. ws.send(msg);
  20202. }
  20203. }
  20204. });
  20205. server_->WebSocket("/ws-echo-string",
  20206. [](const Request &, ws::WebSocket &ws) {
  20207. std::string msg;
  20208. while (ws.read(msg)) {
  20209. ws.send("echo: " + msg);
  20210. }
  20211. });
  20212. server_->WebSocket(
  20213. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20214. // Echo back request metadata
  20215. ws.send("path:" + req.path);
  20216. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20217. std::string msg;
  20218. while (ws.read(msg)) {}
  20219. });
  20220. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20221. std::string msg;
  20222. ws.read(msg); // wait for a message
  20223. ws.close();
  20224. });
  20225. server_->WebSocket("/ws-close-status",
  20226. [](const Request &, ws::WebSocket &ws) {
  20227. std::string msg;
  20228. ws.read(msg); // wait for a message
  20229. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20230. });
  20231. server_->WebSocket(
  20232. "/ws-subprotocol",
  20233. [](const Request &, ws::WebSocket &ws) {
  20234. std::string msg;
  20235. while (ws.read(msg)) {
  20236. ws.send(msg);
  20237. }
  20238. },
  20239. [](const std::vector<std::string> &protocols) -> std::string {
  20240. for (const auto &p : protocols) {
  20241. if (p == "graphql-ws") { return p; }
  20242. }
  20243. return "";
  20244. });
  20245. server_->WebSocket(
  20246. "/ws-subprotocol-unoffered",
  20247. [](const Request &, ws::WebSocket &ws) {
  20248. std::string msg;
  20249. while (ws.read(msg)) {
  20250. ws.send(msg);
  20251. }
  20252. },
  20253. [](const std::vector<std::string> &) -> std::string {
  20254. return "admin";
  20255. });
  20256. }
  20257. void start_server() {
  20258. port_ = server_->bind_to_any_port(HOST);
  20259. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20260. server_->wait_until_ready();
  20261. }
  20262. std::unique_ptr<Server> server_;
  20263. std::thread server_thread_;
  20264. int port_ = 0;
  20265. };
  20266. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20267. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20268. "/ws-echo");
  20269. ASSERT_TRUE(client.connect());
  20270. ASSERT_TRUE(client.is_open());
  20271. ASSERT_TRUE(client.send("Hello WebSocket"));
  20272. std::string msg;
  20273. EXPECT_EQ(ws::Text, client.read(msg));
  20274. EXPECT_EQ("Hello WebSocket", msg);
  20275. client.close();
  20276. }
  20277. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20278. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20279. "/ws-echo");
  20280. ASSERT_TRUE(client.connect());
  20281. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20282. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20283. std::string msg;
  20284. EXPECT_EQ(ws::Binary, client.read(msg));
  20285. EXPECT_EQ(binary_data, msg);
  20286. client.close();
  20287. }
  20288. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20289. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20290. "/ws-echo");
  20291. ASSERT_TRUE(client.connect());
  20292. for (int i = 0; i < 10; i++) {
  20293. auto text = "message " + std::to_string(i);
  20294. ASSERT_TRUE(client.send(text));
  20295. std::string msg;
  20296. ASSERT_TRUE(client.read(msg));
  20297. EXPECT_EQ(text, msg);
  20298. }
  20299. client.close();
  20300. }
  20301. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20302. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20303. "/ws-close");
  20304. ASSERT_TRUE(client.connect());
  20305. // Send a message to trigger the server to close
  20306. ASSERT_TRUE(client.send("trigger close"));
  20307. // The server will close, so read should return false
  20308. std::string msg;
  20309. EXPECT_FALSE(client.read(msg));
  20310. EXPECT_FALSE(client.is_open());
  20311. }
  20312. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20313. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20314. "/ws-echo");
  20315. ASSERT_TRUE(client.connect());
  20316. // 128KB message
  20317. std::string large_data(128 * 1024, 'X');
  20318. ASSERT_TRUE(client.send(large_data));
  20319. std::string msg;
  20320. ASSERT_TRUE(client.read(msg));
  20321. EXPECT_EQ(large_data, msg);
  20322. client.close();
  20323. }
  20324. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20325. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20326. "/ws-echo");
  20327. ASSERT_TRUE(client.connect());
  20328. const int num_threads = 4;
  20329. std::vector<std::thread> threads;
  20330. std::atomic<int> send_count{0};
  20331. for (int t = 0; t < num_threads; t++) {
  20332. threads.emplace_back([&client, &send_count, t]() {
  20333. for (int i = 0; i < 5; i++) {
  20334. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20335. if (client.send(text)) { send_count++; }
  20336. }
  20337. });
  20338. }
  20339. for (auto &th : threads) {
  20340. th.join();
  20341. }
  20342. int received = 0;
  20343. std::string msg;
  20344. while (received < send_count.load()) {
  20345. if (!client.read(msg)) { break; }
  20346. received++;
  20347. }
  20348. EXPECT_EQ(send_count.load(), received);
  20349. client.close();
  20350. }
  20351. TEST_F(WebSocketIntegrationTest, ReadString) {
  20352. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20353. "/ws-echo-string");
  20354. ASSERT_TRUE(client.connect());
  20355. ASSERT_TRUE(client.send("hello"));
  20356. std::string msg;
  20357. ASSERT_TRUE(client.read(msg));
  20358. EXPECT_EQ("echo: hello", msg);
  20359. ASSERT_TRUE(client.send("world"));
  20360. ASSERT_TRUE(client.read(msg));
  20361. EXPECT_EQ("echo: world", msg);
  20362. client.close();
  20363. }
  20364. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20365. Headers headers = {{"X-Test-Header", "test-value"}};
  20366. ws::WebSocketClient client(
  20367. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20368. ASSERT_TRUE(client.connect());
  20369. std::string msg;
  20370. ASSERT_TRUE(client.read(msg));
  20371. EXPECT_EQ("path:/ws-request-info", msg);
  20372. ASSERT_TRUE(client.read(msg));
  20373. EXPECT_EQ("header:test-value", msg);
  20374. client.close();
  20375. }
  20376. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20377. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20378. "/ws-echo");
  20379. client.set_read_timeout(1, 0); // 1 second
  20380. ASSERT_TRUE(client.connect());
  20381. // Don't send anything — server echo handler waits for a message, so read()
  20382. // should time out. The connection survives it: nothing was consumed.
  20383. std::string msg;
  20384. EXPECT_EQ(client.read(msg), ws::Timeout);
  20385. EXPECT_TRUE(client.is_open());
  20386. // And it is still usable afterwards.
  20387. EXPECT_TRUE(client.send("after timeout"));
  20388. EXPECT_EQ(client.read(msg), ws::Text);
  20389. EXPECT_EQ(msg, "after timeout");
  20390. }
  20391. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20392. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20393. "/ws-echo");
  20394. client.set_read_timeout(1, 0);
  20395. ASSERT_TRUE(client.connect());
  20396. ASSERT_TRUE(client.send("first"));
  20397. std::string msg;
  20398. ASSERT_EQ(client.read(msg), ws::Text);
  20399. ASSERT_EQ(msg, "first");
  20400. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20401. // not be used with a read timeout: it would reprocess the previous message.
  20402. EXPECT_EQ(client.read(msg), ws::Timeout);
  20403. EXPECT_EQ(msg, "first");
  20404. }
  20405. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20406. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20407. "/ws-echo");
  20408. ASSERT_TRUE(client.connect());
  20409. // Setting it once the connection is open reaches the live stream, not just
  20410. // the seed for the next connect().
  20411. client.set_read_timeout(1, 0);
  20412. std::string msg;
  20413. EXPECT_EQ(client.read(msg), ws::Timeout);
  20414. EXPECT_TRUE(client.is_open());
  20415. }
  20416. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20417. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20418. "/ws-echo");
  20419. client.set_read_timeout(5, 0);
  20420. ASSERT_TRUE(client.connect());
  20421. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20422. // The server should reject it and close the connection.
  20423. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20424. client.send(oversized);
  20425. // The server's read() should have failed due to payload limit,
  20426. // so our read() should return false (connection closed).
  20427. std::string msg;
  20428. EXPECT_FALSE(client.read(msg));
  20429. }
  20430. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20431. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20432. "/ws-echo");
  20433. client.set_read_timeout(10, 0);
  20434. ASSERT_TRUE(client.connect());
  20435. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20436. // This should succeed.
  20437. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20438. ASSERT_TRUE(client.send(at_limit));
  20439. std::string msg;
  20440. ASSERT_TRUE(client.read(msg));
  20441. EXPECT_EQ(at_limit.size(), msg.size());
  20442. client.close();
  20443. }
  20444. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20445. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20446. "/nonexistent");
  20447. auto res = client.connect();
  20448. EXPECT_FALSE(res);
  20449. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20450. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20451. EXPECT_FALSE(client.is_open());
  20452. }
  20453. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20454. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20455. "/ws-echo");
  20456. ASSERT_TRUE(client.connect());
  20457. ASSERT_TRUE(client.send(""));
  20458. std::string msg;
  20459. EXPECT_EQ(ws::Text, client.read(msg));
  20460. EXPECT_EQ("", msg);
  20461. client.close();
  20462. }
  20463. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20464. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20465. "/ws-echo");
  20466. // First connection
  20467. ASSERT_TRUE(client.connect());
  20468. ASSERT_TRUE(client.send("first"));
  20469. std::string msg;
  20470. ASSERT_TRUE(client.read(msg));
  20471. EXPECT_EQ("first", msg);
  20472. client.close();
  20473. EXPECT_FALSE(client.is_open());
  20474. // Reconnect using the same client object
  20475. ASSERT_TRUE(client.connect());
  20476. ASSERT_TRUE(client.is_open());
  20477. ASSERT_TRUE(client.send("second"));
  20478. ASSERT_TRUE(client.read(msg));
  20479. EXPECT_EQ("second", msg);
  20480. client.close();
  20481. }
  20482. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20483. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20484. "/ws-close-status");
  20485. ASSERT_TRUE(client.connect());
  20486. // Trigger the server to close with GoingAway status
  20487. ASSERT_TRUE(client.send("trigger"));
  20488. // read() should return false after receiving the close frame
  20489. std::string msg;
  20490. EXPECT_FALSE(client.read(msg));
  20491. EXPECT_FALSE(client.is_open());
  20492. }
  20493. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20494. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20495. "/ws-echo");
  20496. ASSERT_TRUE(client.connect());
  20497. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20498. EXPECT_FALSE(client.is_open());
  20499. }
  20500. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20501. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20502. ws::WebSocketClient client(
  20503. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20504. ASSERT_TRUE(client.connect());
  20505. // Server should have selected graphql-ws
  20506. EXPECT_EQ("graphql-ws", client.subprotocol());
  20507. client.close();
  20508. }
  20509. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  20510. Headers headers;
  20511. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  20512. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  20513. ws::WebSocketClient client(
  20514. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20515. ASSERT_TRUE(client.connect());
  20516. // The offer on the second field line counts too, so graphql-ws is selected
  20517. EXPECT_EQ("graphql-ws", client.subprotocol());
  20518. client.close();
  20519. }
  20520. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  20521. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20522. ws::WebSocketClient client(
  20523. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20524. ASSERT_TRUE(client.connect());
  20525. // Server should not have selected any subprotocol
  20526. EXPECT_TRUE(client.subprotocol().empty());
  20527. client.close();
  20528. }
  20529. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  20530. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  20531. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20532. "/ws-subprotocol-unoffered",
  20533. headers);
  20534. ASSERT_TRUE(client.connect());
  20535. EXPECT_TRUE(client.subprotocol().empty());
  20536. client.close();
  20537. }
  20538. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  20539. // Connect without requesting any subprotocol
  20540. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20541. "/ws-subprotocol");
  20542. ASSERT_TRUE(client.connect());
  20543. EXPECT_TRUE(client.subprotocol().empty());
  20544. client.close();
  20545. }
  20546. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  20547. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20548. "/ws-echo");
  20549. client.set_tcp_nodelay(true);
  20550. client.set_connection_timeout(3, 0);
  20551. bool socket_options_called = false;
  20552. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  20553. ASSERT_TRUE(client.connect());
  20554. ASSERT_TRUE(client.is_open());
  20555. EXPECT_TRUE(socket_options_called);
  20556. ASSERT_TRUE(client.send("hello"));
  20557. std::string msg;
  20558. auto result = client.read(msg);
  20559. EXPECT_EQ(result, ws::ReadResult::Text);
  20560. EXPECT_EQ(msg, "hello");
  20561. client.close();
  20562. }
  20563. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20564. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20565. "/ws-echo");
  20566. client.set_connection_timeout(std::chrono::seconds(3));
  20567. client.set_write_timeout(std::chrono::seconds(3));
  20568. // A sub-second remainder exercises the seconds/microseconds split.
  20569. client.set_read_timeout(std::chrono::milliseconds(1500));
  20570. ASSERT_TRUE(client.connect());
  20571. auto start = std::chrono::steady_clock::now();
  20572. std::string msg;
  20573. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20574. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20575. std::chrono::steady_clock::now() - start)
  20576. .count();
  20577. // Above 1s so that dropping the microseconds half of the split fails here.
  20578. // Ignoring the setter altogether would not reach this line at all: a client
  20579. // waits forever by default.
  20580. EXPECT_GE(elapsed, 1400);
  20581. EXPECT_LT(elapsed, 30000);
  20582. }
  20583. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20584. Server svr;
  20585. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20586. if (!req.has_header("Authorization")) {
  20587. res.status = StatusCode::Unauthorized_401;
  20588. res.set_content("Unauthorized", "text/plain");
  20589. return Server::HandlerResponse::Handled;
  20590. }
  20591. return Server::HandlerResponse::Unhandled;
  20592. });
  20593. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20594. std::string msg;
  20595. while (ws.read(msg)) {
  20596. ws.send(msg);
  20597. }
  20598. });
  20599. auto port = svr.bind_to_any_port("localhost");
  20600. std::thread t([&]() { svr.listen_after_bind(); });
  20601. svr.wait_until_ready();
  20602. // Without Authorization header - should be rejected before upgrade
  20603. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20604. EXPECT_FALSE(client1.connect());
  20605. // The rejection is framed like any other HTTP response
  20606. {
  20607. Client cli("localhost", port);
  20608. Headers headers = {{"Upgrade", "websocket"},
  20609. {"Connection", "Upgrade"},
  20610. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20611. {"Sec-WebSocket-Version", "13"}};
  20612. auto res = cli.Get("/ws", headers);
  20613. ASSERT_TRUE(res);
  20614. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20615. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20616. EXPECT_EQ("Unauthorized", res->body);
  20617. }
  20618. // With Authorization header - should succeed
  20619. Headers headers = {{"Authorization", "Bearer token123"}};
  20620. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20621. headers);
  20622. ASSERT_TRUE(client2.connect());
  20623. ASSERT_TRUE(client2.send("hello"));
  20624. std::string msg;
  20625. ASSERT_TRUE(client2.read(msg));
  20626. EXPECT_EQ("hello", msg);
  20627. client2.close();
  20628. svr.stop();
  20629. t.join();
  20630. }
  20631. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20632. Server svr;
  20633. std::atomic<int> pre_request_calls{0};
  20634. std::atomic<bool> route_matched{false};
  20635. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20636. pre_request_calls++;
  20637. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20638. if (req.get_header_value("Authorization") != "Bearer token123") {
  20639. res.status = StatusCode::Unauthorized_401;
  20640. res.set_content("Unauthorized", "text/plain");
  20641. return Server::HandlerResponse::Handled;
  20642. }
  20643. return Server::HandlerResponse::Unhandled;
  20644. });
  20645. std::atomic<bool> handler_called{false};
  20646. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20647. handler_called = true;
  20648. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20649. });
  20650. auto port = svr.bind_to_any_port("localhost");
  20651. std::thread t([&]() { svr.listen_after_bind(); });
  20652. svr.wait_until_ready();
  20653. // Without Authorization header - should be rejected before upgrade
  20654. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20655. "/ws/1");
  20656. EXPECT_FALSE(client1.connect());
  20657. EXPECT_FALSE(handler_called);
  20658. EXPECT_EQ(1, pre_request_calls);
  20659. EXPECT_TRUE(route_matched);
  20660. // The rejection is an ordinary HTTP response, not a protocol switch
  20661. {
  20662. Client cli("localhost", port);
  20663. Headers headers = {{"Upgrade", "websocket"},
  20664. {"Connection", "Upgrade"},
  20665. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20666. {"Sec-WebSocket-Version", "13"}};
  20667. auto res = cli.Get("/ws/1", headers);
  20668. ASSERT_TRUE(res);
  20669. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20670. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20671. EXPECT_EQ("Unauthorized", res->body);
  20672. }
  20673. EXPECT_FALSE(handler_called);
  20674. // With Authorization header - should succeed
  20675. Headers headers = {{"Authorization", "Bearer token123"}};
  20676. ws::WebSocketClient client2(
  20677. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20678. ASSERT_TRUE(client2.connect());
  20679. std::string msg;
  20680. ASSERT_TRUE(client2.read(msg));
  20681. EXPECT_EQ("/ws/:id 2", msg);
  20682. EXPECT_TRUE(handler_called);
  20683. client2.close();
  20684. svr.stop();
  20685. t.join();
  20686. }
  20687. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20688. Server svr;
  20689. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20690. // A read timeout is how a handler gets control back. Without it, a handler
  20691. // parked in read() can never write on the connection it is reading.
  20692. ws.set_read_timeout(std::chrono::milliseconds(100));
  20693. std::string msg;
  20694. while (ws.is_open()) {
  20695. auto r = ws.read(msg);
  20696. if (r == httplib::ws::Timeout) {
  20697. ws.send("tick");
  20698. continue;
  20699. }
  20700. if (r == httplib::ws::Fail) { break; }
  20701. ws.send(msg);
  20702. }
  20703. });
  20704. auto port = svr.bind_to_any_port("localhost");
  20705. std::thread t([&]() { svr.listen_after_bind(); });
  20706. svr.wait_until_ready();
  20707. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20708. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20709. ASSERT_TRUE(client.connect());
  20710. // The client sends nothing, so anything it receives came out of the
  20711. // handler's timeout path.
  20712. std::string msg;
  20713. ASSERT_EQ(client.read(msg), ws::Text);
  20714. EXPECT_EQ("tick", msg);
  20715. client.close();
  20716. svr.stop();
  20717. t.join();
  20718. }
  20719. // Stream::read may return fewer bytes than asked for. This is that contract at
  20720. // its worst -- one byte per call -- which is what a frame header straddling a
  20721. // read buffer's boundary looks like to the frame parser.
  20722. class WsByteAtATimeStream : public Stream {
  20723. public:
  20724. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20725. bool is_readable() const override { return true; }
  20726. bool wait_readable() const override { return true; }
  20727. bool wait_writable() const override { return true; }
  20728. ssize_t read(char *ptr, size_t size) override {
  20729. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20730. *ptr = data_[pos_++];
  20731. return 1;
  20732. }
  20733. ssize_t write(const char *, size_t size) override {
  20734. return static_cast<ssize_t>(size);
  20735. }
  20736. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20737. ip = "127.0.0.1";
  20738. port = 0;
  20739. }
  20740. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20741. ip = "127.0.0.1";
  20742. port = 0;
  20743. }
  20744. socket_t socket() const override { return INVALID_SOCKET; }
  20745. time_t duration() const override { return 0; }
  20746. private:
  20747. std::string data_;
  20748. size_t pos_ = 0;
  20749. };
  20750. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20751. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20752. // length and the mask key are all multi-byte fields here. Each used to be
  20753. // read with a single read() call, which fails as soon as one is split.
  20754. std::string body(200, 'x');
  20755. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20756. std::string frame;
  20757. frame += static_cast<char>(0x81); // FIN + Text
  20758. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20759. frame += static_cast<char>(body.size() >> 8);
  20760. frame += static_cast<char>(body.size() & 0xff);
  20761. for (size_t i = 0; i < 4; i++) {
  20762. frame += static_cast<char>(mask[i]);
  20763. }
  20764. for (size_t i = 0; i < body.size(); i++) {
  20765. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20766. }
  20767. WsByteAtATimeStream strm(frame);
  20768. ws::Opcode opcode;
  20769. std::string payload;
  20770. bool fin = false;
  20771. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20772. /*expect_masked=*/true, 1024),
  20773. ws::impl::FrameRead::Ok);
  20774. EXPECT_TRUE(fin);
  20775. EXPECT_EQ(opcode, ws::Opcode::Text);
  20776. EXPECT_EQ(payload, body);
  20777. }
  20778. TEST(WebSocketTest, QueryStringInHandshake) {
  20779. Server svr;
  20780. std::mutex mtx;
  20781. std::string received_target;
  20782. std::string received_token;
  20783. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20784. {
  20785. std::lock_guard<std::mutex> lock(mtx);
  20786. received_target = req.target;
  20787. if (req.has_param("token")) {
  20788. received_token = req.get_param_value("token");
  20789. }
  20790. }
  20791. std::string msg;
  20792. while (ws.read(msg)) {
  20793. ws.send(msg);
  20794. }
  20795. });
  20796. auto port = svr.bind_to_any_port("localhost");
  20797. std::thread t([&]() { svr.listen_after_bind(); });
  20798. svr.wait_until_ready();
  20799. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20800. "/ws?token=ABC&session=123");
  20801. ASSERT_TRUE(client.connect());
  20802. // Round-trip ensures the handler has run and captured the request.
  20803. ASSERT_TRUE(client.send("hello"));
  20804. std::string msg;
  20805. ASSERT_TRUE(client.read(msg));
  20806. EXPECT_EQ("hello", msg);
  20807. client.close();
  20808. {
  20809. std::lock_guard<std::mutex> lock(mtx);
  20810. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20811. EXPECT_EQ("ABC", received_token);
  20812. }
  20813. svr.stop();
  20814. t.join();
  20815. }
  20816. // Run a handshake against a throwaway server and hand the request the server
  20817. // received back to the caller, so tests can assert on the headers the client
  20818. // actually put on the wire.
  20819. static void capture_websocket_handshake_request(
  20820. const Headers &client_headers,
  20821. std::function<void(const Request &, int port)> verify) {
  20822. Server svr;
  20823. std::mutex mtx;
  20824. Request received;
  20825. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20826. {
  20827. std::lock_guard<std::mutex> lock(mtx);
  20828. received = req;
  20829. }
  20830. std::string msg;
  20831. while (ws.read(msg)) {
  20832. ws.send(msg);
  20833. }
  20834. });
  20835. auto port = svr.bind_to_any_port("localhost");
  20836. std::thread t([&]() { svr.listen_after_bind(); });
  20837. auto se = detail::scope_exit([&] {
  20838. svr.stop();
  20839. t.join();
  20840. });
  20841. svr.wait_until_ready();
  20842. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20843. client_headers);
  20844. ASSERT_TRUE(client.connect());
  20845. ASSERT_TRUE(client.send("hello"));
  20846. std::string msg;
  20847. ASSERT_TRUE(client.read(msg));
  20848. client.close();
  20849. {
  20850. std::lock_guard<std::mutex> lock(mtx);
  20851. verify(received, port);
  20852. }
  20853. }
  20854. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20855. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20856. // Non-default port must be present in the Host header. Default ports
  20857. // (80/443) are omitted; that logic is covered by
  20858. // MakeHostAndPortStringTest.
  20859. EXPECT_EQ("localhost:" + std::to_string(port),
  20860. req.get_header_value("Host"));
  20861. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20862. req.get_header_value("User-Agent"));
  20863. EXPECT_FALSE(req.has_header("Accept"));
  20864. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20865. EXPECT_FALSE(req.has_header("Content-Length"));
  20866. });
  20867. }
  20868. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20869. capture_websocket_handshake_request(
  20870. {{"Host", "example.com"},
  20871. {"User-Agent", "custom-agent"},
  20872. {"X-Custom", "value"}},
  20873. [](const Request &req, int) {
  20874. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20875. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20876. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20877. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20878. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20879. });
  20880. }
  20881. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20882. capture_websocket_handshake_request(
  20883. {{"Upgrade", "bogus"},
  20884. {"Connection", "close"},
  20885. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20886. {"Sec-WebSocket-Version", "8"}},
  20887. [](const Request &req, int) {
  20888. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20889. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20890. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20891. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20892. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20893. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20894. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20895. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20896. req.get_header_value("Sec-WebSocket-Key"));
  20897. });
  20898. }
  20899. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20900. // A header the client refuses to send must abort the handshake before any
  20901. // part of it reaches the wire; a lone request line would otherwise sit in
  20902. // the peer's buffer as a truncated request.
  20903. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20904. ASSERT_NE(INVALID_SOCKET, srv);
  20905. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20906. sockaddr_in addr{};
  20907. addr.sin_family = AF_INET;
  20908. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20909. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20910. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20911. ASSERT_EQ(0, ::listen(srv, 1));
  20912. sockaddr_in bound{};
  20913. socklen_t bound_len = sizeof(bound);
  20914. ASSERT_EQ(
  20915. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20916. auto port = ntohs(bound.sin_port);
  20917. ssize_t received = -1;
  20918. std::thread t([&] {
  20919. // Bound every blocking call so a regression fails the test with a bad
  20920. // value instead of hanging the suite.
  20921. fd_set rfds;
  20922. FD_ZERO(&rfds);
  20923. FD_SET(srv, &rfds);
  20924. timeval tv{5, 0};
  20925. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20926. 0) {
  20927. return;
  20928. }
  20929. sockaddr_in cli_addr{};
  20930. socklen_t cli_len = sizeof(cli_addr);
  20931. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20932. if (cli == INVALID_SOCKET) { return; }
  20933. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20934. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20935. char buf[4096];
  20936. received = ::recv(cli, buf, sizeof(buf), 0);
  20937. });
  20938. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20939. // connect() has already shut the socket down by the time it returns false,
  20940. // so the peer sees EOF without waiting for the client to be destroyed.
  20941. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20942. {{"X-Bad", "a\r\nInjected: 1"}});
  20943. EXPECT_FALSE(client.connect());
  20944. t.join();
  20945. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20946. EXPECT_EQ(0, received);
  20947. }
  20948. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20949. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20950. // contains "upgrade" as a substring is a different token and must not
  20951. // start a WebSocket handshake.
  20952. auto make_request = [](const std::vector<std::string> &connection_values) {
  20953. Request req;
  20954. req.method = "GET";
  20955. req.headers.emplace("Upgrade", "websocket");
  20956. for (const auto &value : connection_values) {
  20957. req.headers.emplace("Connection", value);
  20958. }
  20959. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20960. req.headers.emplace("Sec-WebSocket-Version", "13");
  20961. return req;
  20962. };
  20963. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20964. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20965. EXPECT_TRUE(
  20966. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20967. EXPECT_TRUE(
  20968. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20969. EXPECT_TRUE(
  20970. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20971. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20972. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20973. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20974. EXPECT_FALSE(
  20975. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20976. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20977. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20978. }
  20979. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20980. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20981. // asks recipients to match each protocol-name case-insensitively, and RFC
  20982. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20983. // client naming websocket alongside another protocol, or on a second field
  20984. // line, is offering websocket; a value that merely contains "websocket" as a
  20985. // substring is a different protocol name and is not.
  20986. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20987. Request req;
  20988. req.method = "GET";
  20989. for (const auto &value : upgrade_values) {
  20990. req.headers.emplace("Upgrade", value);
  20991. }
  20992. req.headers.emplace("Connection", "Upgrade");
  20993. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20994. req.headers.emplace("Sec-WebSocket-Version", "13");
  20995. return req;
  20996. };
  20997. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20998. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20999. EXPECT_TRUE(
  21000. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21001. EXPECT_TRUE(
  21002. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21003. EXPECT_TRUE(
  21004. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21005. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21006. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21007. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21008. EXPECT_FALSE(
  21009. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21010. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21011. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21012. }
  21013. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21014. Server svr;
  21015. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21016. auto port = svr.bind_to_any_port("localhost");
  21017. std::thread t([&]() { svr.listen_after_bind(); });
  21018. auto se = detail::scope_exit([&] {
  21019. svr.stop();
  21020. t.join();
  21021. });
  21022. svr.wait_until_ready();
  21023. Headers headers = {{"Upgrade", "websocket"},
  21024. {"Connection", "notupgrade"},
  21025. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21026. {"Sec-WebSocket-Version", "13"}};
  21027. Client cli("localhost", port);
  21028. auto res = cli.Get("/ws", headers);
  21029. // The route exists only as a WebSocket route, so a request that fails the
  21030. // handshake check falls through to ordinary routing.
  21031. ASSERT_TRUE(res);
  21032. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21033. }
  21034. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21035. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21036. // Connection value is the only thing left for the client to reject.
  21037. Server svr;
  21038. svr.Get("/ws", [](const Request &req, Response &res) {
  21039. res.status = StatusCode::SwitchingProtocol_101;
  21040. res.set_header("Upgrade", "websocket");
  21041. res.set_header("Connection", "notupgrade");
  21042. res.set_header("Sec-WebSocket-Accept",
  21043. detail::websocket_accept_key(
  21044. req.get_header_value("Sec-WebSocket-Key")));
  21045. });
  21046. auto port = svr.bind_to_any_port("localhost");
  21047. std::thread t([&]() { svr.listen_after_bind(); });
  21048. auto se = detail::scope_exit([&] {
  21049. svr.stop();
  21050. t.join();
  21051. });
  21052. svr.wait_until_ready();
  21053. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21054. auto res = client.connect();
  21055. EXPECT_FALSE(res);
  21056. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21057. EXPECT_FALSE(client.is_open());
  21058. }
  21059. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21060. Server svr;
  21061. svr.Get("/ws", [](const Request &req, Response &res) {
  21062. res.status = StatusCode::SwitchingProtocol_101;
  21063. res.set_header("Upgrade", "websocket");
  21064. res.set_header("Connection", "Upgrade");
  21065. res.set_header("Sec-WebSocket-Accept",
  21066. detail::websocket_accept_key(
  21067. req.get_header_value("Sec-WebSocket-Key")));
  21068. res.set_header("Sec-WebSocket-Protocol", "admin");
  21069. });
  21070. auto port = svr.bind_to_any_port("localhost");
  21071. std::thread t([&]() { svr.listen_after_bind(); });
  21072. auto se = detail::scope_exit([&] {
  21073. svr.stop();
  21074. t.join();
  21075. });
  21076. svr.wait_until_ready();
  21077. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21078. // Server selects a subprotocol the client never offered
  21079. {
  21080. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21081. ws::WebSocketClient client(url, headers);
  21082. auto res = client.connect();
  21083. EXPECT_FALSE(res);
  21084. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21085. EXPECT_FALSE(client.is_open());
  21086. EXPECT_TRUE(client.subprotocol().empty());
  21087. }
  21088. // Client offered none but the server named one anyway
  21089. {
  21090. ws::WebSocketClient client(url);
  21091. auto res = client.connect();
  21092. EXPECT_FALSE(res);
  21093. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21094. EXPECT_FALSE(client.is_open());
  21095. EXPECT_TRUE(client.subprotocol().empty());
  21096. }
  21097. }
  21098. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21099. // The socket path doubles as the URL host, so it must not contain '/'.
  21100. const char *shard = getenv("GTEST_SHARD_INDEX");
  21101. const std::string sock_path =
  21102. shard ? std::string("httplib-ws-") + shard + ".sock"
  21103. : std::string("httplib-ws.sock");
  21104. std::remove(sock_path.c_str());
  21105. Server svr;
  21106. std::mutex mtx;
  21107. std::string received_host;
  21108. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21109. {
  21110. std::lock_guard<std::mutex> lock(mtx);
  21111. received_host = req.get_header_value("Host");
  21112. }
  21113. std::string msg;
  21114. while (ws.read(msg)) {
  21115. ws.send(msg);
  21116. }
  21117. });
  21118. svr.set_address_family(AF_UNIX);
  21119. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21120. auto se = detail::scope_exit([&] {
  21121. svr.stop();
  21122. t.join();
  21123. std::remove(sock_path.c_str());
  21124. });
  21125. svr.wait_until_ready();
  21126. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21127. client.set_address_family(AF_UNIX);
  21128. ASSERT_TRUE(client.connect());
  21129. ASSERT_TRUE(client.send("hello"));
  21130. std::string msg;
  21131. ASSERT_TRUE(client.read(msg));
  21132. client.close();
  21133. {
  21134. std::lock_guard<std::mutex> lock(mtx);
  21135. // There is no host:port for a Unix socket, so the same "localhost"
  21136. // placeholder the HTTP client uses is expected.
  21137. EXPECT_EQ("localhost", received_host);
  21138. }
  21139. }
  21140. // Two threads must never parse WebSocket frames from the same stream.
  21141. // close() used to read the peer's Close reply with its own frame read, so it
  21142. // raced a reader thread that was in the middle of a payload: the payload loop
  21143. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21144. // so bytes taken by close() were replaced with bytes from further along the
  21145. // stream. The message kept its length and silently changed content.
  21146. //
  21147. // The raw peer below sends a frame header plus part of the payload, waits for
  21148. // the handler to call close(), and only then sends the rest. Whichever thread
  21149. // would win the race for those bytes, the message must arrive intact, because
  21150. // close() must not touch the stream while read() owns it.
  21151. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21152. #ifndef _WIN32
  21153. signal(SIGPIPE, SIG_IGN);
  21154. #endif
  21155. const size_t payload_len = 120; // fits the 7-bit length field
  21156. const size_t prefix_len = 8;
  21157. const int attempts = 8;
  21158. std::string expected(payload_len, '\0');
  21159. for (size_t i = 0; i < payload_len; i++) {
  21160. expected[i] = static_cast<char>('a' + i % 26);
  21161. }
  21162. std::atomic<bool> peer_stalled{false};
  21163. std::atomic<bool> handler_done{false};
  21164. std::mutex received_mutex;
  21165. std::vector<std::string> received;
  21166. // Bound every wait, so a regression fails the test instead of hanging the
  21167. // suite.
  21168. auto wait_for = [](const std::atomic<bool> &flag) {
  21169. for (int i = 0; i < 500 && !flag; i++) {
  21170. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21171. }
  21172. };
  21173. Server svr;
  21174. svr.set_websocket_ping_interval(0);
  21175. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21176. std::thread reader([&]() {
  21177. std::string msg;
  21178. while (ws.read(msg)) {
  21179. std::lock_guard<std::mutex> guard(received_mutex);
  21180. received.push_back(msg);
  21181. }
  21182. });
  21183. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21184. // inside read_websocket_frame() when close() runs.
  21185. wait_for(peer_stalled);
  21186. ws.close();
  21187. reader.join();
  21188. handler_done = true;
  21189. });
  21190. auto port = svr.bind_to_any_port("127.0.0.1");
  21191. std::thread t([&]() { svr.listen_after_bind(); });
  21192. auto se = detail::scope_exit([&] {
  21193. svr.stop();
  21194. t.join();
  21195. });
  21196. svr.wait_until_ready();
  21197. auto send_bytes = [](socket_t s, const std::string &data) {
  21198. #ifdef _WIN32
  21199. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21200. #else
  21201. auto n = ::send(s, data.data(), data.size(), 0);
  21202. #endif
  21203. return n == static_cast<decltype(n)>(data.size());
  21204. };
  21205. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21206. // Every length used here fits the 7-bit length field.
  21207. auto masked_header = [](uint8_t first_byte, size_t len) {
  21208. std::string h;
  21209. h += static_cast<char>(first_byte);
  21210. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21211. h.append(4, '\0'); // mask key
  21212. return h;
  21213. };
  21214. for (int attempt = 0; attempt < attempts; attempt++) {
  21215. peer_stalled = false;
  21216. handler_done = false;
  21217. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21218. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21219. auto se_sock = detail::scope_exit([&] {
  21220. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21221. });
  21222. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21223. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21224. sockaddr_in addr{};
  21225. addr.sin_family = AF_INET;
  21226. addr.sin_port = htons(static_cast<uint16_t>(port));
  21227. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21228. ASSERT_EQ(
  21229. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21230. << "attempt " << attempt;
  21231. ASSERT_TRUE(send_bytes(sock,
  21232. "GET /ws HTTP/1.1\r\n"
  21233. "Host: 127.0.0.1\r\n"
  21234. "Upgrade: websocket\r\n"
  21235. "Connection: Upgrade\r\n"
  21236. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21237. "Sec-WebSocket-Version: 13\r\n"
  21238. "\r\n"))
  21239. << "attempt " << attempt;
  21240. std::string response;
  21241. while (response.find("\r\n\r\n") == std::string::npos) {
  21242. char buf[512];
  21243. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21244. if (n <= 0) { break; }
  21245. response.append(buf, static_cast<size_t>(n));
  21246. }
  21247. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21248. << "attempt " << attempt;
  21249. // Send the header of a Binary message but only the first prefix_len bytes
  21250. // of its payload, leaving the reader thread stalled inside the payload.
  21251. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21252. expected.substr(0, prefix_len)))
  21253. << "attempt " << attempt;
  21254. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21255. peer_stalled = true;
  21256. // Let close() send its Close frame and park in its own read before the
  21257. // rest of the payload arrives, so both threads are waiting for it.
  21258. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21259. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21260. close_frame += static_cast<char>(0x03); // status 1000
  21261. close_frame += static_cast<char>(0xE8);
  21262. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21263. << "attempt " << attempt;
  21264. // Closing the peer releases the reader thread even on the buggy path,
  21265. // where it waits for bytes another thread already consumed.
  21266. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21267. detail::close_socket(sock);
  21268. sock = INVALID_SOCKET;
  21269. wait_for(handler_done);
  21270. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21271. }
  21272. std::lock_guard<std::mutex> guard(received_mutex);
  21273. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21274. << "a message in flight when close() ran was dropped";
  21275. for (size_t i = 0; i < received.size(); i++) {
  21276. EXPECT_EQ(expected, received[i]) << "message " << i;
  21277. }
  21278. }
  21279. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21280. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21281. protected:
  21282. void SetUp() override {
  21283. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21284. SERVER_PRIVATE_KEY_FILE);
  21285. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21286. std::string msg;
  21287. ws::ReadResult ret;
  21288. while ((ret = ws.read(msg))) {
  21289. if (ret == ws::Binary) {
  21290. ws.send(msg.data(), msg.size());
  21291. } else {
  21292. ws.send(msg);
  21293. }
  21294. }
  21295. });
  21296. port_ = server_->bind_to_any_port(HOST);
  21297. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21298. server_->wait_until_ready();
  21299. }
  21300. void TearDown() override {
  21301. server_->stop();
  21302. if (server_thread_.joinable()) { server_thread_.join(); }
  21303. }
  21304. std::unique_ptr<SSLServer> server_;
  21305. std::thread server_thread_;
  21306. int port_ = 0;
  21307. };
  21308. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21309. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21310. "/ws-echo");
  21311. client.enable_server_certificate_verification(false);
  21312. ASSERT_TRUE(client.connect());
  21313. ASSERT_TRUE(client.is_open());
  21314. ASSERT_TRUE(client.send("Hello WSS"));
  21315. std::string msg;
  21316. EXPECT_EQ(ws::Text, client.read(msg));
  21317. EXPECT_EQ("Hello WSS", msg);
  21318. client.close();
  21319. }
  21320. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21321. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21322. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21323. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21324. // client (without calling close() first) is the only path that runs
  21325. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21326. // bug exactly.
  21327. //
  21328. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21329. // when linked against an instrumented libssl; run under Valgrind to catch it
  21330. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21331. // suite (the freed session otherwise stalls on the close handshake) — this test
  21332. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21333. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21334. {
  21335. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21336. "/ws-echo");
  21337. client.enable_server_certificate_verification(false);
  21338. client.set_read_timeout(2, 0);
  21339. client.set_write_timeout(2, 0);
  21340. ASSERT_TRUE(client.connect());
  21341. ASSERT_TRUE(client.is_open());
  21342. ASSERT_TRUE(client.send("still open"));
  21343. // Intentionally do NOT call client.close(): leaving scope runs
  21344. // shutdown_and_close() with the WebSocket still open, which must send the
  21345. // close frame while the TLS session is still alive.
  21346. }
  21347. }
  21348. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21349. // shutdown_and_close() at the start of connect(), reproducing the same
  21350. // use-after-free within the test body rather than at scope exit. The second
  21351. // connect must succeed and echo, proving the close handshake ran over a live
  21352. // session. See the note above about memory-tool requirements.
  21353. TEST_F(WebSocketSSLIntegrationTest,
  21354. ReconnectWhileOpenSendsCloseOverLiveSession) {
  21355. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21356. "/ws-echo");
  21357. client.enable_server_certificate_verification(false);
  21358. client.set_read_timeout(2, 0);
  21359. client.set_write_timeout(2, 0);
  21360. ASSERT_TRUE(client.connect());
  21361. ASSERT_TRUE(client.is_open());
  21362. ASSERT_TRUE(client.send("still open"));
  21363. // Reconnect without closing first: connect() calls shutdown_and_close() on
  21364. // the still-open connection, which must not touch a freed TLS session.
  21365. ASSERT_TRUE(client.connect());
  21366. ASSERT_TRUE(client.is_open());
  21367. ASSERT_TRUE(client.send("after reconnect"));
  21368. std::string msg;
  21369. EXPECT_EQ(ws::Text, client.read(msg));
  21370. EXPECT_EQ("after reconnect", msg);
  21371. client.close();
  21372. }
  21373. #endif
  21374. #ifdef CPPHTTPLIB_SSL_ENABLED
  21375. class WebSocketSSLCATest : public ::testing::Test {
  21376. protected:
  21377. void SetUp() override {
  21378. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  21379. SERVER_PRIVATE_KEY_FILE);
  21380. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21381. std::string msg;
  21382. while (ws.read(msg)) {
  21383. ws.send(msg);
  21384. }
  21385. });
  21386. port_ = server_->bind_to_any_port("127.0.0.1");
  21387. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21388. server_->wait_until_ready();
  21389. }
  21390. void TearDown() override {
  21391. server_->stop();
  21392. if (server_thread_.joinable()) { server_thread_.join(); }
  21393. }
  21394. std::string url() const {
  21395. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21396. }
  21397. std::unique_ptr<SSLServer> server_;
  21398. std::thread server_thread_;
  21399. int port_ = 0;
  21400. };
  21401. // A custom CA loaded as PEM verifies the server with full certificate
  21402. // verification enabled
  21403. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21404. ws::WebSocketClient client(url());
  21405. std::string cert;
  21406. read_file(SERVER_CERT2_FILE, cert);
  21407. client.load_ca_cert_store(cert.c_str(), cert.size());
  21408. ASSERT_TRUE(client.connect());
  21409. ASSERT_TRUE(client.send("hello"));
  21410. std::string msg;
  21411. EXPECT_EQ(ws::Text, client.read(msg));
  21412. EXPECT_EQ("hello", msg);
  21413. client.close();
  21414. }
  21415. // A custom CA that does not cover the server must fail verification (the
  21416. // custom CA is exclusive; system certs are not loaded alongside it)
  21417. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21418. ws::WebSocketClient client(url());
  21419. std::string cert;
  21420. read_file(CLIENT_CA_CERT_FILE, cert);
  21421. client.load_ca_cert_store(cert.c_str(), cert.size());
  21422. auto res = client.connect();
  21423. ASSERT_FALSE(res);
  21424. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21425. EXPECT_EQ(-1, res.status());
  21426. EXPECT_NE(0u, res.ssl_backend_error());
  21427. }
  21428. // The same CA as a file path rather than PEM in memory
  21429. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21430. ws::WebSocketClient client(url());
  21431. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21432. ASSERT_TRUE(client.connect());
  21433. ASSERT_TRUE(client.send("hello"));
  21434. std::string msg;
  21435. EXPECT_EQ(ws::Text, client.read(msg));
  21436. EXPECT_EQ("hello", msg);
  21437. client.close();
  21438. }
  21439. // ...and a CA file that does not cover the server still fails, so it is the
  21440. // path above that decides the outcome
  21441. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21442. ws::WebSocketClient client(url());
  21443. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21444. ASSERT_FALSE(client.connect());
  21445. }
  21446. // Regression test: reconnecting with a native custom CA store used to reuse
  21447. // a store handle the previous TLS context had already freed (use-after-free
  21448. // under the OpenSSL backend). The context now lives as long as the client.
  21449. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  21450. ws::WebSocketClient client(url());
  21451. std::string cert;
  21452. read_file(SERVER_CERT2_FILE, cert);
  21453. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  21454. ASSERT_TRUE(client.connect());
  21455. client.close();
  21456. ASSERT_TRUE(client.connect());
  21457. ASSERT_TRUE(client.send("again"));
  21458. std::string msg;
  21459. EXPECT_EQ(ws::Text, client.read(msg));
  21460. EXPECT_EQ("again", msg);
  21461. client.close();
  21462. }
  21463. // Regression test: a certificate with a trusted chain but no identity match
  21464. // for the server IP must be rejected. The Mbed TLS backend used to skip
  21465. // verification entirely for IP hosts, so this connection succeeded there.
  21466. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  21467. // chain verification while the identity check must still fail.
  21468. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  21469. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21470. ASSERT_TRUE(svr.is_valid());
  21471. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21472. std::string msg;
  21473. while (ws.read(msg)) {
  21474. ws.send(msg);
  21475. }
  21476. });
  21477. auto port = svr.bind_to_any_port("127.0.0.1");
  21478. auto t = std::thread([&]() { svr.listen_after_bind(); });
  21479. auto se = detail::scope_exit([&] {
  21480. svr.stop();
  21481. t.join();
  21482. });
  21483. svr.wait_until_ready();
  21484. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  21485. "/echo");
  21486. std::string cert;
  21487. read_file(SERVER_CERT_FILE, cert);
  21488. client.load_ca_cert_store(cert.c_str(), cert.size());
  21489. ASSERT_FALSE(client.connect());
  21490. }
  21491. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  21492. // SNI, so nothing binds the host name to the TLS session. These bind the
  21493. // server to "localhost" instead, the only shape that exercises the SNI and
  21494. // hostname-verification path with certificate verification left enabled.
  21495. class WebSocketSSLDnsHostTest : public ::testing::Test {
  21496. protected:
  21497. void Start(const char *cert_file) {
  21498. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  21499. SERVER_PRIVATE_KEY_FILE);
  21500. ASSERT_TRUE(server_->is_valid());
  21501. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21502. std::string msg;
  21503. while (ws.read(msg)) {
  21504. ws.send(msg);
  21505. }
  21506. });
  21507. port_ = server_->bind_to_any_port("localhost");
  21508. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21509. server_->wait_until_ready();
  21510. }
  21511. void TearDown() override {
  21512. if (server_) { server_->stop(); }
  21513. if (server_thread_.joinable()) { server_thread_.join(); }
  21514. }
  21515. std::string url() const {
  21516. return "wss://localhost:" + std::to_string(port_) + "/echo";
  21517. }
  21518. std::unique_ptr<SSLServer> server_;
  21519. std::thread server_thread_;
  21520. int port_ = 0;
  21521. };
  21522. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  21523. // out and the connection is usable
  21524. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  21525. Start(SERVER_CERT2_FILE);
  21526. ws::WebSocketClient client(url());
  21527. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21528. ASSERT_TRUE(client.connect());
  21529. ASSERT_TRUE(client.send("hello"));
  21530. std::string msg;
  21531. EXPECT_EQ(ws::Text, client.read(msg));
  21532. EXPECT_EQ("hello", msg);
  21533. client.close();
  21534. }
  21535. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  21536. // while the identity check must still reject "localhost"
  21537. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  21538. Start(SERVER_CERT_FILE);
  21539. ws::WebSocketClient client(url());
  21540. client.set_ca_cert_path(SERVER_CERT_FILE);
  21541. auto res = client.connect();
  21542. ASSERT_FALSE(res);
  21543. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  21544. EXPECT_EQ(-1, res.status());
  21545. }
  21546. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  21547. // disabled: the chain is still checked, only the identity check is skipped
  21548. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  21549. Start(SERVER_CERT_FILE);
  21550. ws::WebSocketClient client(url());
  21551. client.set_ca_cert_path(SERVER_CERT_FILE);
  21552. client.enable_server_hostname_verification(false);
  21553. ASSERT_TRUE(client.connect());
  21554. ASSERT_TRUE(client.send("hello"));
  21555. std::string msg;
  21556. EXPECT_EQ(ws::Text, client.read(msg));
  21557. EXPECT_EQ("hello", msg);
  21558. client.close();
  21559. }
  21560. // A CA that did not sign the server certificate fails the chain, even though
  21561. // the name would match
  21562. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  21563. Start(SERVER_CERT2_FILE);
  21564. ws::WebSocketClient client(url());
  21565. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21566. ASSERT_FALSE(client.connect());
  21567. }
  21568. // With verification disabled, neither the chain nor the name is checked
  21569. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  21570. Start(SERVER_CERT_FILE);
  21571. ws::WebSocketClient client(url());
  21572. client.enable_server_certificate_verification(false);
  21573. ASSERT_TRUE(client.connect());
  21574. ASSERT_TRUE(client.send("hello"));
  21575. std::string msg;
  21576. EXPECT_EQ(ws::Text, client.read(msg));
  21577. EXPECT_EQ("hello", msg);
  21578. client.close();
  21579. }
  21580. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  21581. protected:
  21582. void SetUp() override {
  21583. server_ = httplib::detail::make_unique<SSLServer>(
  21584. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21585. ASSERT_TRUE(server_->is_valid());
  21586. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21587. std::string msg;
  21588. while (ws.read(msg)) {
  21589. ws.send(msg);
  21590. }
  21591. });
  21592. port_ = server_->bind_to_any_port("localhost");
  21593. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21594. server_->wait_until_ready();
  21595. }
  21596. void TearDown() override {
  21597. server_->stop();
  21598. if (server_thread_.joinable()) { server_thread_.join(); }
  21599. }
  21600. std::string url() const {
  21601. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21602. }
  21603. void ConnectWithClientCert(const std::string &client_cert_file,
  21604. const std::string &client_private_key_file,
  21605. const char *private_key_password) {
  21606. std::string cert_pem, key_pem;
  21607. read_file(client_cert_file, cert_pem);
  21608. read_file(client_private_key_file, key_pem);
  21609. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21610. key_pem.c_str(), key_pem.size(),
  21611. private_key_password};
  21612. ws::WebSocketClient client(url(), pem);
  21613. ASSERT_TRUE(client.is_valid());
  21614. client.enable_server_certificate_verification(false);
  21615. ASSERT_TRUE(client.connect());
  21616. ASSERT_TRUE(client.send("hello"));
  21617. std::string msg;
  21618. EXPECT_EQ(ws::Text, client.read(msg));
  21619. EXPECT_EQ("hello", msg);
  21620. client.close();
  21621. }
  21622. std::unique_ptr<SSLServer> server_;
  21623. std::thread server_thread_;
  21624. int port_ = 0;
  21625. };
  21626. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21627. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21628. }
  21629. // Control for the tests above: the fixture's server really does require a
  21630. // client certificate, so it is the PEM the constructor installed that decides
  21631. // the outcome.
  21632. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21633. ws::WebSocketClient client(url());
  21634. ASSERT_TRUE(client.is_valid());
  21635. client.enable_server_certificate_verification(false);
  21636. EXPECT_FALSE(client.connect());
  21637. }
  21638. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21639. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21640. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21641. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21642. }
  21643. #endif
  21644. #if !defined(_WIN32)
  21645. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21646. auto secret_dir = std::string("./symlink_test_secret");
  21647. auto served_dir = std::string("./symlink_test_served");
  21648. auto secret_file = secret_dir + "/secret.txt";
  21649. auto symlink_path = served_dir + "/escape";
  21650. // Setup: create directories and files
  21651. mkdir(secret_dir.c_str(), 0755);
  21652. mkdir(served_dir.c_str(), 0755);
  21653. {
  21654. std::ofstream ofs(secret_file);
  21655. ofs << "SECRET_DATA";
  21656. }
  21657. // Create symlink using absolute path so it resolves correctly
  21658. #ifdef PATH_MAX
  21659. char abs_secret[PATH_MAX];
  21660. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21661. #else
  21662. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21663. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21664. ASSERT_NE(nullptr, abs_secret);
  21665. #endif
  21666. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21667. auto se = detail::scope_exit([&] {
  21668. unlink(symlink_path.c_str());
  21669. unlink(secret_file.c_str());
  21670. rmdir(served_dir.c_str());
  21671. rmdir(secret_dir.c_str());
  21672. });
  21673. Server svr;
  21674. svr.set_mount_point("/", served_dir);
  21675. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21676. auto se2 = detail::scope_exit([&] {
  21677. svr.stop();
  21678. listen_thread.join();
  21679. });
  21680. svr.wait_until_ready();
  21681. Client cli("localhost", PORT);
  21682. // Symlink pointing outside base dir should be blocked
  21683. auto res = cli.Get("/escape/secret.txt");
  21684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21685. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21686. }
  21687. #endif
  21688. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  21689. // "GET /smuggled" request), reads the first response, and only then sends the
  21690. // embedded request as the body. Returns how many times /smuggled ran.
  21691. //
  21692. // The body is sent AFTER receiving the first response (as in the original
  21693. // PoC) so that the stream_line_reader cannot buffer it together with the
  21694. // headers of the first request.
  21695. static int count_smuggled_requests(const std::string &outer_head,
  21696. std::string &first_response) {
  21697. Server svr;
  21698. svr.set_mount_point("/", "./www");
  21699. std::atomic<int> smuggled_count(0);
  21700. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21701. smuggled_count++;
  21702. res.set_content("oops", "text/plain");
  21703. });
  21704. svr.Post("/post", [&](const Request &req, Response &res) {
  21705. res.set_content(req.body, "text/plain");
  21706. });
  21707. auto port = svr.bind_to_any_port("localhost");
  21708. thread t = thread([&] { svr.listen_after_bind(); });
  21709. auto se = detail::scope_exit([&] {
  21710. svr.stop();
  21711. t.join();
  21712. });
  21713. svr.wait_until_ready();
  21714. auto error = Error::Success;
  21715. auto sock = detail::create_client_socket(
  21716. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21717. /*connection_timeout_sec=*/2, 0,
  21718. /*read_timeout_sec=*/2, 0,
  21719. /*write_timeout_sec=*/2, 0, std::string(), error);
  21720. EXPECT_NE(INVALID_SOCKET, sock);
  21721. if (sock == INVALID_SOCKET) { return -1; }
  21722. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21723. // The "smuggled" request will be sent as the body of the outer request
  21724. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21725. "Host: localhost\r\n"
  21726. "Connection: close\r\n"
  21727. "\r\n";
  21728. auto head = outer_head;
  21729. auto len = std::to_string(smuggled.size());
  21730. for (auto pos = head.find("{len}"); pos != std::string::npos;
  21731. pos = head.find("{len}", pos + len.size())) {
  21732. head.replace(pos, 5, len);
  21733. }
  21734. // Step 1: Send only the outer request headers (no body yet)
  21735. auto sent = send(sock, head.data(), head.size(), 0);
  21736. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  21737. // Step 2: Read the first response
  21738. char buf[4096];
  21739. for (;;) {
  21740. auto n = recv(sock, buf, sizeof(buf), 0);
  21741. if (n <= 0) break;
  21742. first_response.append(buf, static_cast<size_t>(n));
  21743. // Stop once we have a complete response (headers + body)
  21744. auto hdr_end = first_response.find("\r\n\r\n");
  21745. if (hdr_end != std::string::npos) {
  21746. // Check for Content-Length to know when the body is complete
  21747. auto cl_pos = first_response.find("Content-Length:");
  21748. if (cl_pos != std::string::npos) {
  21749. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21750. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21751. auto cl = std::stoul(
  21752. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21753. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21754. } else {
  21755. break; // No Content-Length, assume headers-only response
  21756. }
  21757. }
  21758. }
  21759. // Step 3: Now send the body, which looks like a new HTTP request. On a
  21760. // vulnerable server the keep-alive loop reads this as a second request. The
  21761. // server may already have closed the connection, so the result is ignored.
  21762. send(sock, smuggled.data(), smuggled.size(), 0);
  21763. // Half-close so that a server which drained the body sees EOF and closes,
  21764. // instead of the read below waiting for the read timeout.
  21765. #ifdef _WIN32
  21766. ::shutdown(sock, SD_SEND);
  21767. #else
  21768. ::shutdown(sock, SHUT_WR);
  21769. #endif
  21770. // Step 4: Read until the server closes the connection
  21771. for (;;) {
  21772. auto n = recv(sock, buf, sizeof(buf), 0);
  21773. if (n <= 0) break;
  21774. }
  21775. return smuggled_count.load();
  21776. }
  21777. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21778. // A GET request with Content-Length to a static file handler must have its
  21779. // body drained before the keep-alive connection is reused. Otherwise the
  21780. // unread body bytes are interpreted as the next HTTP request.
  21781. std::string first_response;
  21782. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21783. "Host: localhost\r\n"
  21784. "Content-Length: {len}\r\n"
  21785. "\r\n",
  21786. first_response));
  21787. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  21788. }
  21789. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  21790. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  21791. // be answered with 400 and the connection closed. Treating it as "no body"
  21792. // leaves the body to be parsed as the next request.
  21793. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  21794. const char *targets[] = {
  21795. "GET /file", // handler that never reads the body
  21796. "GET /not-found", // no handler matches (404)
  21797. "POST /post", // handler that reads the body
  21798. };
  21799. for (auto target : targets) {
  21800. for (auto value : values) {
  21801. std::string first_response;
  21802. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  21803. " HTTP/1.1\r\n"
  21804. "Host: localhost\r\n"
  21805. "Content-Length: " +
  21806. value + "\r\n\r\n",
  21807. first_response))
  21808. << target << " with Content-Length: " << value;
  21809. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  21810. << target << " with Content-Length: " << value;
  21811. }
  21812. }
  21813. }
  21814. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  21815. // A 400 for an unparseable request line leaves the rest of the message
  21816. // unread, so the connection must be closed rather than reused.
  21817. std::string first_response;
  21818. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  21819. "Host: localhost\r\n"
  21820. "Content-Length: {len}\r\n"
  21821. "\r\n",
  21822. first_response));
  21823. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21824. }
  21825. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  21826. // Same as above for a header block that fails to parse.
  21827. std::string first_response;
  21828. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21829. "Host: localhost\r\n"
  21830. "Bad Header\r\n"
  21831. "Content-Length: {len}\r\n"
  21832. "\r\n",
  21833. first_response));
  21834. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21835. }
  21836. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  21837. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  21838. // server must not read another request on that connection, even when the
  21839. // request had no body to drain.
  21840. std::string first_response;
  21841. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  21842. "Host: localhost\r\n"
  21843. "\r\n",
  21844. first_response));
  21845. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  21846. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  21847. }
  21848. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21849. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21850. // must be rejected with 400 Bad Request.
  21851. Server svr;
  21852. svr.Post("/test", [&](const Request &, Response &res) {
  21853. res.set_content("ok", "text/plain");
  21854. });
  21855. thread t = thread([&] { svr.listen(HOST, PORT); });
  21856. auto se = detail::scope_exit([&] {
  21857. svr.stop();
  21858. t.join();
  21859. ASSERT_FALSE(svr.is_running());
  21860. });
  21861. svr.wait_until_ready();
  21862. // Exact "chunked"
  21863. {
  21864. auto req = "POST /test HTTP/1.1\r\n"
  21865. "Host: localhost\r\n"
  21866. "Content-Length: 5\r\n"
  21867. "Transfer-Encoding: chunked\r\n"
  21868. "Connection: close\r\n"
  21869. "\r\n"
  21870. "hello";
  21871. std::string response;
  21872. ASSERT_TRUE(send_request(1, req, &response));
  21873. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21874. response.substr(0, response.find("\r\n")));
  21875. }
  21876. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21877. {
  21878. auto req = "POST /test HTTP/1.1\r\n"
  21879. "Host: localhost\r\n"
  21880. "Content-Length: 5\r\n"
  21881. "Transfer-Encoding: gzip, chunked\r\n"
  21882. "Connection: close\r\n"
  21883. "\r\n"
  21884. "hello";
  21885. std::string response;
  21886. ASSERT_TRUE(send_request(1, req, &response));
  21887. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21888. response.substr(0, response.find("\r\n")));
  21889. }
  21890. }
  21891. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21892. Server svr;
  21893. svr.Post("/test", [&](const Request &, Response &res) {
  21894. res.set_content("ok", "text/plain");
  21895. });
  21896. thread t = thread([&] { svr.listen(HOST, PORT); });
  21897. auto se = detail::scope_exit([&] {
  21898. svr.stop();
  21899. t.join();
  21900. ASSERT_FALSE(svr.is_running());
  21901. });
  21902. svr.wait_until_ready();
  21903. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  21904. // length cannot be determined, so the server must answer 400 and close
  21905. // rather than treat the request as bodyless and leave the body in the
  21906. // socket for the next request to pick up.
  21907. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  21908. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  21909. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  21910. std::string response;
  21911. ASSERT_TRUE(send_request(1, req, &response));
  21912. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21913. response.substr(0, response.find("\r\n")))
  21914. << transfer_encoding;
  21915. }
  21916. // RFC 9110 5.3: the codings may also be split across several
  21917. // Transfer-Encoding lines, which combine in the order they were received.
  21918. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  21919. // just like the single-line "chunked, gzip" above.
  21920. {
  21921. auto req = "POST /test HTTP/1.1\r\n"
  21922. "Host: localhost\r\n"
  21923. "Transfer-Encoding: chunked\r\n"
  21924. "Transfer-Encoding: gzip\r\n"
  21925. "\r\n"
  21926. "0\r\n\r\n";
  21927. std::string response;
  21928. ASSERT_TRUE(send_request(1, req, &response));
  21929. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21930. response.substr(0, response.find("\r\n")));
  21931. }
  21932. // A sequence ending in chunked stays valid.
  21933. auto req = "POST /test HTTP/1.1\r\n"
  21934. "Host: localhost\r\n"
  21935. "Transfer-Encoding: gzip, chunked\r\n"
  21936. "Connection: close\r\n"
  21937. "\r\n"
  21938. "0\r\n\r\n";
  21939. std::string response;
  21940. ASSERT_TRUE(send_request(1, req, &response));
  21941. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21942. // ...including when it is spread over several lines.
  21943. auto split_req = "POST /test HTTP/1.1\r\n"
  21944. "Host: localhost\r\n"
  21945. "Transfer-Encoding: gzip\r\n"
  21946. "Transfer-Encoding: chunked\r\n"
  21947. "Connection: close\r\n"
  21948. "\r\n"
  21949. "0\r\n\r\n";
  21950. std::string split_response;
  21951. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21952. EXPECT_EQ("HTTP/1.1 200 OK",
  21953. split_response.substr(0, split_response.find("\r\n")));
  21954. }
  21955. // Regression for issue #2450: a DELETE without Content-Length on a
  21956. // keep-alive connection must not let the post-response drain consume the
  21957. // next request's bytes.
  21958. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21959. Server svr;
  21960. std::atomic<int> delete_count(0);
  21961. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21962. delete_count++;
  21963. res.status = StatusCode::NoContent_204;
  21964. });
  21965. auto port = svr.bind_to_any_port(HOST);
  21966. thread t = thread([&] { svr.listen_after_bind(); });
  21967. auto se = detail::scope_exit([&] {
  21968. svr.stop();
  21969. t.join();
  21970. });
  21971. svr.wait_until_ready();
  21972. auto error = Error::Success;
  21973. auto sock = detail::create_client_socket(
  21974. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21975. /*connection_timeout_sec=*/2, 0,
  21976. /*read_timeout_sec=*/2, 0,
  21977. /*write_timeout_sec=*/2, 0, std::string(), error);
  21978. ASSERT_NE(INVALID_SOCKET, sock);
  21979. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21980. auto send_request_and_read_response = [&](const std::string &req,
  21981. std::string &out) -> bool {
  21982. auto sent = send(sock, req.data(), req.size(), 0);
  21983. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21984. char buf[4096];
  21985. for (;;) {
  21986. auto n = recv(sock, buf, sizeof(buf), 0);
  21987. if (n <= 0) { return !out.empty(); }
  21988. out.append(buf, static_cast<size_t>(n));
  21989. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21990. }
  21991. };
  21992. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21993. "Host: localhost\r\n"
  21994. "\r\n";
  21995. std::string resp1;
  21996. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21997. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21998. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21999. "Host: localhost\r\n"
  22000. "Connection: close\r\n"
  22001. "\r\n";
  22002. std::string resp2;
  22003. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22004. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22005. EXPECT_EQ(2, delete_count.load());
  22006. }
  22007. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22008. Server svr;
  22009. svr.Post("/ingest", [&](const Request &, Response &res,
  22010. const ContentReader &content_reader) {
  22011. auto consumed = content_reader([](const char *, size_t) { return false; });
  22012. EXPECT_FALSE(consumed);
  22013. res.status = StatusCode::Conflict_409;
  22014. res.set_header("Connection", "close");
  22015. });
  22016. auto port = svr.bind_to_any_port(HOST);
  22017. thread t = thread([&] { svr.listen_after_bind(); });
  22018. auto se = detail::scope_exit([&] {
  22019. svr.stop();
  22020. t.join();
  22021. });
  22022. svr.wait_until_ready();
  22023. auto error = Error::Success;
  22024. auto sock = detail::create_client_socket(
  22025. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22026. /*connection_timeout_sec=*/2, 0,
  22027. /*read_timeout_sec=*/1, 0,
  22028. /*write_timeout_sec=*/2, 0, std::string(), error);
  22029. ASSERT_NE(INVALID_SOCKET, sock);
  22030. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22031. std::string request = "POST /ingest HTTP/1.1\r\n"
  22032. "Host: localhost\r\n"
  22033. "Transfer-Encoding: chunked\r\n"
  22034. "\r\n"
  22035. "4\r\n"
  22036. "data\r\n";
  22037. auto sent = send(sock, request.data(), request.size(), 0);
  22038. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22039. std::string response;
  22040. ssize_t received = 0;
  22041. do {
  22042. char buf[4096];
  22043. received = recv(sock, buf, sizeof(buf), 0);
  22044. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22045. } while (received > 0);
  22046. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22047. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22048. EXPECT_EQ(0, received);
  22049. }
  22050. namespace no_proxy_test {
  22051. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22052. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22053. // calling listen().
  22054. class ScopedServer {
  22055. public:
  22056. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22057. ~ScopedServer() {
  22058. svr_.stop();
  22059. if (th_.joinable()) { th_.join(); }
  22060. }
  22061. Server &svr() { return svr_; }
  22062. int port() const { return port_; }
  22063. void listen() {
  22064. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22065. svr_.wait_until_ready();
  22066. }
  22067. private:
  22068. Server svr_;
  22069. std::thread th_;
  22070. int port_ = 0;
  22071. };
  22072. class ProxyAndTargetServers {
  22073. public:
  22074. ProxyAndTargetServers() {
  22075. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22076. proxy_hits_++;
  22077. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22078. res.set_content("via-proxy", "text/plain");
  22079. });
  22080. target_.Get(".*", [this](const Request &req, Response &res) {
  22081. target_hits_++;
  22082. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22083. res.set_content("direct", "text/plain");
  22084. });
  22085. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22086. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22087. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22088. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22089. proxy_mock_.wait_until_ready();
  22090. target_.wait_until_ready();
  22091. }
  22092. ~ProxyAndTargetServers() {
  22093. proxy_mock_.stop();
  22094. target_.stop();
  22095. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22096. if (target_thread_.joinable()) { target_thread_.join(); }
  22097. }
  22098. Server &proxy_mock() { return proxy_mock_; }
  22099. Server &target() { return target_; }
  22100. int proxy_port() const { return proxy_port_; }
  22101. int target_port() const { return target_port_; }
  22102. int proxy_hits() const { return proxy_hits_.load(); }
  22103. int target_hits() const { return target_hits_.load(); }
  22104. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22105. void reset_counters() {
  22106. proxy_hits_ = 0;
  22107. target_hits_ = 0;
  22108. last_had_proxy_authz_ = false;
  22109. }
  22110. private:
  22111. Server proxy_mock_;
  22112. Server target_;
  22113. std::thread proxy_thread_;
  22114. std::thread target_thread_;
  22115. int proxy_port_ = 0;
  22116. int target_port_ = 0;
  22117. std::atomic<int> proxy_hits_{0};
  22118. std::atomic<int> target_hits_{0};
  22119. std::atomic<bool> last_had_proxy_authz_{false};
  22120. };
  22121. inline std::unique_ptr<Client> make_client(const std::string &host,
  22122. ProxyAndTargetServers &s) {
  22123. auto cli = detail::make_unique<Client>(host, s.target_port());
  22124. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22125. cli->set_proxy("127.0.0.1", s.proxy_port());
  22126. return cli;
  22127. }
  22128. } // namespace no_proxy_test
  22129. using no_proxy_test::make_client;
  22130. using no_proxy_test::ProxyAndTargetServers;
  22131. TEST(NoProxyTest, ExactHostnameBypasses) {
  22132. ProxyAndTargetServers s;
  22133. auto cli = make_client("example.com", s);
  22134. cli->set_no_proxy({"example.com"});
  22135. auto res = cli->Get("/");
  22136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22137. EXPECT_EQ(0, s.proxy_hits());
  22138. EXPECT_EQ(1, s.target_hits());
  22139. }
  22140. TEST(NoProxyTest, SubdomainBypasses) {
  22141. ProxyAndTargetServers s;
  22142. auto cli = make_client("foo.example.com", s);
  22143. cli->set_no_proxy({"example.com"});
  22144. auto res = cli->Get("/");
  22145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22146. EXPECT_EQ(0, s.proxy_hits());
  22147. EXPECT_EQ(1, s.target_hits());
  22148. }
  22149. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  22150. // Regression guard: "evilexample.com" must not be considered a subdomain
  22151. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22152. // check would let traffic bypass the proxy and leak credentials direct
  22153. // to the attacker host.
  22154. ProxyAndTargetServers s;
  22155. auto cli = make_client("evilexample.com", s);
  22156. cli->set_no_proxy({"example.com"});
  22157. auto res = cli->Get("/");
  22158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22159. EXPECT_GE(s.proxy_hits(), 1);
  22160. EXPECT_EQ(0, s.target_hits());
  22161. }
  22162. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22163. ProxyAndTargetServers s;
  22164. auto cli = make_client("example.com.evil.com", s);
  22165. cli->set_no_proxy({"example.com"});
  22166. auto res = cli->Get("/");
  22167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22168. EXPECT_GE(s.proxy_hits(), 1);
  22169. EXPECT_EQ(0, s.target_hits());
  22170. }
  22171. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22172. ProxyAndTargetServers s;
  22173. auto cli = make_client("example.com", s);
  22174. cli->set_no_proxy({".example.com"});
  22175. auto res = cli->Get("/");
  22176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22177. EXPECT_EQ(0, s.proxy_hits());
  22178. EXPECT_EQ(1, s.target_hits());
  22179. }
  22180. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22181. ProxyAndTargetServers s;
  22182. auto cli = make_client("Example.COM", s);
  22183. cli->set_no_proxy({"EXAMPLE.com"});
  22184. auto res = cli->Get("/");
  22185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22186. EXPECT_EQ(0, s.proxy_hits());
  22187. EXPECT_EQ(1, s.target_hits());
  22188. }
  22189. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22190. ProxyAndTargetServers s;
  22191. auto cli = make_client("example.com.", s);
  22192. cli->set_no_proxy({"example.com"});
  22193. auto res = cli->Get("/");
  22194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22195. EXPECT_EQ(0, s.proxy_hits());
  22196. EXPECT_EQ(1, s.target_hits());
  22197. }
  22198. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22199. // Trailing dots must be normalized on BOTH sides — host and entry.
  22200. // An implementation that only strips the host-side trailing dot would
  22201. // fail to match host "example.com" against entry "example.com." because
  22202. // a literal substring search would compare 11 chars against 12.
  22203. ProxyAndTargetServers s;
  22204. auto cli = make_client("example.com", s);
  22205. cli->set_no_proxy({"example.com."});
  22206. auto res = cli->Get("/");
  22207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22208. EXPECT_EQ(0, s.proxy_hits());
  22209. EXPECT_EQ(1, s.target_hits());
  22210. }
  22211. TEST(NoProxyTest, WildcardBypassesEverything) {
  22212. ProxyAndTargetServers s;
  22213. auto cli = make_client("anything.invalid.test", s);
  22214. cli->set_no_proxy({"*"});
  22215. auto res = cli->Get("/");
  22216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22217. EXPECT_EQ(0, s.proxy_hits());
  22218. EXPECT_EQ(1, s.target_hits());
  22219. }
  22220. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22221. ProxyAndTargetServers s;
  22222. Client cli("127.0.0.1", s.target_port());
  22223. cli.set_proxy("127.0.0.1", s.proxy_port());
  22224. cli.set_no_proxy({"127.0.0.1"});
  22225. auto res = cli.Get("/");
  22226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22227. EXPECT_EQ(0, s.proxy_hits());
  22228. EXPECT_EQ(1, s.target_hits());
  22229. }
  22230. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22231. ProxyAndTargetServers s;
  22232. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22233. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22234. cli.set_proxy("127.0.0.1", s.proxy_port());
  22235. cli.set_no_proxy({"::1"});
  22236. auto res = cli.Get("/");
  22237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22238. EXPECT_EQ(0, s.proxy_hits());
  22239. EXPECT_EQ(1, s.target_hits());
  22240. }
  22241. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22242. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22243. // must still be recognized as IPv6 for CIDR matching. Implementations
  22244. // that detect IPv6 only when the host begins with '[' would parse the
  22245. // host as a hostname and miss the match.
  22246. ProxyAndTargetServers s;
  22247. Client cli("fe80::1", s.target_port());
  22248. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22249. cli.set_proxy("127.0.0.1", s.proxy_port());
  22250. cli.set_no_proxy({"fe80::/10"});
  22251. auto res = cli.Get("/");
  22252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22253. EXPECT_EQ(0, s.proxy_hits());
  22254. EXPECT_EQ(1, s.target_hits());
  22255. }
  22256. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22257. ProxyAndTargetServers s;
  22258. Client cli("::1", s.target_port());
  22259. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22260. cli.set_proxy("127.0.0.1", s.proxy_port());
  22261. cli.set_no_proxy({"[::1]"});
  22262. auto res = cli.Get("/");
  22263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22264. EXPECT_EQ(0, s.proxy_hits());
  22265. EXPECT_EQ(1, s.target_hits());
  22266. }
  22267. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  22268. ProxyAndTargetServers s;
  22269. Client cli("fe80::1", s.target_port());
  22270. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22271. cli.set_proxy("127.0.0.1", s.proxy_port());
  22272. cli.set_no_proxy({"[fe80::]/10"});
  22273. auto res = cli.Get("/");
  22274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22275. EXPECT_EQ(0, s.proxy_hits());
  22276. EXPECT_EQ(1, s.target_hits());
  22277. }
  22278. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22279. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22280. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22281. // tricks via address-family conversion.
  22282. ProxyAndTargetServers s;
  22283. Client cli("::ffff:127.0.0.1", s.target_port());
  22284. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22285. cli.set_proxy("127.0.0.1", s.proxy_port());
  22286. cli.set_no_proxy({"127.0.0.1"});
  22287. auto res = cli.Get("/");
  22288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22289. EXPECT_GE(s.proxy_hits(), 1);
  22290. EXPECT_EQ(0, s.target_hits());
  22291. }
  22292. TEST(NoProxyTest, IPv4CidrMatch) {
  22293. ProxyAndTargetServers s;
  22294. Client cli("127.0.0.1", s.target_port());
  22295. cli.set_proxy("127.0.0.1", s.proxy_port());
  22296. cli.set_no_proxy({"127.0.0.0/8"});
  22297. auto res = cli.Get("/");
  22298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22299. EXPECT_EQ(0, s.proxy_hits());
  22300. EXPECT_EQ(1, s.target_hits());
  22301. }
  22302. TEST(NoProxyTest, IPv4CidrNonMatch) {
  22303. ProxyAndTargetServers s;
  22304. Client cli("127.0.0.1", s.target_port());
  22305. cli.set_proxy("127.0.0.1", s.proxy_port());
  22306. cli.set_no_proxy({"10.0.0.0/8"});
  22307. auto res = cli.Get("/");
  22308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22309. EXPECT_GE(s.proxy_hits(), 1);
  22310. EXPECT_EQ(0, s.target_hits());
  22311. }
  22312. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  22313. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  22314. // IPv4 target matches.
  22315. ProxyAndTargetServers s;
  22316. Client cli("127.0.0.1", s.target_port());
  22317. cli.set_proxy("127.0.0.1", s.proxy_port());
  22318. cli.set_no_proxy({"0.0.0.0/0"});
  22319. auto res = cli.Get("/");
  22320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22321. EXPECT_EQ(0, s.proxy_hits());
  22322. EXPECT_EQ(1, s.target_hits());
  22323. }
  22324. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  22325. ProxyAndTargetServers s;
  22326. Client cli("127.0.0.1", s.target_port());
  22327. cli.set_proxy("127.0.0.1", s.proxy_port());
  22328. cli.set_no_proxy({"127.0.0.1"});
  22329. auto res = cli.Get("/");
  22330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22331. EXPECT_EQ(0, s.proxy_hits());
  22332. EXPECT_EQ(1, s.target_hits());
  22333. }
  22334. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  22335. ProxyAndTargetServers s;
  22336. Client cli("127.0.0.1", s.target_port());
  22337. cli.set_proxy("127.0.0.1", s.proxy_port());
  22338. cli.set_no_proxy({"127.0.0.0/33"});
  22339. auto res = cli.Get("/");
  22340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22341. EXPECT_GE(s.proxy_hits(), 1);
  22342. EXPECT_EQ(0, s.target_hits());
  22343. }
  22344. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  22345. // Empty prefix after the slash must be rejected, not silently treated as /32.
  22346. ProxyAndTargetServers s;
  22347. Client cli("127.0.0.1", s.target_port());
  22348. cli.set_proxy("127.0.0.1", s.proxy_port());
  22349. cli.set_no_proxy({"127.0.0.1/"});
  22350. auto res = cli.Get("/");
  22351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22352. EXPECT_GE(s.proxy_hits(), 1);
  22353. EXPECT_EQ(0, s.target_hits());
  22354. }
  22355. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  22356. ProxyAndTargetServers s;
  22357. auto cli = make_client("internal.corp", s);
  22358. cli->set_proxy_basic_auth("u", "p");
  22359. cli->set_no_proxy({"internal.corp"});
  22360. auto res = cli->Get("/");
  22361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22362. EXPECT_EQ(1, s.target_hits());
  22363. EXPECT_EQ(0, s.proxy_hits());
  22364. EXPECT_FALSE(s.last_had_proxy_authz())
  22365. << "Proxy-Authorization must not be sent direct to the target";
  22366. }
  22367. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  22368. ProxyAndTargetServers s;
  22369. auto cli = make_client("public.example", s);
  22370. cli->set_proxy_basic_auth("u", "p");
  22371. cli->set_no_proxy({"internal.corp"}); // does not match
  22372. auto res = cli->Get("/");
  22373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22374. EXPECT_GE(s.proxy_hits(), 1);
  22375. EXPECT_TRUE(s.last_had_proxy_authz());
  22376. }
  22377. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  22378. ProxyAndTargetServers s;
  22379. auto cli = make_client("anything.test", s);
  22380. auto res = cli->Get("/");
  22381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22382. EXPECT_GE(s.proxy_hits(), 1);
  22383. EXPECT_EQ(0, s.target_hits());
  22384. }
  22385. TEST(NoProxyTest, PortSpecificEntryRejected) {
  22386. ProxyAndTargetServers s;
  22387. auto cli = make_client("example.com", s);
  22388. cli->set_no_proxy({"example.com:8080"});
  22389. auto res = cli->Get("/");
  22390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22391. EXPECT_GE(s.proxy_hits(), 1);
  22392. EXPECT_EQ(0, s.target_hits());
  22393. }
  22394. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  22395. ProxyAndTargetServers s;
  22396. auto cli = make_client("anything.test", s);
  22397. cli->set_no_proxy({"", " ", "\t"});
  22398. auto res = cli->Get("/");
  22399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22400. EXPECT_GE(s.proxy_hits(), 1);
  22401. EXPECT_EQ(0, s.target_hits());
  22402. }
  22403. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  22404. // An entry with leading/trailing whitespace must still match — env-style
  22405. // values are commonly pasted with stray spaces and an implementation
  22406. // that feeds the raw token directly to inet_pton would fail to match
  22407. // valid CIDRs because of the spaces.
  22408. ProxyAndTargetServers s;
  22409. Client cli("127.0.0.1", s.target_port());
  22410. cli.set_proxy("127.0.0.1", s.proxy_port());
  22411. cli.set_no_proxy({" 127.0.0.0/8 "});
  22412. auto res = cli.Get("/");
  22413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22414. EXPECT_EQ(0, s.proxy_hits());
  22415. EXPECT_EQ(1, s.target_hits());
  22416. }
  22417. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  22418. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  22419. // go direct and must NOT carry Proxy-Authorization.
  22420. std::atomic<int> proxy_hits{0};
  22421. std::atomic<int> target_hits{0};
  22422. std::atomic<bool> target_saw_authz{false};
  22423. no_proxy_test::ScopedServer proxy_mock, target;
  22424. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22425. proxy_hits++;
  22426. res.status = 302;
  22427. res.set_header("Location", "http://127.0.0.1:" +
  22428. std::to_string(target.port()) + "/landed");
  22429. });
  22430. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22431. target_hits++;
  22432. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  22433. res.set_content("direct", "text/plain");
  22434. });
  22435. proxy_mock.listen();
  22436. target.listen();
  22437. Client cli("public.example", target.port());
  22438. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22439. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22440. cli.set_proxy_basic_auth("u", "p");
  22441. cli.set_no_proxy({"127.0.0.1"});
  22442. cli.set_follow_location(true);
  22443. auto res = cli.Get("/redir");
  22444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22445. EXPECT_GE(proxy_hits.load(), 1);
  22446. EXPECT_GE(target_hits.load(), 1);
  22447. EXPECT_FALSE(target_saw_authz.load());
  22448. }
  22449. #ifdef CPPHTTPLIB_SSL_ENABLED
  22450. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  22451. // Direct origin replying 407 must not trigger the digest retry; otherwise
  22452. // proxy creds would be sent to the (possibly hostile) origin.
  22453. std::atomic<int> target_hits{0};
  22454. std::atomic<bool> target_saw_proxy_authz{false};
  22455. no_proxy_test::ScopedServer target;
  22456. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22457. target_hits++;
  22458. if (req.has_header("Proxy-Authorization")) {
  22459. target_saw_proxy_authz = true;
  22460. }
  22461. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22462. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  22463. "nonce=\"abc\", algorithm=MD5");
  22464. });
  22465. target.listen();
  22466. // The proxy address is set to the target's port: the bypass MUST kick in;
  22467. // if it doesn't, the test still routes "via proxy" to the same server and
  22468. // the Proxy-Authorization assertion below catches the leak.
  22469. Client cli("evil.example", target.port());
  22470. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  22471. cli.set_proxy("127.0.0.1", target.port());
  22472. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22473. cli.set_no_proxy({"evil.example"});
  22474. auto res = cli.Get("/x");
  22475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22476. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22477. EXPECT_EQ(1, target_hits.load());
  22478. EXPECT_FALSE(target_saw_proxy_authz.load());
  22479. }
  22480. #endif
  22481. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  22482. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  22483. std::atomic<int> proxy_hits{0};
  22484. std::atomic<int> bypass_hits{0};
  22485. std::atomic<bool> proxy_saw_c_url{false};
  22486. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  22487. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22488. proxy_hits++;
  22489. if (req.path.find("/start") != std::string::npos) {
  22490. res.status = 302;
  22491. res.set_header("Location", "http://127.0.0.1:" +
  22492. std::to_string(bypass_server.port()) +
  22493. "/middle");
  22494. return;
  22495. }
  22496. if (req.path.find("/end") != std::string::npos) {
  22497. proxy_saw_c_url = true;
  22498. res.set_content("c-via-proxy", "text/plain");
  22499. return;
  22500. }
  22501. res.set_content("unexpected", "text/plain");
  22502. });
  22503. // public.example's "advertised" port is arbitrary (the request never lands
  22504. // there — it goes through the proxy), but use a dynamic value to stay
  22505. // friendly with sharded parallel runs.
  22506. int public_port = bypass_server.port();
  22507. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  22508. bypass_hits++;
  22509. res.status = 302;
  22510. res.set_header("Location", "http://public.example:" +
  22511. std::to_string(public_port) + "/end");
  22512. });
  22513. proxy_mock.listen();
  22514. bypass_server.listen();
  22515. Client cli("public.example", public_port);
  22516. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22517. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22518. cli.set_no_proxy({"127.0.0.1"});
  22519. cli.set_follow_location(true);
  22520. auto res = cli.Get("/start");
  22521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22522. EXPECT_EQ(StatusCode::OK_200, res->status);
  22523. EXPECT_EQ("c-via-proxy", res->body);
  22524. EXPECT_GE(proxy_hits.load(), 2);
  22525. EXPECT_GE(bypass_hits.load(), 1);
  22526. EXPECT_TRUE(proxy_saw_c_url.load());
  22527. }
  22528. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  22529. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  22530. // request reconnects to the correct endpoint.
  22531. std::atomic<int> proxy_hits{0};
  22532. std::atomic<int> target_hits{0};
  22533. no_proxy_test::ScopedServer proxy_mock, target;
  22534. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22535. proxy_hits++;
  22536. res.set_content("via-proxy", "text/plain");
  22537. });
  22538. target.svr().Get(".*", [&](const Request &, Response &res) {
  22539. target_hits++;
  22540. res.set_content("direct", "text/plain");
  22541. });
  22542. proxy_mock.listen();
  22543. target.listen();
  22544. Client cli("public.example", target.port());
  22545. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22546. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22547. cli.set_keep_alive(true);
  22548. auto res1 = cli.Get("/a");
  22549. ASSERT_TRUE(res1);
  22550. EXPECT_EQ("via-proxy", res1->body);
  22551. EXPECT_EQ(1, proxy_hits.load());
  22552. EXPECT_EQ(0, target_hits.load());
  22553. cli.set_no_proxy({"public.example"});
  22554. auto res2 = cli.Get("/b");
  22555. ASSERT_TRUE(res2);
  22556. EXPECT_EQ("direct", res2->body);
  22557. EXPECT_EQ(1, proxy_hits.load());
  22558. EXPECT_EQ(1, target_hits.load());
  22559. }
  22560. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  22561. namespace proxy_tunnel_test {
  22562. // SSLServer counterpart to no_proxy_test::ScopedServer.
  22563. class ScopedSSLServer {
  22564. public:
  22565. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  22566. port_ = svr_.bind_to_any_port("127.0.0.1");
  22567. }
  22568. ~ScopedSSLServer() {
  22569. svr_.stop();
  22570. if (th_.joinable()) { th_.join(); }
  22571. }
  22572. SSLServer &svr() { return svr_; }
  22573. int port() const { return port_; }
  22574. void listen() {
  22575. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22576. svr_.wait_until_ready();
  22577. }
  22578. private:
  22579. SSLServer svr_;
  22580. std::thread th_;
  22581. int port_ = 0;
  22582. };
  22583. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  22584. class ScopedConnectProxy {
  22585. public:
  22586. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  22587. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  22588. if (listen_fd_ < 0) { return; }
  22589. int yes = 1;
  22590. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  22591. sockaddr_in a{};
  22592. a.sin_family = AF_INET;
  22593. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22594. a.sin_port = 0;
  22595. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  22596. return;
  22597. }
  22598. socklen_t alen = sizeof(a);
  22599. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  22600. 0) {
  22601. return;
  22602. }
  22603. port_ = ntohs(a.sin_port);
  22604. if (::listen(listen_fd_, 1) != 0) { return; }
  22605. th_ = std::thread([this] { run(); });
  22606. }
  22607. ~ScopedConnectProxy() {
  22608. stop_ = true;
  22609. if (listen_fd_ >= 0) {
  22610. ::shutdown(listen_fd_, SHUT_RDWR);
  22611. ::close(listen_fd_);
  22612. }
  22613. if (th_.joinable()) { th_.join(); }
  22614. }
  22615. int port() const { return port_; }
  22616. int connect_hits() const { return connect_hits_.load(); }
  22617. // Head of the last CONNECT request, as the proxy saw it on the wire.
  22618. std::string connect_request() const {
  22619. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22620. return connect_request_;
  22621. }
  22622. private:
  22623. void run() {
  22624. while (!stop_.load()) {
  22625. fd_set rfds;
  22626. FD_ZERO(&rfds);
  22627. FD_SET(listen_fd_, &rfds);
  22628. timeval tv{0, 100 * 1000};
  22629. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  22630. if (sel <= 0) { continue; }
  22631. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  22632. if (client_fd < 0) { continue; }
  22633. std::string req;
  22634. char buf[2048];
  22635. while (req.find("\r\n\r\n") == std::string::npos) {
  22636. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  22637. if (n <= 0) { break; }
  22638. req.append(buf, static_cast<size_t>(n));
  22639. }
  22640. if (req.compare(0, 7, "CONNECT") != 0) {
  22641. ::close(client_fd);
  22642. continue;
  22643. }
  22644. connect_hits_++;
  22645. {
  22646. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22647. connect_request_ = req;
  22648. }
  22649. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  22650. ::send(client_fd, ok, std::strlen(ok), 0);
  22651. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  22652. sockaddr_in o{};
  22653. o.sin_family = AF_INET;
  22654. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22655. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  22656. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  22657. 0) {
  22658. ::close(client_fd);
  22659. ::close(origin_fd);
  22660. continue;
  22661. }
  22662. auto forward = [](int from, int to) {
  22663. char b[8192];
  22664. for (;;) {
  22665. ssize_t n = ::recv(from, b, sizeof(b), 0);
  22666. if (n <= 0) { break; }
  22667. ssize_t off = 0;
  22668. while (off < n) {
  22669. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  22670. if (s <= 0) {
  22671. off = n;
  22672. break;
  22673. }
  22674. off += s;
  22675. }
  22676. }
  22677. ::shutdown(to, SHUT_WR);
  22678. };
  22679. std::thread t1([&] { forward(client_fd, origin_fd); });
  22680. std::thread t2([&] { forward(origin_fd, client_fd); });
  22681. t1.join();
  22682. t2.join();
  22683. ::close(client_fd);
  22684. ::close(origin_fd);
  22685. }
  22686. }
  22687. int forward_port_ = -1;
  22688. int listen_fd_ = -1;
  22689. int port_ = 0;
  22690. std::thread th_;
  22691. std::atomic<bool> stop_{false};
  22692. std::atomic<int> connect_hits_{0};
  22693. mutable std::mutex connect_request_mutex_;
  22694. std::string connect_request_;
  22695. };
  22696. // Sends one request through the CONNECT proxy to the TLS origin with a
  22697. // credential configured for each hop, and checks that each credential reaches
  22698. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22699. // origin's (every header in origin_headers) on the tunnelled request.
  22700. void CredentialsStayWithTheirHop(
  22701. const std::function<void(SSLClient &)> &set_credentials,
  22702. const std::string &scheme,
  22703. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22704. std::atomic<int> origin_hits{0};
  22705. std::atomic<bool> origin_saw_proxy_authz{false};
  22706. std::atomic<bool> origin_saw_headers{false};
  22707. ScopedSSLServer origin;
  22708. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22709. origin_hits++;
  22710. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22711. origin_saw_headers =
  22712. std::all_of(origin_headers.begin(), origin_headers.end(),
  22713. [&](const std::string &h) { return req.has_header(h); });
  22714. res.set_content("ok", "text/plain");
  22715. });
  22716. origin.listen();
  22717. ScopedConnectProxy proxy(origin.port());
  22718. ASSERT_NE(0, proxy.port());
  22719. // Pinned to 127.0.0.1 for the same reason as the test below.
  22720. SSLClient cli("127.0.0.1", origin.port());
  22721. cli.enable_server_certificate_verification(false);
  22722. cli.set_proxy("127.0.0.1", proxy.port());
  22723. set_credentials(cli);
  22724. auto res = cli.Get("/x");
  22725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22726. EXPECT_EQ(StatusCode::OK_200, res->status);
  22727. EXPECT_EQ(1, origin_hits.load());
  22728. EXPECT_EQ(1, proxy.connect_hits());
  22729. EXPECT_TRUE(origin_saw_headers.load());
  22730. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22731. << "Proxy-Authorization must not be sent inside the tunnel";
  22732. auto connect_req = proxy.connect_request();
  22733. EXPECT_NE(std::string::npos,
  22734. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22735. for (const auto &h : origin_headers) {
  22736. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22737. << h << " must not be sent to the proxy on CONNECT";
  22738. }
  22739. }
  22740. } // namespace proxy_tunnel_test
  22741. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22742. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22743. [](SSLClient &cli) {
  22744. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22745. cli.set_basic_auth("origin-user", "origin-pass");
  22746. },
  22747. "Basic");
  22748. }
  22749. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22750. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22751. [](SSLClient &cli) {
  22752. cli.set_proxy_bearer_token_auth("proxy-token");
  22753. cli.set_bearer_token_auth("origin-token");
  22754. },
  22755. "Bearer");
  22756. }
  22757. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22758. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22759. [](SSLClient &cli) {
  22760. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22761. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22762. {"Cookie", "sid=origin-session"},
  22763. {"X-Api-Key", "origin-key"}});
  22764. },
  22765. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22766. }
  22767. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22768. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22769. // retry; otherwise proxy creds would be sent to the origin.
  22770. std::atomic<int> origin_hits{0};
  22771. std::atomic<bool> origin_saw_proxy_authz{false};
  22772. proxy_tunnel_test::ScopedSSLServer origin;
  22773. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22774. origin_hits++;
  22775. if (req.has_header("Proxy-Authorization")) {
  22776. origin_saw_proxy_authz = true;
  22777. }
  22778. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22779. res.set_header("Proxy-Authenticate",
  22780. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22781. "algorithm=MD5");
  22782. });
  22783. origin.listen();
  22784. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22785. ASSERT_NE(0, proxy.port());
  22786. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22787. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22788. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22789. // and answer with its own status, making this test flaky.
  22790. SSLClient cli("127.0.0.1", origin.port());
  22791. cli.enable_server_certificate_verification(false);
  22792. cli.set_proxy("127.0.0.1", proxy.port());
  22793. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22794. auto res = cli.Get("/x");
  22795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22796. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22797. EXPECT_EQ(1, origin_hits.load());
  22798. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22799. EXPECT_EQ(1, proxy.connect_hits());
  22800. }
  22801. #endif