test.cc 773 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080
  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_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(ClientTest, MoveConstructible) {
  305. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  306. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  307. }
  308. TEST(ClientTest, MoveAssignable) {
  309. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  310. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  311. }
  312. #ifdef _WIN32
  313. TEST(StartupTest, WSAStartup) {
  314. WSADATA wsaData;
  315. int ret = WSAStartup(0x0002, &wsaData);
  316. ASSERT_EQ(0, ret);
  317. }
  318. #endif
  319. TEST(DecodePathTest, PercentCharacter) {
  320. EXPECT_EQ(
  321. decode_path_component(
  322. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  323. U8("descrip=Gastos áéíóúñÑ 6"));
  324. }
  325. TEST(DecodePathTest, PercentCharacterNUL) {
  326. string expected;
  327. expected.push_back('x');
  328. expected.push_back('\0');
  329. expected.push_back('x');
  330. EXPECT_EQ(decode_path_component("x%00x"), expected);
  331. }
  332. TEST(DecodePathTest, UnicodeEncoding) {
  333. // %u0041 = 'A' (1-byte UTF-8)
  334. EXPECT_EQ("A", decode_path_component("%u0041"));
  335. // %u00E9 = 'é' (2-byte UTF-8)
  336. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  337. // %u3042 = 'あ' (3-byte UTF-8)
  338. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  339. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  340. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  341. // %uD800 = surrogate (invalid, silently dropped)
  342. EXPECT_EQ("", decode_path_component("%uD800"));
  343. }
  344. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  345. // A sign or whitespace inside the two-character escape window must not be
  346. // accepted as a valid percent-encoding; the sequence is passed through
  347. // literally, matching decode_uri_component / decode_path_component.
  348. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  349. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  350. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  351. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  352. // Well-formed escapes still decode.
  353. EXPECT_EQ("-", decode_query_component("%2D", false));
  354. EXPECT_EQ("A", decode_query_component("%41", false));
  355. }
  356. TEST(SanitizeFilenameTest, VariousPatterns) {
  357. // Path traversal
  358. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  359. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  360. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  361. // Normal and edge cases
  362. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  363. EXPECT_EQ("filename.txt",
  364. httplib::sanitize_filename("/path/to/filename.txt"));
  365. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  366. EXPECT_EQ("", httplib::sanitize_filename(".."));
  367. EXPECT_EQ("", httplib::sanitize_filename(""));
  368. // Null bytes stripped
  369. EXPECT_EQ("safe.txt",
  370. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  371. // Whitespace-only rejected
  372. EXPECT_EQ("", httplib::sanitize_filename(" "));
  373. }
  374. // Forward declaration (see the base64_encode note below): split builds move the
  375. // definition into httplib.cc, so re-declaring it here lets the test link.
  376. namespace httplib {
  377. namespace detail {
  378. bool is_chunked_transfer_encoding(const Headers &headers);
  379. } // namespace detail
  380. } // namespace httplib
  381. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  382. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  383. auto make = [](std::initializer_list<const char *> lines) {
  384. Headers h;
  385. for (auto te : lines) {
  386. if (te) { h.emplace("Transfer-Encoding", te); }
  387. }
  388. return h;
  389. };
  390. // Sole coding, matched case-insensitively.
  391. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  392. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  393. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  394. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  395. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  396. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  397. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  398. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  399. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  400. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  401. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  402. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  403. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  404. // were received, into one list. Headers preserves that order, so the answer
  405. // is decided by the last coding of the last line and the order the lines
  406. // arrived in is significant.
  407. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  408. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  409. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  410. // The split can fall anywhere in the list.
  411. EXPECT_TRUE(
  412. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  413. EXPECT_FALSE(
  414. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  415. // A trailing line naming no coding leaves the list ending in nothing, so it
  416. // must not inherit the chunked from the line before it.
  417. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  418. }
  419. // Forward declaration: in split builds split.py strips `inline` and moves the
  420. // definition into httplib.cc, so detail::base64_encode is not visible from the
  421. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  422. // in both header-only and split builds.
  423. namespace httplib {
  424. namespace detail {
  425. std::string base64_encode(const std::string &in);
  426. } // namespace detail
  427. } // namespace httplib
  428. TEST(Base64EncodeTest, KnownAnswers) {
  429. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  430. // where the accumulator's top bit is already set before the next shift.
  431. EXPECT_EQ("", detail::base64_encode(""));
  432. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  433. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  434. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  435. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  436. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  437. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  438. // High bytes keep the top bit set across several rounds.
  439. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  440. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  441. }
  442. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  447. string reservedCharacters = ";,/?:@&=+$";
  448. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  449. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  450. }
  451. TEST(ClientQueryOrder, PreserveOrder) {
  452. // This test reproduces Issue #2259: client may reorder query parameters
  453. // when sending a GET request. The expected behavior is that the client
  454. // preserves the original query string order when the caller supplied it
  455. // as part of the path.
  456. Server svr;
  457. svr.Get("/", [&](const Request &req, Response &res) {
  458. // Echo back the raw target so the test can assert ordering
  459. res.set_content(req.target, "text/plain");
  460. });
  461. std::thread t{[&] { svr.listen(HOST, PORT); }};
  462. auto se = detail::scope_exit([&] {
  463. svr.stop();
  464. t.join();
  465. ASSERT_FALSE(svr.is_running());
  466. });
  467. svr.wait_until_ready();
  468. Client cli(HOST, PORT);
  469. ASSERT_TRUE(cli.is_valid());
  470. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  471. auto res = cli.Get(original);
  472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  473. // Expect the echoed target to exactly match the original path (order
  474. // preserved)
  475. EXPECT_EQ(res->body, original);
  476. }
  477. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  478. string chineseCharacters = U8("中国語");
  479. string russianCharacters = U8("дом");
  480. string brazilianCharacters = U8("óculos");
  481. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  482. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  483. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  484. "%D0%B4%D0%BE%D0%BC");
  485. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  486. }
  487. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  488. string unescapedCharacters = "-_.!~*'()";
  489. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  490. }
  491. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  492. string reservedCharacters = ";,/?:@&=+$";
  493. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  494. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  495. }
  496. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  497. string chineseCharacters = U8("中国語");
  498. string russianCharacters = U8("дом");
  499. string brazilianCharacters = U8("óculos");
  500. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  501. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  502. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  503. "%D0%B4%D0%BE%D0%BC");
  504. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  505. }
  506. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  507. // Issue #2082 use case: encoding path component with ampersand
  508. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  509. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  510. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  511. }
  512. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  513. string unescapedCharacters = "-_.!~*'()";
  514. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  515. }
  516. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  517. string reservedCharacters = ";,/?:@&=+$#";
  518. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  519. }
  520. TEST(EncodeUriTest, TestUTF8Characters) {
  521. string chineseCharacters = U8("中国語");
  522. string russianCharacters = U8("дом");
  523. string brazilianCharacters = U8("óculos");
  524. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  525. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  526. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  527. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  528. }
  529. TEST(EncodeUriTest, TestCompleteUri) {
  530. string uri =
  531. "https://example.com/path/to/resource?query=value&param=test#fragment";
  532. EXPECT_EQ(
  533. httplib::encode_uri(uri),
  534. "https://example.com/path/to/resource?query=value&param=test#fragment");
  535. }
  536. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  537. string uri =
  538. "https://example.com/path with spaces/file name.html?q=hello world";
  539. EXPECT_EQ(httplib::encode_uri(uri),
  540. "https://example.com/path%20with%20spaces/"
  541. "file%20name.html?q=hello%20world");
  542. }
  543. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  544. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  545. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  546. }
  547. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  548. string unescapedCharacters = "-_.!~*'()";
  549. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  550. }
  551. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  552. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  553. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  554. string encodedBrazilian = "%C3%B3culos";
  555. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  556. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  557. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  558. }
  559. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  560. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  561. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  562. "Piri Tommy Villiers - on & on");
  563. }
  564. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  565. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  566. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  567. }
  568. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  569. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  570. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  571. }
  572. TEST(DecodeUriTest, TestUTF8Characters) {
  573. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  574. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  575. string encodedBrazilian = "%C3%B3culos";
  576. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  577. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  578. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  579. }
  580. TEST(DecodeUriTest, TestCompleteUri) {
  581. string encodedUri = "https://example.com/path%20with%20spaces/"
  582. "file%20name.html?q=hello%20world";
  583. EXPECT_EQ(
  584. httplib::decode_uri(encodedUri),
  585. "https://example.com/path with spaces/file name.html?q=hello world");
  586. }
  587. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  588. string original =
  589. "https://example.com/path with spaces/file name.html?q=hello world";
  590. string encoded = httplib::encode_uri(original);
  591. string decoded = httplib::decode_uri(encoded);
  592. EXPECT_EQ(decoded, original);
  593. }
  594. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  595. // decode_uri is the inverse of encode_uri: an escaped reserved character
  596. // stays encoded so it is not promoted into a real delimiter, while
  597. // non-reserved escapes still decode (like JS decodeURI).
  598. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  599. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  600. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  601. "%3F%3A%40%26%3D%2B%24%2C%3B");
  602. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  603. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  604. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  605. "http://example.com/a%2Fb");
  606. // decode_uri_component still decodes the reserved character.
  607. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  608. }
  609. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  610. string original = "Piri Tommy Villiers - on & on";
  611. string encoded = httplib::encode_uri_component(original);
  612. string decoded = httplib::decode_uri_component(encoded);
  613. EXPECT_EQ(decoded, original);
  614. }
  615. TEST(TrimTests, TrimStringTests) {
  616. EXPECT_EQ("abc", detail::trim_copy("abc"));
  617. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  618. EXPECT_TRUE(detail::trim_copy("").empty());
  619. }
  620. TEST(AsciiTest, LocaleIndependentClassification) {
  621. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  622. // which consult the global C locale: std::isalnum(0xC5) can return true
  623. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  624. // helpers must classify every byte by the ASCII grammar alone.
  625. for (int i = 0; i < 256; i++) {
  626. auto c = static_cast<char>(i);
  627. auto is_digit = i >= '0' && i <= '9';
  628. auto is_upper = i >= 'A' && i <= 'Z';
  629. auto is_lower = i >= 'a' && i <= 'z';
  630. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  631. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  632. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  633. << "byte " << i;
  634. }
  635. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  636. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  637. // Non-ASCII bytes must be percent-encoded, never passed through as
  638. // alphanumeric.
  639. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  640. }
  641. TEST(FromCharsTest, Double) {
  642. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  643. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  644. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  645. auto parse = [](const std::string &s, double &v) {
  646. return detail::from_chars(s.data(), s.data() + s.size(), v);
  647. };
  648. double v = -1.0;
  649. // Representative quality values.
  650. EXPECT_EQ(parse("0", v).ec, std::errc{});
  651. EXPECT_DOUBLE_EQ(v, 0.0);
  652. EXPECT_EQ(parse("1", v).ec, std::errc{});
  653. EXPECT_DOUBLE_EQ(v, 1.0);
  654. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  655. EXPECT_DOUBLE_EQ(v, 0.8);
  656. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  657. EXPECT_DOUBLE_EQ(v, 0.001);
  658. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  659. EXPECT_DOUBLE_EQ(v, 1.0);
  660. // A missing integer or fractional part is tolerated.
  661. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  662. EXPECT_DOUBLE_EQ(v, 0.5);
  663. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  664. EXPECT_DOUBLE_EQ(v, 5.0);
  665. // Values outside [0, 1] still parse; the caller range-checks them.
  666. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  667. EXPECT_DOUBLE_EQ(v, 123.456);
  668. // Stops at the first byte that is not part of the number and reports where.
  669. std::string trailing = "0.9, text/html";
  670. auto r = parse(trailing, v);
  671. EXPECT_EQ(r.ec, std::errc{});
  672. EXPECT_DOUBLE_EQ(v, 0.9);
  673. EXPECT_EQ(*r.ptr, ',');
  674. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  675. // outright, and an 'e'/'E' simply ends the number.
  676. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  677. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  678. std::string exp_input = "1.5e3";
  679. r = parse(exp_input, v);
  680. EXPECT_EQ(r.ec, std::errc{});
  681. EXPECT_DOUBLE_EQ(v, 1.5);
  682. EXPECT_EQ(*r.ptr, 'e');
  683. // Invalid inputs.
  684. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  685. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  686. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  687. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  688. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  689. // Pathological but well-formed inputs must stay bounded (no overflow, no
  690. // out-of-bounds table access) and stay within [0, 1] for the caller.
  691. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  692. std::errc{});
  693. EXPECT_DOUBLE_EQ(v, 0.0);
  694. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  695. std::errc{});
  696. EXPECT_GE(v, 0.0);
  697. EXPECT_LE(v, 1.0);
  698. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  699. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  700. }
  701. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  702. // Simple case without quality values
  703. std::vector<std::string> result1;
  704. EXPECT_TRUE(detail::parse_accept_header(
  705. "text/html,application/json,text/plain", result1));
  706. EXPECT_EQ(result1.size(), 3U);
  707. EXPECT_EQ(result1[0], "text/html");
  708. EXPECT_EQ(result1[1], "application/json");
  709. EXPECT_EQ(result1[2], "text/plain");
  710. // With quality values
  711. std::vector<std::string> result2;
  712. EXPECT_TRUE(detail::parse_accept_header(
  713. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  714. EXPECT_EQ(result2.size(), 3U);
  715. EXPECT_EQ(result2[0], "application/json"); // highest q value
  716. EXPECT_EQ(result2[1], "text/html");
  717. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  718. }
  719. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  720. // Mixed with and without quality values
  721. std::vector<std::string> result;
  722. EXPECT_TRUE(detail::parse_accept_header(
  723. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  724. EXPECT_EQ(result.size(), 3U);
  725. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  726. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  727. EXPECT_EQ(result[2], "application/json"); // q=0.5
  728. }
  729. TEST(ParseAcceptHeaderTest, EdgeCases) {
  730. // Empty header
  731. std::vector<std::string> empty_result;
  732. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  733. EXPECT_TRUE(empty_result.empty());
  734. // Single type
  735. std::vector<std::string> single_result;
  736. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  737. EXPECT_EQ(single_result.size(), 1U);
  738. EXPECT_EQ(single_result[0], "application/json");
  739. // Wildcard types
  740. std::vector<std::string> wildcard_result;
  741. EXPECT_TRUE(detail::parse_accept_header(
  742. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  743. EXPECT_EQ(wildcard_result.size(), 3U);
  744. EXPECT_EQ(wildcard_result[0], "application/json");
  745. EXPECT_EQ(wildcard_result[1], "text/*");
  746. EXPECT_EQ(wildcard_result[2], "*/*");
  747. }
  748. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  749. // Common browser Accept header
  750. std::vector<std::string> browser_result;
  751. EXPECT_TRUE(
  752. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  753. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  754. browser_result));
  755. EXPECT_EQ(browser_result.size(), 6U);
  756. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  757. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  758. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  759. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  760. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  761. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  762. // API client header
  763. std::vector<std::string> api_result;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  766. api_result));
  767. EXPECT_EQ(api_result.size(), 3U);
  768. EXPECT_EQ(api_result[0], "application/json");
  769. EXPECT_EQ(api_result[1], "application/xml");
  770. EXPECT_EQ(api_result[2], "text/plain");
  771. }
  772. TEST(ParseAcceptHeaderTest, SpecialCases) {
  773. // Quality value with 3 decimal places
  774. std::vector<std::string> decimal_result;
  775. EXPECT_TRUE(detail::parse_accept_header(
  776. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  777. EXPECT_EQ(decimal_result.size(), 2U);
  778. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  779. EXPECT_EQ(decimal_result[1], "text/html");
  780. // Zero quality (should still be included but with lowest priority)
  781. std::vector<std::string> zero_q_result;
  782. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  783. zero_q_result));
  784. EXPECT_EQ(zero_q_result.size(), 2U);
  785. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  786. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  787. // No spaces around commas
  788. std::vector<std::string> no_space_result;
  789. EXPECT_TRUE(detail::parse_accept_header(
  790. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  791. no_space_result));
  792. EXPECT_EQ(no_space_result.size(), 3U);
  793. EXPECT_EQ(no_space_result[0], "text/html");
  794. EXPECT_EQ(no_space_result[1], "application/json");
  795. EXPECT_EQ(no_space_result[2], "text/plain");
  796. }
  797. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  798. // Quality values always use '.' as the decimal separator, so parsing must
  799. // not depend on the process locale. An embedding application may have
  800. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  801. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  802. std::string saved = cur ? cur : "C";
  803. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  804. "fr_FR.UTF-8"};
  805. bool switched = false;
  806. for (const auto loc : comma_locales) {
  807. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  808. std::localeconv()->decimal_point[0] == ',') {
  809. switched = true;
  810. break;
  811. }
  812. }
  813. if (!switched) {
  814. std::setlocale(LC_NUMERIC, saved.c_str());
  815. GTEST_SKIP() << "no comma-decimal locale available on this host";
  816. }
  817. // The higher-weighted type appears later in the list, so a correct parse
  818. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  819. // sensitive parse reads both weights as 0 and leaves the original order.
  820. std::vector<std::string> result;
  821. EXPECT_TRUE(detail::parse_accept_header(
  822. "application/json;q=0.1,text/html;q=0.9", result));
  823. ASSERT_EQ(result.size(), 2U);
  824. EXPECT_EQ(result[0], "text/html");
  825. EXPECT_EQ(result[1], "application/json");
  826. std::setlocale(LC_NUMERIC, saved.c_str());
  827. }
  828. TEST(ParseAcceptHeaderTest, InvalidCases) {
  829. std::vector<std::string> result;
  830. // Invalid quality value (> 1.0)
  831. EXPECT_FALSE(
  832. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  833. // Invalid quality value (< 0.0)
  834. EXPECT_FALSE(
  835. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  836. // Invalid quality value (not a number)
  837. EXPECT_FALSE(detail::parse_accept_header(
  838. "text/html;q=invalid,application/json", result));
  839. // Empty quality value
  840. EXPECT_FALSE(
  841. detail::parse_accept_header("text/html;q=,application/json", result));
  842. // Invalid media type format (no slash and not wildcard)
  843. EXPECT_FALSE(
  844. detail::parse_accept_header("invalidtype,application/json", result));
  845. // Empty media type
  846. result.clear();
  847. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  848. // Only commas
  849. result.clear();
  850. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  851. // Valid cases should still work
  852. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  853. EXPECT_EQ(result.size(), 1U);
  854. EXPECT_EQ(result[0], "*/*");
  855. EXPECT_TRUE(detail::parse_accept_header("*", result));
  856. EXPECT_EQ(result.size(), 1U);
  857. EXPECT_EQ(result[0], "*");
  858. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  859. EXPECT_EQ(result.size(), 1U);
  860. EXPECT_EQ(result[0], "text/*");
  861. }
  862. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  863. Server svr;
  864. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  865. EXPECT_EQ(req.accept_content_types.size(), 3U);
  866. EXPECT_EQ(req.accept_content_types[0], "application/json");
  867. EXPECT_EQ(req.accept_content_types[1], "text/html");
  868. EXPECT_EQ(req.accept_content_types[2], "*/*");
  869. res.set_content("ok", "text/plain");
  870. });
  871. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  872. EXPECT_TRUE(false);
  873. res.set_content("bad request", "text/plain");
  874. });
  875. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  876. auto se = detail::scope_exit([&] {
  877. svr.stop();
  878. listen_thread.join();
  879. ASSERT_FALSE(svr.is_running());
  880. });
  881. svr.wait_until_ready();
  882. Client cli("localhost", PORT);
  883. {
  884. auto res = cli.Get(
  885. "/accept_ok",
  886. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  888. EXPECT_EQ(StatusCode::OK_200, res->status);
  889. }
  890. {
  891. auto res = cli.Get("/accept_bad_request",
  892. Headers{{"Accept", "text/html;q=abc,application/json"}});
  893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  894. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  895. }
  896. }
  897. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  898. Server svr;
  899. svr.Get("/", [](const Request & /*req*/, Response &res) {
  900. res.set_content("ok", "text/plain");
  901. });
  902. std::atomic<int> start_count{0};
  903. std::atomic<bool> running_when_called{false};
  904. svr.set_start_handler([&]() {
  905. running_when_called = svr.is_running();
  906. start_count++;
  907. });
  908. auto port = svr.bind_to_any_port(HOST);
  909. std::thread t([&]() { svr.listen_after_bind(); });
  910. auto se = detail::scope_exit([&] {
  911. svr.stop();
  912. t.join();
  913. ASSERT_FALSE(svr.is_running());
  914. });
  915. svr.wait_until_ready();
  916. // A successful request proves the accept loop is running, which the start
  917. // handler precedes; so by now the handler must have run exactly once.
  918. Client cli(HOST, port);
  919. cli.set_connection_timeout(std::chrono::seconds(5));
  920. auto res = cli.Get("/");
  921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  922. EXPECT_EQ(StatusCode::OK_200, res->status);
  923. EXPECT_EQ(1, start_count.load());
  924. EXPECT_TRUE(running_when_called.load());
  925. }
  926. TEST(DivideTest, DivideStringTests) {
  927. auto divide = [](const std::string &str, char d) {
  928. std::string lhs;
  929. std::string rhs;
  930. detail::divide(str, d,
  931. [&](const char *lhs_data, std::size_t lhs_size,
  932. const char *rhs_data, std::size_t rhs_size) {
  933. lhs.assign(lhs_data, lhs_size);
  934. rhs.assign(rhs_data, rhs_size);
  935. });
  936. return std::make_pair(std::move(lhs), std::move(rhs));
  937. };
  938. {
  939. const auto res = divide("", '=');
  940. EXPECT_EQ(res.first, "");
  941. EXPECT_EQ(res.second, "");
  942. }
  943. {
  944. const auto res = divide("=", '=');
  945. EXPECT_EQ(res.first, "");
  946. EXPECT_EQ(res.second, "");
  947. }
  948. {
  949. const auto res = divide(" ", '=');
  950. EXPECT_EQ(res.first, " ");
  951. EXPECT_EQ(res.second, "");
  952. }
  953. {
  954. const auto res = divide("a", '=');
  955. EXPECT_EQ(res.first, "a");
  956. EXPECT_EQ(res.second, "");
  957. }
  958. {
  959. const auto res = divide("a=", '=');
  960. EXPECT_EQ(res.first, "a");
  961. EXPECT_EQ(res.second, "");
  962. }
  963. {
  964. const auto res = divide("=b", '=');
  965. EXPECT_EQ(res.first, "");
  966. EXPECT_EQ(res.second, "b");
  967. }
  968. {
  969. const auto res = divide("a=b", '=');
  970. EXPECT_EQ(res.first, "a");
  971. EXPECT_EQ(res.second, "b");
  972. }
  973. {
  974. const auto res = divide("a=b=", '=');
  975. EXPECT_EQ(res.first, "a");
  976. EXPECT_EQ(res.second, "b=");
  977. }
  978. {
  979. const auto res = divide("a=b=c", '=');
  980. EXPECT_EQ(res.first, "a");
  981. EXPECT_EQ(res.second, "b=c");
  982. }
  983. }
  984. TEST(SplitTest, ParseQueryString) {
  985. string s = "key1=val1&key2=val2&key3=val3";
  986. Params dic;
  987. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  988. [&](const char *b, const char *e) {
  989. string key, val;
  990. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  991. if (key.empty()) {
  992. key.assign(b2, e2);
  993. } else {
  994. val.assign(b2, e2);
  995. }
  996. });
  997. dic.emplace(key, val);
  998. });
  999. EXPECT_EQ("val1", dic.find("key1")->second);
  1000. EXPECT_EQ("val2", dic.find("key2")->second);
  1001. EXPECT_EQ("val3", dic.find("key3")->second);
  1002. }
  1003. TEST(SplitTest, ParseInvalidQueryTests) {
  1004. {
  1005. string s = " ";
  1006. Params dict;
  1007. detail::parse_query_text(s, dict);
  1008. EXPECT_TRUE(dict.empty());
  1009. }
  1010. {
  1011. string s = " = =";
  1012. Params dict;
  1013. detail::parse_query_text(s, dict);
  1014. EXPECT_TRUE(dict.empty());
  1015. }
  1016. }
  1017. TEST(ParseQueryTest, ParseQueryString) {
  1018. {
  1019. std::string s = "key1=val1&key2=val2&key3=val3";
  1020. Params dic;
  1021. detail::parse_query_text(s, dic);
  1022. EXPECT_EQ("val1", dic.find("key1")->second);
  1023. EXPECT_EQ("val2", dic.find("key2")->second);
  1024. EXPECT_EQ("val3", dic.find("key3")->second);
  1025. }
  1026. {
  1027. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1028. Params dic;
  1029. detail::parse_query_text(s, dic);
  1030. EXPECT_EQ("", dic.find("key1")->second);
  1031. EXPECT_EQ("val1", dic.find("key2")->second);
  1032. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1033. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1034. }
  1035. }
  1036. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1037. Params dic;
  1038. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1039. dic.emplace("key1", "val1");
  1040. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1041. dic.emplace("key2", "val2");
  1042. dic.emplace("key3", "val3");
  1043. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1044. }
  1045. // Joins every entry of a Headers or Params into "key=value " so a whole
  1046. // traversal can be compared in one assertion. Both are instantiations of the
  1047. // same insertion-ordered container, so one helper serves both.
  1048. template <typename Map> static std::string entries_to_string(const Map &m) {
  1049. std::string s;
  1050. for (const auto &entry : m) {
  1051. s += entry.first + "=" + entry.second + " ";
  1052. }
  1053. return s;
  1054. }
  1055. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1056. // Params used to be a std::multimap, which sorted by name and handed the
  1057. // caller's query back alphabetised. A client signing its query string could
  1058. // not reproduce the order it asked for.
  1059. Params dic;
  1060. dic.emplace("zulu", "1");
  1061. dic.emplace("alpha", "2");
  1062. dic.emplace("mike", "3");
  1063. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1064. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1065. }
  1066. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1067. Params dic;
  1068. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1069. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1070. }
  1071. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1072. Request req;
  1073. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1074. req.params);
  1075. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1076. EXPECT_EQ("first", req.get_param_value("tag"));
  1077. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1078. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1079. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1080. EXPECT_EQ("", req.get_param_value("tag", 3));
  1081. }
  1082. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1083. // Params shares its container with Headers, which matches field names
  1084. // case-insensitively. Parameter names must not pick that up.
  1085. Params dic;
  1086. dic.emplace("Key", "upper");
  1087. dic.emplace("key", "lower");
  1088. EXPECT_EQ(2U, dic.size());
  1089. EXPECT_EQ(1U, dic.count("Key"));
  1090. EXPECT_EQ(1U, dic.count("key"));
  1091. EXPECT_EQ("upper", dic.find("Key")->second);
  1092. EXPECT_EQ("lower", dic.find("key")->second);
  1093. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1094. }
  1095. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1096. Server svr;
  1097. std::string order;
  1098. svr.Get("/order", [&](const Request &req, Response &res) {
  1099. order = entries_to_string(req.params);
  1100. res.set_content("ok", "text/plain");
  1101. });
  1102. auto port = svr.bind_to_any_port(HOST);
  1103. thread t = thread([&] { svr.listen_after_bind(); });
  1104. auto se = detail::scope_exit([&] {
  1105. svr.stop();
  1106. t.join();
  1107. ASSERT_FALSE(svr.is_running());
  1108. });
  1109. svr.wait_until_ready();
  1110. Client cli(HOST, port);
  1111. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1112. ASSERT_TRUE(res);
  1113. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1114. }
  1115. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1116. Server svr;
  1117. std::string field_order, file_order;
  1118. svr.Post("/order", [&](const Request &req, Response &res) {
  1119. for (const auto &field : req.form.fields) {
  1120. field_order += field.first + "=" + field.second.content + " ";
  1121. }
  1122. for (const auto &file : req.form.files) {
  1123. file_order += file.first + "=" + file.second.filename + " ";
  1124. }
  1125. res.set_content("ok", "text/plain");
  1126. });
  1127. auto port = svr.bind_to_any_port(HOST);
  1128. thread t = thread([&] { svr.listen_after_bind(); });
  1129. auto se = detail::scope_exit([&] {
  1130. svr.stop();
  1131. t.join();
  1132. ASSERT_FALSE(svr.is_running());
  1133. });
  1134. svr.wait_until_ready();
  1135. UploadFormDataItems items = {
  1136. {"zulu", "1", "", ""},
  1137. {"alpha", "2", "", ""},
  1138. {"mike", "3", "", ""},
  1139. {"zebra", "z", "z.txt", "text/plain"},
  1140. {"apple", "a", "a.txt", "text/plain"},
  1141. };
  1142. Client cli(HOST, port);
  1143. auto res = cli.Post("/order", items);
  1144. ASSERT_TRUE(res);
  1145. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1146. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1147. }
  1148. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1149. Server svr;
  1150. std::vector<std::string> values;
  1151. std::string first, second, out_of_range, order;
  1152. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1153. values = req.form.get_fields("tag");
  1154. first = req.form.get_field("tag", 0);
  1155. second = req.form.get_field("tag", 1);
  1156. out_of_range = req.form.get_field("tag", 2);
  1157. for (const auto &field : req.form.fields) {
  1158. order += field.first + "=" + field.second.content + " ";
  1159. }
  1160. res.set_content("ok", "text/plain");
  1161. });
  1162. auto port = svr.bind_to_any_port(HOST);
  1163. thread t = thread([&] { svr.listen_after_bind(); });
  1164. auto se = detail::scope_exit([&] {
  1165. svr.stop();
  1166. t.join();
  1167. ASSERT_FALSE(svr.is_running());
  1168. });
  1169. svr.wait_until_ready();
  1170. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1171. // not adjacent in the container.
  1172. UploadFormDataItems items = {
  1173. {"tag", "first", "", ""},
  1174. {"other", "x", "", ""},
  1175. {"tag", "second", "", ""},
  1176. };
  1177. Client cli(HOST, port);
  1178. auto res = cli.Post("/repeated", items);
  1179. ASSERT_TRUE(res);
  1180. ASSERT_EQ(2U, values.size());
  1181. EXPECT_EQ("first", values[0]);
  1182. EXPECT_EQ("second", values[1]);
  1183. EXPECT_EQ("first", first);
  1184. EXPECT_EQ("second", second);
  1185. // std::multimap already kept entries sharing a name in insertion order, so
  1186. // everything above passes without this change too. The whole traversal is
  1187. // what tells the two apart: sorting by name would hoist "other" to the front
  1188. // and the two "tag" parts would end up adjacent.
  1189. EXPECT_EQ("tag=first other=x tag=second ", order);
  1190. // Advancing past the last entry of a name used to run off the container;
  1191. // the container's saturating increment makes it return the default instead.
  1192. EXPECT_EQ("", out_of_range);
  1193. }
  1194. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1195. // Server::read_content() keeps a FormFields::iterator alive across the
  1196. // content callbacks that fill the part it points at. The container is
  1197. // vector-backed, so a later emplace can reallocate and invalidate an older
  1198. // iterator; 64 parts grow the vector through seven reallocations, which
  1199. // checks that every part's content still lands in its own entry.
  1200. const size_t part_count = 64;
  1201. // One formula for both the parts sent and the values expected back, so the
  1202. // two cannot drift apart.
  1203. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1204. auto content_of = [](size_t i) {
  1205. return std::string(64, static_cast<char>('a' + (i % 26)));
  1206. };
  1207. Server svr;
  1208. std::vector<std::pair<std::string, std::string>> received;
  1209. svr.Post("/many", [&](const Request &req, Response &res) {
  1210. for (const auto &field : req.form.fields) {
  1211. received.emplace_back(field.first, field.second.content);
  1212. }
  1213. res.set_content("ok", "text/plain");
  1214. });
  1215. auto port = svr.bind_to_any_port(HOST);
  1216. thread t = thread([&] { svr.listen_after_bind(); });
  1217. auto se = detail::scope_exit([&] {
  1218. svr.stop();
  1219. t.join();
  1220. ASSERT_FALSE(svr.is_running());
  1221. });
  1222. svr.wait_until_ready();
  1223. UploadFormDataItems items;
  1224. for (size_t i = 0; i < part_count; i++) {
  1225. items.push_back({name_of(i), content_of(i), "", ""});
  1226. }
  1227. Client cli(HOST, port);
  1228. auto res = cli.Post("/many", items);
  1229. ASSERT_TRUE(res);
  1230. ASSERT_EQ(part_count, received.size());
  1231. for (size_t i = 0; i < part_count; i++) {
  1232. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1233. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1234. }
  1235. }
  1236. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1237. string content_type = "multipart/form-data; boundary=something";
  1238. string boundary;
  1239. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1240. EXPECT_TRUE(ret);
  1241. EXPECT_EQ(boundary, "something");
  1242. }
  1243. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1244. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1245. string boundary;
  1246. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1247. EXPECT_TRUE(ret);
  1248. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1249. }
  1250. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1251. string content_type =
  1252. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1253. string boundary;
  1254. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1255. EXPECT_TRUE(ret);
  1256. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1257. }
  1258. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1259. string content_type =
  1260. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1261. string boundary;
  1262. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1263. EXPECT_TRUE(ret);
  1264. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1265. }
  1266. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1267. const string boundary(70, 'a');
  1268. string content_type = "multipart/form-data; boundary=" + boundary;
  1269. string parsed;
  1270. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1271. EXPECT_TRUE(ret);
  1272. EXPECT_EQ(parsed, boundary);
  1273. }
  1274. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1275. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1276. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1277. string parsed;
  1278. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1279. EXPECT_FALSE(ret);
  1280. }
  1281. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1282. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1283. // is 72 characters on the wire and still valid.
  1284. const string boundary(70, 'a');
  1285. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1286. string parsed;
  1287. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1288. EXPECT_EQ(parsed, boundary);
  1289. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1290. parsed.clear();
  1291. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1292. }
  1293. TEST(GetHeaderValueTest, DefaultValue) {
  1294. Headers headers = {{"Dummy", "Dummy"}};
  1295. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1296. EXPECT_STREQ("text/plain", val);
  1297. }
  1298. TEST(GetHeaderValueTest, DefaultValueInt) {
  1299. Headers headers = {{"Dummy", "Dummy"}};
  1300. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1301. EXPECT_EQ(100ull, val);
  1302. }
  1303. TEST(GetHeaderValueTest, RegularValue) {
  1304. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1305. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1306. EXPECT_STREQ("text/html", val);
  1307. }
  1308. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1309. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1310. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1311. EXPECT_STREQ("text/html", val);
  1312. }
  1313. TEST(GetHeaderValueTest, SetContent) {
  1314. Response res;
  1315. res.set_content("html", "text/html");
  1316. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1317. res.set_content("text", "text/plain");
  1318. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1319. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1320. }
  1321. TEST(GetHeaderValueTest, RegularValueInt) {
  1322. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1323. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1324. EXPECT_EQ(100ull, val);
  1325. }
  1326. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1327. Headers headers = {{"Content-Length", "x"}};
  1328. auto is_invalid_value = false;
  1329. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1330. is_invalid_value);
  1331. EXPECT_EQ(0ull, val);
  1332. EXPECT_TRUE(is_invalid_value);
  1333. }
  1334. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1335. // An all-digit value that overflows size_t must be reported as invalid, not
  1336. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1337. // a large length to a small one on 32-bit builds, leaving the framing length
  1338. // wrong while is_invalid_value stayed false.
  1339. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1340. auto is_invalid_value = false;
  1341. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1342. is_invalid_value);
  1343. EXPECT_TRUE(is_invalid_value);
  1344. // A well-formed length is unaffected.
  1345. Headers ok = {{"Content-Length", "1234"}};
  1346. is_invalid_value = false;
  1347. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1348. is_invalid_value);
  1349. EXPECT_EQ(1234ull, val);
  1350. EXPECT_FALSE(is_invalid_value);
  1351. }
  1352. TEST(GetHeaderValueTest, Range) {
  1353. {
  1354. Headers headers = {make_range_header({{1, -1}})};
  1355. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1356. EXPECT_STREQ("bytes=1-", val);
  1357. }
  1358. {
  1359. Headers headers = {make_range_header({{-1, 1}})};
  1360. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1361. EXPECT_STREQ("bytes=-1", val);
  1362. }
  1363. {
  1364. Headers headers = {make_range_header({{1, 10}})};
  1365. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1366. EXPECT_STREQ("bytes=1-10", val);
  1367. }
  1368. {
  1369. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1370. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1371. EXPECT_STREQ("bytes=1-10, 100-", val);
  1372. }
  1373. {
  1374. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1375. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1376. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1377. }
  1378. {
  1379. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1380. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1381. EXPECT_STREQ("bytes=0-0, -1", val);
  1382. }
  1383. }
  1384. TEST(BearerTokenAuthTest, SchemeValidation) {
  1385. // A value shorter than "Bearer " must not throw from the fixed-length
  1386. // substr, and a non-Bearer scheme must not be reported as a token.
  1387. struct {
  1388. const char *value;
  1389. const char *expected;
  1390. } cases[] = {
  1391. {"x", ""},
  1392. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1393. {"Bearer abc123", "abc123"},
  1394. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1395. };
  1396. for (const auto &c : cases) {
  1397. Request req;
  1398. req.set_header("Authorization", c.value);
  1399. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1400. }
  1401. }
  1402. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1403. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1404. // to depend on the standard library (libstdc++ handed back duplicates in
  1405. // reverse insertion order, libc++ in insertion order).
  1406. Request req;
  1407. req.set_header("Accept-Encoding", "gzip");
  1408. req.set_header("Accept-Encoding", "deflate");
  1409. req.set_header("Accept-Encoding", "br");
  1410. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1411. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1412. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1413. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1414. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1415. }
  1416. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1417. Request req;
  1418. req.set_header("X-Test", "only");
  1419. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1420. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1421. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1422. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1423. }
  1424. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1425. Headers headers;
  1426. headers.emplace("Host", "example.com");
  1427. headers.emplace("Accept-Encoding", "gzip");
  1428. headers.emplace("User-Agent", "test");
  1429. headers.emplace("Accept-Encoding", "deflate");
  1430. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1431. "Accept-Encoding=deflate ",
  1432. entries_to_string(headers));
  1433. }
  1434. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1435. Headers headers = {{"Content-Type", "text/html"},
  1436. {"CONTENT-TYPE", "text/xml"}};
  1437. EXPECT_EQ(2U, headers.count("content-type"));
  1438. auto it = headers.find("content-type");
  1439. ASSERT_TRUE(it != headers.end());
  1440. EXPECT_EQ("text/html", it->second);
  1441. }
  1442. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1443. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1444. // drop only those fields and leave everything positioned between them.
  1445. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1446. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1447. auto rng = headers.equal_range("a");
  1448. headers.erase(rng.first, rng.second);
  1449. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1450. }
  1451. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1452. Headers headers = {
  1453. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1454. EXPECT_EQ(3U, headers.erase("A"));
  1455. EXPECT_EQ(0U, headers.count("A"));
  1456. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1457. }
  1458. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1459. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1460. headers.emplace_front("Host", "example.com");
  1461. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1462. entries_to_string(headers));
  1463. }
  1464. TEST(ParseHeaderValueTest, Range) {
  1465. {
  1466. Ranges ranges;
  1467. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1468. EXPECT_TRUE(ret);
  1469. EXPECT_EQ(1u, ranges.size());
  1470. EXPECT_EQ(1u, ranges[0].first);
  1471. EXPECT_EQ(-1, ranges[0].second);
  1472. }
  1473. {
  1474. Ranges ranges;
  1475. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1476. EXPECT_TRUE(ret);
  1477. EXPECT_EQ(1u, ranges.size());
  1478. EXPECT_EQ(-1, ranges[0].first);
  1479. EXPECT_EQ(1u, ranges[0].second);
  1480. }
  1481. {
  1482. Ranges ranges;
  1483. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1484. EXPECT_TRUE(ret);
  1485. EXPECT_EQ(1u, ranges.size());
  1486. EXPECT_EQ(1u, ranges[0].first);
  1487. EXPECT_EQ(10u, ranges[0].second);
  1488. }
  1489. {
  1490. Ranges ranges;
  1491. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1492. EXPECT_FALSE(ret);
  1493. }
  1494. {
  1495. Ranges ranges;
  1496. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1497. EXPECT_TRUE(ret);
  1498. EXPECT_EQ(2u, ranges.size());
  1499. EXPECT_EQ(1u, ranges[0].first);
  1500. EXPECT_EQ(10u, ranges[0].second);
  1501. EXPECT_EQ(100u, ranges[1].first);
  1502. EXPECT_EQ(-1, ranges[1].second);
  1503. }
  1504. {
  1505. Ranges ranges;
  1506. auto ret =
  1507. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1508. EXPECT_TRUE(ret);
  1509. EXPECT_EQ(3u, ranges.size());
  1510. EXPECT_EQ(1u, ranges[0].first);
  1511. EXPECT_EQ(10u, ranges[0].second);
  1512. EXPECT_EQ(100u, ranges[1].first);
  1513. EXPECT_EQ(200u, ranges[1].second);
  1514. EXPECT_EQ(300u, ranges[2].first);
  1515. EXPECT_EQ(400u, ranges[2].second);
  1516. }
  1517. {
  1518. Ranges ranges;
  1519. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1520. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1521. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1522. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1523. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1524. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1525. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1526. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1527. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1528. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1529. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1530. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1531. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1532. EXPECT_TRUE(ranges.empty());
  1533. }
  1534. }
  1535. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1536. Request req;
  1537. req.set_header("Accept-Encoding", "gzip");
  1538. Response res;
  1539. res.set_header("Content-Type", "text/plain");
  1540. auto ret = detail::encoding_type(req, res);
  1541. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1542. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1543. #else
  1544. EXPECT_TRUE(ret == detail::EncodingType::None);
  1545. #endif
  1546. }
  1547. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1548. Request req;
  1549. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1550. Response res;
  1551. res.set_header("Content-Type", "text/plain");
  1552. auto ret = detail::encoding_type(req, res);
  1553. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1554. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1555. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1556. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1557. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1558. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1559. #else
  1560. EXPECT_TRUE(ret == detail::EncodingType::None);
  1561. #endif
  1562. }
  1563. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1564. Request req;
  1565. req.set_header("Accept-Encoding",
  1566. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1567. Response res;
  1568. res.set_header("Content-Type", "text/plain");
  1569. auto ret = detail::encoding_type(req, res);
  1570. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1571. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1572. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1573. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1574. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1575. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1576. #else
  1577. EXPECT_TRUE(ret == detail::EncodingType::None);
  1578. #endif
  1579. }
  1580. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1581. // All supported encodings rejected with q=0 should return None
  1582. Request req;
  1583. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1584. Response res;
  1585. res.set_header("Content-Type", "text/plain");
  1586. auto ret = detail::encoding_type(req, res);
  1587. EXPECT_TRUE(ret == detail::EncodingType::None);
  1588. }
  1589. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1590. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1591. Request req;
  1592. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1593. Response res;
  1594. res.set_header("Content-Type", "text/plain");
  1595. auto ret = detail::encoding_type(req, res);
  1596. EXPECT_TRUE(ret == detail::EncodingType::None);
  1597. }
  1598. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1599. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1600. Request req;
  1601. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1602. Response res;
  1603. res.set_header("Content-Type", "text/plain");
  1604. auto ret = detail::encoding_type(req, res);
  1605. EXPECT_TRUE(ret == detail::EncodingType::None);
  1606. }
  1607. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1608. // RFC 7231: Accept-Encoding values are case-insensitive
  1609. Request req;
  1610. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1611. Response res;
  1612. res.set_header("Content-Type", "text/plain");
  1613. auto ret = detail::encoding_type(req, res);
  1614. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1615. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1616. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1617. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1618. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1619. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1620. #else
  1621. EXPECT_TRUE(ret == detail::EncodingType::None);
  1622. #endif
  1623. }
  1624. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1625. // q value should determine priority, not hardcoded order
  1626. Request req;
  1627. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1628. Response res;
  1629. res.set_header("Content-Type", "text/plain");
  1630. auto ret = detail::encoding_type(req, res);
  1631. // gzip has highest q=1.0, so it should be selected even though
  1632. // br and zstd are also supported
  1633. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1634. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1635. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1636. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1637. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1638. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1639. #else
  1640. EXPECT_TRUE(ret == detail::EncodingType::None);
  1641. #endif
  1642. }
  1643. TEST(BufferStreamTest, read) {
  1644. detail::BufferStream strm1;
  1645. Stream &strm = strm1;
  1646. EXPECT_EQ(5, strm.write("hello"));
  1647. char buf[512];
  1648. EXPECT_EQ(2, strm.read(buf, 2));
  1649. EXPECT_EQ('h', buf[0]);
  1650. EXPECT_EQ('e', buf[1]);
  1651. EXPECT_EQ(2, strm.read(buf, 2));
  1652. EXPECT_EQ('l', buf[0]);
  1653. EXPECT_EQ('l', buf[1]);
  1654. EXPECT_EQ(1, strm.read(buf, 1));
  1655. EXPECT_EQ('o', buf[0]);
  1656. EXPECT_EQ(0, strm.read(buf, 1));
  1657. }
  1658. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1659. auto host = "www.httpwatch.com";
  1660. auto ip = hosted_at(host);
  1661. EXPECT_EQ("23.96.13.243", ip);
  1662. std::vector<std::string> addrs;
  1663. hosted_at(host, addrs);
  1664. EXPECT_EQ(1u, addrs.size());
  1665. }
  1666. #if 0 // It depends on each test environment...
  1667. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1668. auto host = "www.youtube.com";
  1669. std::vector<std::string> addrs;
  1670. hosted_at(host, addrs);
  1671. EXPECT_EQ(20u, addrs.size());
  1672. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1673. EXPECT_TRUE(it != addrs.end());
  1674. }
  1675. #endif
  1676. class ChunkedEncodingTest : public ::testing::Test {
  1677. protected:
  1678. ChunkedEncodingTest()
  1679. : cli_(HOST, PORT)
  1680. #ifdef CPPHTTPLIB_SSL_ENABLED
  1681. ,
  1682. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1683. #endif
  1684. {
  1685. cli_.set_connection_timeout(2);
  1686. #ifdef CPPHTTPLIB_SSL_ENABLED
  1687. cli_.enable_server_certificate_verification(false);
  1688. #endif
  1689. }
  1690. virtual void SetUp() {
  1691. read_file("./image.jpg", image_data_);
  1692. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1693. res.set_content("Hello World!", "text/plain");
  1694. });
  1695. svr_.Get(
  1696. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1697. res.set_chunked_content_provider(
  1698. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1699. size_t remaining = image_data_.size() - offset;
  1700. if (remaining == 0) {
  1701. sink.done();
  1702. } else {
  1703. constexpr size_t CHUNK_SIZE = 1024;
  1704. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1705. sink.write(&image_data_[offset], send_size);
  1706. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1707. }
  1708. return true;
  1709. });
  1710. });
  1711. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1712. svr_.wait_until_ready();
  1713. }
  1714. virtual void TearDown() {
  1715. svr_.stop();
  1716. if (!request_threads_.empty()) {
  1717. std::this_thread::sleep_for(std::chrono::seconds(1));
  1718. for (auto &t : request_threads_) {
  1719. t.join();
  1720. }
  1721. }
  1722. t_.join();
  1723. }
  1724. #ifdef CPPHTTPLIB_SSL_ENABLED
  1725. SSLClient cli_;
  1726. SSLServer svr_;
  1727. #else
  1728. Client cli_;
  1729. Server svr_;
  1730. #endif
  1731. thread t_;
  1732. std::vector<thread> request_threads_;
  1733. std::string image_data_;
  1734. };
  1735. TEST_F(ChunkedEncodingTest, NormalGet) {
  1736. auto res = cli_.Get("/chunked");
  1737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1738. std::string out;
  1739. read_file("./image.jpg", out);
  1740. EXPECT_EQ(StatusCode::OK_200, res->status);
  1741. EXPECT_EQ(out, res->body);
  1742. }
  1743. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1744. std::string body;
  1745. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1746. body.append(data, data_length);
  1747. return true;
  1748. });
  1749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1750. std::string out;
  1751. read_file("./image.jpg", out);
  1752. EXPECT_EQ(StatusCode::OK_200, res->status);
  1753. EXPECT_EQ(out, body);
  1754. }
  1755. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1756. std::string body;
  1757. auto res = cli_.Get(
  1758. "/chunked",
  1759. [&](const Response &response) {
  1760. EXPECT_EQ(StatusCode::OK_200, response.status);
  1761. return true;
  1762. },
  1763. [&](const char *data, size_t data_length) {
  1764. body.append(data, data_length);
  1765. return true;
  1766. });
  1767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1768. std::string out;
  1769. read_file("./image.jpg", out);
  1770. EXPECT_EQ(StatusCode::OK_200, res->status);
  1771. EXPECT_EQ(out, body);
  1772. }
  1773. TEST(RangeTest, FromHTTPBin_Online) {
  1774. auto host = "httpbingo.org";
  1775. auto path = std::string{"/range/32"};
  1776. #ifdef CPPHTTPLIB_SSL_ENABLED
  1777. auto port = 443;
  1778. SSLClient cli(host, port);
  1779. #else
  1780. auto port = 80;
  1781. Client cli(host, port);
  1782. #endif
  1783. cli.set_connection_timeout(5);
  1784. {
  1785. auto res = cli.Get(path);
  1786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1787. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1788. EXPECT_EQ(StatusCode::OK_200, res->status);
  1789. }
  1790. {
  1791. Headers headers = {make_range_header({{1, -1}})};
  1792. auto res = cli.Get(path, headers);
  1793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1794. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1795. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1796. }
  1797. {
  1798. Headers headers = {make_range_header({{1, 10}})};
  1799. auto res = cli.Get(path, headers);
  1800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1801. EXPECT_EQ("bcdefghijk", res->body);
  1802. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1803. }
  1804. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1805. // entire resource, while the original httpbin returned 200. Both are
  1806. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1807. {
  1808. Headers headers = {make_range_header({{0, 31}})};
  1809. auto res = cli.Get(path, headers);
  1810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1811. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1812. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1813. res->status == StatusCode::PartialContent_206);
  1814. }
  1815. {
  1816. Headers headers = {make_range_header({{0, -1}})};
  1817. auto res = cli.Get(path, headers);
  1818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1819. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1820. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1821. res->status == StatusCode::PartialContent_206);
  1822. }
  1823. // go-httpbin returns 206 with clamped range for over-range requests,
  1824. // while the original httpbin returned 416. Both behaviors are observed
  1825. // in real servers, so we only verify the request succeeds.
  1826. {
  1827. Headers headers = {make_range_header({{0, 32}})};
  1828. auto res = cli.Get(path, headers);
  1829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1830. }
  1831. }
  1832. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1833. auto host = "unresolvableaddress.local";
  1834. auto path = std::string{"/"};
  1835. #ifdef CPPHTTPLIB_SSL_ENABLED
  1836. auto port = 443;
  1837. SSLClient cli(host, port);
  1838. #else
  1839. auto port = 80;
  1840. Client cli(host, port);
  1841. #endif
  1842. cli.set_connection_timeout(1);
  1843. {
  1844. auto res = cli.Get(path);
  1845. ASSERT_FALSE(res);
  1846. }
  1847. std::this_thread::sleep_for(std::chrono::seconds(8));
  1848. }
  1849. #if defined(__linux__) && defined(__GLIBC__) && \
  1850. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1851. // Forward declaration: in split builds split.py strips `inline` and moves the
  1852. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1853. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1854. // against the symbol in both header-only and split builds.
  1855. namespace httplib {
  1856. namespace detail {
  1857. int getaddrinfo_with_timeout(const char *node, const char *service,
  1858. const struct addrinfo *hints,
  1859. struct addrinfo **res, time_t timeout_sec);
  1860. } // namespace detail
  1861. } // namespace httplib
  1862. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1863. //
  1864. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1865. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1866. // gai_suspend() call hits the connection timeout the function calls
  1867. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1868. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1869. // still alive and still references the now-destroyed stack frame.
  1870. //
  1871. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1872. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1873. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1874. // and runs them in a container.
  1875. namespace {
  1876. bool should_run_issue_2431_tests() {
  1877. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1878. return v && *v && std::string(v) != "0";
  1879. }
  1880. std::string unique_unresolvable_host(int n) {
  1881. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1882. // glibc still asks the configured nameserver — which is exactly the path
  1883. // we want to exercise. A unique label per call avoids the resolver cache.
  1884. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1885. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1886. std::to_string(n) + ".invalid";
  1887. }
  1888. } // namespace
  1889. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1890. if (!should_run_issue_2431_tests()) {
  1891. GTEST_SKIP()
  1892. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1893. }
  1894. for (int i = 0; i < 8; ++i) {
  1895. struct addrinfo hints;
  1896. memset(&hints, 0, sizeof(hints));
  1897. hints.ai_family = AF_UNSPEC;
  1898. hints.ai_socktype = SOCK_STREAM;
  1899. auto host = unique_unresolvable_host(i);
  1900. struct addrinfo *result = nullptr;
  1901. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1902. &result, /*timeout_sec=*/1);
  1903. if (rc == 0 && result) { freeaddrinfo(result); }
  1904. }
  1905. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1906. // stack region they still believe holds their gaicb.
  1907. std::this_thread::sleep_for(std::chrono::seconds(3));
  1908. }
  1909. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1910. if (!should_run_issue_2431_tests()) {
  1911. GTEST_SKIP()
  1912. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1913. }
  1914. std::atomic<bool> stop{false};
  1915. std::vector<std::thread> threads;
  1916. for (int t = 0; t < 8; ++t) {
  1917. threads.emplace_back([t, &stop] {
  1918. int i = 0;
  1919. while (!stop.load(std::memory_order_relaxed)) {
  1920. struct addrinfo hints;
  1921. memset(&hints, 0, sizeof(hints));
  1922. hints.ai_family = AF_UNSPEC;
  1923. hints.ai_socktype = SOCK_STREAM;
  1924. auto host = unique_unresolvable_host(t * 100000 + i++);
  1925. struct addrinfo *result = nullptr;
  1926. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1927. &result, /*timeout_sec=*/1);
  1928. if (rc == 0 && result) { freeaddrinfo(result); }
  1929. }
  1930. });
  1931. }
  1932. std::this_thread::sleep_for(std::chrono::seconds(8));
  1933. stop.store(true, std::memory_order_relaxed);
  1934. for (auto &th : threads) {
  1935. th.join();
  1936. }
  1937. std::this_thread::sleep_for(std::chrono::seconds(3));
  1938. }
  1939. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1940. if (!should_run_issue_2431_tests()) {
  1941. GTEST_SKIP()
  1942. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1943. }
  1944. std::atomic<bool> stop{false};
  1945. std::vector<std::thread> threads;
  1946. for (int t = 0; t < 8; ++t) {
  1947. threads.emplace_back([t, &stop] {
  1948. int i = 0;
  1949. while (!stop.load(std::memory_order_relaxed)) {
  1950. auto host = unique_unresolvable_host(t * 100000 + i++);
  1951. Client cli(host, 80);
  1952. cli.set_connection_timeout(1, 0);
  1953. cli.set_read_timeout(1, 0);
  1954. cli.set_write_timeout(1, 0);
  1955. (void)cli.Get("/");
  1956. }
  1957. });
  1958. }
  1959. std::this_thread::sleep_for(std::chrono::seconds(8));
  1960. stop.store(true, std::memory_order_relaxed);
  1961. for (auto &th : threads) {
  1962. th.join();
  1963. }
  1964. std::this_thread::sleep_for(std::chrono::seconds(3));
  1965. }
  1966. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1967. TEST(ConnectionErrorTest, InvalidHost) {
  1968. auto host = "-abcde.com";
  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(std::chrono::seconds(2));
  1977. auto res = cli.Get("/");
  1978. ASSERT_TRUE(!res);
  1979. EXPECT_EQ(Error::Connection, res.error());
  1980. }
  1981. TEST(ConnectionErrorTest, InvalidHost2) {
  1982. auto host = "httpcan.org/";
  1983. #ifdef CPPHTTPLIB_SSL_ENABLED
  1984. SSLClient cli(host);
  1985. #else
  1986. Client cli(host);
  1987. #endif
  1988. cli.set_connection_timeout(std::chrono::seconds(2));
  1989. auto res = cli.Get("/");
  1990. ASSERT_TRUE(!res);
  1991. EXPECT_EQ(Error::Connection, res.error());
  1992. }
  1993. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1994. auto host = "httpcan.org/";
  1995. #ifdef CPPHTTPLIB_SSL_ENABLED
  1996. SSLClient cli(host);
  1997. #else
  1998. Client cli(host);
  1999. #endif
  2000. cli.set_connection_timeout(std::chrono::seconds(2));
  2001. auto res = cli.Get("/");
  2002. ASSERT_TRUE(!res);
  2003. stringstream s;
  2004. s << "error code: " << res.error();
  2005. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2006. }
  2007. TEST(ConnectionErrorTest, InvalidPort) {
  2008. auto host = "localhost";
  2009. auto port = 44380;
  2010. #ifdef CPPHTTPLIB_SSL_ENABLED
  2011. SSLClient cli(host, port);
  2012. #else
  2013. Client cli(host, port);
  2014. #endif
  2015. cli.set_connection_timeout(std::chrono::seconds(2));
  2016. auto res = cli.Get("/");
  2017. ASSERT_TRUE(!res);
  2018. EXPECT_TRUE(Error::Connection == res.error() ||
  2019. Error::ConnectionTimeout == res.error());
  2020. }
  2021. TEST(ConnectionErrorTest, Timeout_Online) {
  2022. auto host = "google.com";
  2023. #ifdef CPPHTTPLIB_SSL_ENABLED
  2024. auto port = 44380;
  2025. SSLClient cli(host, port);
  2026. #else
  2027. auto port = 8080;
  2028. Client cli(host, port);
  2029. #endif
  2030. cli.set_connection_timeout(std::chrono::seconds(2));
  2031. // only probe one address type so that the error reason
  2032. // correlates to the timed-out IPv4, not the unsupported
  2033. // IPv6 connection attempt
  2034. cli.set_address_family(AF_INET);
  2035. auto res = cli.Get("/");
  2036. ASSERT_TRUE(!res);
  2037. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2038. }
  2039. TEST(CancelTest, NoCancel_Online) {
  2040. auto host = "httpbingo.org";
  2041. auto path = std::string{"/range/32"};
  2042. #ifdef CPPHTTPLIB_SSL_ENABLED
  2043. auto port = 443;
  2044. SSLClient cli(host, port);
  2045. #else
  2046. auto port = 80;
  2047. Client cli(host, port);
  2048. #endif
  2049. cli.set_connection_timeout(std::chrono::seconds(5));
  2050. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2052. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2053. EXPECT_EQ(StatusCode::OK_200, res->status);
  2054. }
  2055. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2056. // Use /bytes with a large payload so that the DownloadProgress callback
  2057. // (which only fires for Content-Length responses) is invoked before the
  2058. // entire body is received, giving cancellation a chance to fire.
  2059. auto host = "httpbingo.org";
  2060. auto path = std::string{"/bytes/524288"};
  2061. #ifdef CPPHTTPLIB_SSL_ENABLED
  2062. auto port = 443;
  2063. SSLClient cli(host, port);
  2064. #else
  2065. auto port = 80;
  2066. Client cli(host, port);
  2067. #endif
  2068. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2069. cli.set_connection_timeout(std::chrono::seconds(5));
  2070. ASSERT_TRUE(!res);
  2071. EXPECT_EQ(Error::Canceled, res.error());
  2072. }
  2073. TEST(CancelTest, WithCancelLargePayload_Online) {
  2074. auto host = "httpbingo.org";
  2075. auto path = std::string{"/bytes/524288"};
  2076. #ifdef CPPHTTPLIB_SSL_ENABLED
  2077. auto port = 443;
  2078. SSLClient cli(host, port);
  2079. #else
  2080. auto port = 80;
  2081. Client cli(host, port);
  2082. #endif
  2083. cli.set_connection_timeout(std::chrono::seconds(5));
  2084. uint32_t count = 0;
  2085. auto res =
  2086. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2087. ASSERT_TRUE(!res);
  2088. EXPECT_EQ(Error::Canceled, res.error());
  2089. }
  2090. TEST(CancelTest, NoCancelPost) {
  2091. Server svr;
  2092. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2093. res.set_content("Hello World!", "text/plain");
  2094. });
  2095. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2096. auto se = detail::scope_exit([&] {
  2097. svr.stop();
  2098. thread.join();
  2099. ASSERT_FALSE(svr.is_running());
  2100. });
  2101. svr.wait_until_ready();
  2102. Client cli(HOST, PORT);
  2103. cli.set_connection_timeout(std::chrono::seconds(5));
  2104. auto res =
  2105. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2106. "application/json", [](uint64_t, uint64_t) { return true; });
  2107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2108. EXPECT_EQ("Hello World!", res->body);
  2109. EXPECT_EQ(StatusCode::OK_200, res->status);
  2110. }
  2111. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2112. Server svr;
  2113. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2114. res.set_content("Hello World!", "text/plain");
  2115. });
  2116. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2117. auto se = detail::scope_exit([&] {
  2118. svr.stop();
  2119. thread.join();
  2120. ASSERT_FALSE(svr.is_running());
  2121. });
  2122. svr.wait_until_ready();
  2123. Client cli(HOST, PORT);
  2124. cli.set_connection_timeout(std::chrono::seconds(5));
  2125. auto res =
  2126. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2127. "application/json", [](uint64_t, uint64_t) { return false; });
  2128. ASSERT_TRUE(!res);
  2129. EXPECT_EQ(Error::Canceled, res.error());
  2130. }
  2131. TEST(CancelTest, WithCancelLargePayloadPost) {
  2132. Server svr;
  2133. svr.set_payload_max_length(200 * 1024 * 1024);
  2134. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2135. res.set_content(LARGE_DATA, "text/plain");
  2136. });
  2137. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2138. auto se = detail::scope_exit([&] {
  2139. svr.stop();
  2140. thread.join();
  2141. ASSERT_FALSE(svr.is_running());
  2142. });
  2143. svr.wait_until_ready();
  2144. Client cli(HOST, PORT);
  2145. cli.set_payload_max_length(200 * 1024 * 1024);
  2146. cli.set_connection_timeout(std::chrono::seconds(5));
  2147. auto res =
  2148. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2149. "application/json", [](uint64_t, uint64_t) { return false; });
  2150. ASSERT_TRUE(!res);
  2151. EXPECT_EQ(Error::Canceled, res.error());
  2152. }
  2153. TEST(CancelTest, NoCancelPut) {
  2154. Server svr;
  2155. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2156. res.set_content("Hello World!", "text/plain");
  2157. });
  2158. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2159. auto se = detail::scope_exit([&] {
  2160. svr.stop();
  2161. thread.join();
  2162. ASSERT_FALSE(svr.is_running());
  2163. });
  2164. svr.wait_until_ready();
  2165. Client cli(HOST, PORT);
  2166. cli.set_connection_timeout(std::chrono::seconds(5));
  2167. auto res =
  2168. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2169. "application/json", [](uint64_t, uint64_t) { return true; });
  2170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2171. EXPECT_EQ("Hello World!", res->body);
  2172. EXPECT_EQ(StatusCode::OK_200, res->status);
  2173. }
  2174. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2175. Server svr;
  2176. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2177. res.set_content("Hello World!", "text/plain");
  2178. });
  2179. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2180. auto se = detail::scope_exit([&] {
  2181. svr.stop();
  2182. thread.join();
  2183. ASSERT_FALSE(svr.is_running());
  2184. });
  2185. svr.wait_until_ready();
  2186. Client cli(HOST, PORT);
  2187. cli.set_connection_timeout(std::chrono::seconds(5));
  2188. auto res =
  2189. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2190. "application/json", [](uint64_t, uint64_t) { return false; });
  2191. ASSERT_TRUE(!res);
  2192. EXPECT_EQ(Error::Canceled, res.error());
  2193. }
  2194. TEST(CancelTest, WithCancelLargePayloadPut) {
  2195. Server svr;
  2196. svr.set_payload_max_length(200 * 1024 * 1024);
  2197. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2198. res.set_content(LARGE_DATA, "text/plain");
  2199. });
  2200. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2201. auto se = detail::scope_exit([&] {
  2202. svr.stop();
  2203. thread.join();
  2204. ASSERT_FALSE(svr.is_running());
  2205. });
  2206. svr.wait_until_ready();
  2207. Client cli(HOST, PORT);
  2208. cli.set_payload_max_length(200 * 1024 * 1024);
  2209. cli.set_connection_timeout(std::chrono::seconds(5));
  2210. auto res =
  2211. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2212. "application/json", [](uint64_t, uint64_t) { return false; });
  2213. ASSERT_TRUE(!res);
  2214. EXPECT_EQ(Error::Canceled, res.error());
  2215. }
  2216. TEST(CancelTest, NoCancelPatch) {
  2217. Server svr;
  2218. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2219. res.set_content("Hello World!", "text/plain");
  2220. });
  2221. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2222. auto se = detail::scope_exit([&] {
  2223. svr.stop();
  2224. thread.join();
  2225. ASSERT_FALSE(svr.is_running());
  2226. });
  2227. svr.wait_until_ready();
  2228. Client cli(HOST, PORT);
  2229. cli.set_connection_timeout(std::chrono::seconds(5));
  2230. auto res =
  2231. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2232. "application/json", [](uint64_t, uint64_t) { return true; });
  2233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2234. EXPECT_EQ("Hello World!", res->body);
  2235. EXPECT_EQ(StatusCode::OK_200, res->status);
  2236. }
  2237. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2238. Server svr;
  2239. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2240. res.set_content("Hello World!", "text/plain");
  2241. });
  2242. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2243. auto se = detail::scope_exit([&] {
  2244. svr.stop();
  2245. thread.join();
  2246. ASSERT_FALSE(svr.is_running());
  2247. });
  2248. svr.wait_until_ready();
  2249. Client cli(HOST, PORT);
  2250. cli.set_connection_timeout(std::chrono::seconds(5));
  2251. auto res =
  2252. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2253. "application/json", [](uint64_t, uint64_t) { return false; });
  2254. ASSERT_TRUE(!res);
  2255. EXPECT_EQ(Error::Canceled, res.error());
  2256. }
  2257. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2258. Server svr;
  2259. svr.set_payload_max_length(200 * 1024 * 1024);
  2260. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2261. res.set_content(LARGE_DATA, "text/plain");
  2262. });
  2263. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2264. auto se = detail::scope_exit([&] {
  2265. svr.stop();
  2266. thread.join();
  2267. ASSERT_FALSE(svr.is_running());
  2268. });
  2269. svr.wait_until_ready();
  2270. Client cli(HOST, PORT);
  2271. cli.set_payload_max_length(200 * 1024 * 1024);
  2272. cli.set_connection_timeout(std::chrono::seconds(5));
  2273. auto res =
  2274. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2275. "application/json", [](uint64_t, uint64_t) { return false; });
  2276. ASSERT_TRUE(!res);
  2277. EXPECT_EQ(Error::Canceled, res.error());
  2278. }
  2279. TEST(CancelTest, NoCancelDelete) {
  2280. Server svr;
  2281. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2282. res.set_content("Hello World!", "text/plain");
  2283. });
  2284. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2285. auto se = detail::scope_exit([&] {
  2286. svr.stop();
  2287. thread.join();
  2288. ASSERT_FALSE(svr.is_running());
  2289. });
  2290. svr.wait_until_ready();
  2291. Client cli(HOST, PORT);
  2292. cli.set_connection_timeout(std::chrono::seconds(5));
  2293. auto res =
  2294. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2295. "application/json", [](uint64_t, uint64_t) { return true; });
  2296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2297. EXPECT_EQ("Hello World!", res->body);
  2298. EXPECT_EQ(StatusCode::OK_200, res->status);
  2299. }
  2300. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2301. Server svr;
  2302. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2303. res.set_content("Hello World!", "text/plain");
  2304. });
  2305. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2306. auto se = detail::scope_exit([&] {
  2307. svr.stop();
  2308. thread.join();
  2309. ASSERT_FALSE(svr.is_running());
  2310. });
  2311. svr.wait_until_ready();
  2312. Client cli(HOST, PORT);
  2313. cli.set_connection_timeout(std::chrono::seconds(5));
  2314. auto res =
  2315. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2316. "application/json", [](uint64_t, uint64_t) { return false; });
  2317. ASSERT_TRUE(!res);
  2318. EXPECT_EQ(Error::Canceled, res.error());
  2319. }
  2320. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2321. Server svr;
  2322. svr.set_payload_max_length(200 * 1024 * 1024);
  2323. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2324. res.set_content(LARGE_DATA, "text/plain");
  2325. });
  2326. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2327. auto se = detail::scope_exit([&] {
  2328. svr.stop();
  2329. thread.join();
  2330. ASSERT_FALSE(svr.is_running());
  2331. });
  2332. svr.wait_until_ready();
  2333. Client cli(HOST, PORT);
  2334. cli.set_payload_max_length(200 * 1024 * 1024);
  2335. cli.set_connection_timeout(std::chrono::seconds(5));
  2336. auto res =
  2337. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2338. "application/json", [](uint64_t, uint64_t) { return false; });
  2339. ASSERT_TRUE(!res);
  2340. EXPECT_EQ(Error::Canceled, res.error());
  2341. }
  2342. static std::string remove_whitespace(const std::string &input) {
  2343. std::string output;
  2344. output.reserve(input.size());
  2345. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2346. [](unsigned char c) { return !std::isspace(c); });
  2347. return output;
  2348. }
  2349. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2350. auto host = "httpbingo.org";
  2351. auto path = std::string{"/basic-auth/hello/world"};
  2352. #ifdef CPPHTTPLIB_SSL_ENABLED
  2353. auto port = 443;
  2354. SSLClient cli(host, port);
  2355. #else
  2356. auto port = 80;
  2357. Client cli(host, port);
  2358. #endif
  2359. {
  2360. auto res = cli.Get(path);
  2361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2362. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2363. }
  2364. {
  2365. auto res = cli.Get(
  2366. path, Headers{make_basic_authentication_header("hello", "world")});
  2367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2368. auto body = remove_whitespace(res->body);
  2369. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2370. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2371. EXPECT_EQ(StatusCode::OK_200, res->status);
  2372. }
  2373. {
  2374. cli.set_basic_auth("hello", "world");
  2375. auto res = cli.Get(path);
  2376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2377. auto body = remove_whitespace(res->body);
  2378. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2379. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2380. EXPECT_EQ(StatusCode::OK_200, res->status);
  2381. }
  2382. {
  2383. cli.set_basic_auth("hello", "bad");
  2384. auto res = cli.Get(path);
  2385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2386. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2387. }
  2388. {
  2389. cli.set_basic_auth("bad", "world");
  2390. auto res = cli.Get(path);
  2391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2392. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2393. }
  2394. }
  2395. #ifdef CPPHTTPLIB_SSL_ENABLED
  2396. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2397. auto host = "httpbingo.org";
  2398. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2399. auto paths = std::vector<std::string>{
  2400. "/digest-auth/auth/hello/world/MD5",
  2401. "/digest-auth/auth/hello/world/SHA-256",
  2402. };
  2403. auto port = 443;
  2404. SSLClient cli(host, port);
  2405. {
  2406. auto res = cli.Get(unauth_path);
  2407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2408. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2409. }
  2410. {
  2411. cli.set_digest_auth("hello", "world");
  2412. for (const auto &path : paths) {
  2413. auto res = cli.Get(path.c_str());
  2414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2415. auto body = remove_whitespace(res->body);
  2416. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2417. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2418. EXPECT_EQ(StatusCode::OK_200, res->status);
  2419. }
  2420. cli.set_digest_auth("hello", "bad");
  2421. for (const auto &path : paths) {
  2422. auto res = cli.Get(path.c_str());
  2423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2424. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2425. }
  2426. }
  2427. }
  2428. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2429. // comma-separated list of challenges, and each challenge may itself carry a
  2430. // comma-separated auth-param list, so a server can legally offer Basic
  2431. // before Digest, either as two field lines or packed into one. Runs one 401
  2432. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2433. // value() joins them in receipt order) and checks that the retry carries a
  2434. // well-formed Digest Authorization header naming expected_realm.
  2435. static void
  2436. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2437. const std::string &expected_realm) {
  2438. std::atomic<int> hits{0};
  2439. Server svr;
  2440. svr.Get("/x", [&](const Request &req, Response &res) {
  2441. if (++hits == 1) {
  2442. res.status = StatusCode::Unauthorized_401;
  2443. for (const auto &challenge : challenges) {
  2444. res.set_header("WWW-Authenticate", challenge);
  2445. }
  2446. } else {
  2447. auto authorization = req.get_header_value("Authorization");
  2448. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2449. EXPECT_NE(std::string::npos,
  2450. authorization.find("realm=\"" + expected_realm + "\""));
  2451. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2452. res.set_content("ok", "text/plain");
  2453. }
  2454. });
  2455. auto port = svr.bind_to_any_port(HOST);
  2456. std::thread t([&]() { svr.listen_after_bind(); });
  2457. auto se = detail::scope_exit([&] {
  2458. svr.stop();
  2459. t.join();
  2460. });
  2461. svr.wait_until_ready();
  2462. Client cli(HOST, port);
  2463. cli.set_digest_auth("hello", "world");
  2464. auto res = cli.Get("/x");
  2465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2466. EXPECT_EQ(2, hits.load());
  2467. }
  2468. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2469. static const char *kDigestChallenge =
  2470. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2471. "algorithm=MD5";
  2472. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2473. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2474. "testrealm");
  2475. }
  2476. // Same challenge list with the schemes in the opposite order, to make sure
  2477. // the fix above didn't just special-case "Basic first".
  2478. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2479. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2480. "testrealm");
  2481. }
  2482. // A comma inside a quoted auth-param value must not be mistaken for the
  2483. // separator between two challenges (or two auth-params).
  2484. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2485. run_digest_challenge_list_test(
  2486. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2487. "algorithm=MD5"},
  2488. "test,realm");
  2489. }
  2490. #endif
  2491. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2492. auto host = "google.com";
  2493. auto another_host = "example.com";
  2494. auto wrong_ip = "0.0.0.0";
  2495. #ifdef CPPHTTPLIB_SSL_ENABLED
  2496. SSLClient cli(host);
  2497. #else
  2498. Client cli(host);
  2499. #endif
  2500. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2501. auto res = cli.Get("/");
  2502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2503. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2504. }
  2505. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2506. auto host = "google.com";
  2507. auto wrong_ip = "0.0.0.0";
  2508. #ifdef CPPHTTPLIB_SSL_ENABLED
  2509. SSLClient cli(host);
  2510. #else
  2511. Client cli(host);
  2512. #endif
  2513. cli.set_hostname_addr_map({{host, wrong_ip}});
  2514. auto res = cli.Get("/");
  2515. ASSERT_TRUE(!res);
  2516. EXPECT_EQ(Error::Connection, res.error());
  2517. }
  2518. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2519. // A mapped value that is not an IP literal must be resolved. "localhost"
  2520. // resolves from the hosts file, so this test needs no external DNS.
  2521. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2522. auto host = "target.invalid";
  2523. Server svr;
  2524. std::string received_host;
  2525. svr.Get("/hi", [&](const Request &req, Response &res) {
  2526. received_host = req.get_header_value("Host");
  2527. res.set_content("Hello World!", "text/plain");
  2528. });
  2529. auto port = svr.bind_to_any_port(HOST);
  2530. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2531. auto se = detail::scope_exit([&] {
  2532. svr.stop();
  2533. thread.join();
  2534. ASSERT_FALSE(svr.is_running());
  2535. });
  2536. svr.wait_until_ready();
  2537. Client cli(host, port);
  2538. cli.set_hostname_addr_map({{host, HOST}});
  2539. auto res = cli.Get("/hi");
  2540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2541. EXPECT_EQ(StatusCode::OK_200, res->status);
  2542. // The mapping only redirects the connection; the identity stays host_.
  2543. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2544. }
  2545. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2546. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2547. auto host = "target.invalid";
  2548. Server svr;
  2549. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2550. res.set_content("Hello World!", "text/plain");
  2551. });
  2552. auto port = svr.bind_to_any_port("127.0.0.1");
  2553. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2554. auto se = detail::scope_exit([&] {
  2555. svr.stop();
  2556. thread.join();
  2557. ASSERT_FALSE(svr.is_running());
  2558. });
  2559. svr.wait_until_ready();
  2560. Client cli(host, port);
  2561. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2562. auto res = cli.Get("/hi");
  2563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2564. EXPECT_EQ(StatusCode::OK_200, res->status);
  2565. }
  2566. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2567. // An empty mapped value must leave host_ as the connection target. Without
  2568. // that guard the empty value would become the host argument, getaddrinfo
  2569. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2570. // loopback - silently connecting somewhere the caller never asked for.
  2571. // The server listens on loopback, so such a fallback would succeed and is
  2572. // therefore observable as a failure of this test.
  2573. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2574. Server svr;
  2575. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2576. res.set_content("Hello World!", "text/plain");
  2577. });
  2578. auto port = svr.bind_to_any_port(HOST);
  2579. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2580. auto se = detail::scope_exit([&] {
  2581. svr.stop();
  2582. thread.join();
  2583. ASSERT_FALSE(svr.is_running());
  2584. });
  2585. svr.wait_until_ready();
  2586. Client cli(blackhole, port);
  2587. cli.set_hostname_addr_map({{blackhole, ""}});
  2588. cli.set_connection_timeout(1);
  2589. auto res = cli.Get("/hi");
  2590. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2591. }
  2592. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2593. auto host = "httpbingo.org";
  2594. auto path = std::string{"/absolute-redirect/3"};
  2595. #ifdef CPPHTTPLIB_SSL_ENABLED
  2596. SSLClient cli(host);
  2597. #else
  2598. Client cli(host);
  2599. #endif
  2600. cli.set_follow_location(true);
  2601. auto res = cli.Get(path);
  2602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2603. EXPECT_EQ(StatusCode::OK_200, res->status);
  2604. }
  2605. TEST(RedirectTest, Redirect_Online) {
  2606. auto host = "httpbingo.org";
  2607. auto path = std::string{"/redirect/3"};
  2608. #ifdef CPPHTTPLIB_SSL_ENABLED
  2609. SSLClient cli(host);
  2610. #else
  2611. Client cli(host);
  2612. #endif
  2613. cli.set_follow_location(true);
  2614. auto res = cli.Get(path);
  2615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2616. EXPECT_EQ(StatusCode::OK_200, res->status);
  2617. }
  2618. TEST(RelativeRedirectTest, Redirect_Online) {
  2619. auto host = "httpbingo.org";
  2620. auto path = std::string{"/relative-redirect/3"};
  2621. #ifdef CPPHTTPLIB_SSL_ENABLED
  2622. SSLClient cli(host);
  2623. #else
  2624. Client cli(host);
  2625. #endif
  2626. cli.set_follow_location(true);
  2627. auto res = cli.Get(path);
  2628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2629. EXPECT_EQ(StatusCode::OK_200, res->status);
  2630. }
  2631. TEST(TooManyRedirectTest, Redirect_Online) {
  2632. auto host = "httpbingo.org";
  2633. auto path = std::string{"/redirect/21"};
  2634. #ifdef CPPHTTPLIB_SSL_ENABLED
  2635. SSLClient cli(host);
  2636. #else
  2637. Client cli(host);
  2638. #endif
  2639. cli.set_follow_location(true);
  2640. auto res = cli.Get(path);
  2641. ASSERT_TRUE(!res);
  2642. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2643. }
  2644. #ifdef CPPHTTPLIB_SSL_ENABLED
  2645. TEST(YahooRedirectTest, Redirect_Online) {
  2646. Client cli("yahoo.com");
  2647. auto res = cli.Get("/");
  2648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2649. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2650. cli.set_follow_location(true);
  2651. res = cli.Get("/");
  2652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2653. EXPECT_EQ(StatusCode::OK_200, res->status);
  2654. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2655. }
  2656. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2657. #define REDIR_HOST "httpbingo.org"
  2658. #define REDIR_PATH "/redirect-to"
  2659. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2660. SSLClient cli(REDIR_HOST);
  2661. cli.set_follow_location(true);
  2662. auto res =
  2663. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2665. EXPECT_EQ(StatusCode::OK_200, res->status);
  2666. }
  2667. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2668. SSLClient cli(REDIR_HOST);
  2669. cli.set_follow_location(true);
  2670. Params params;
  2671. params.emplace("url", "http://example.com");
  2672. params.emplace("status_code", "302");
  2673. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2675. EXPECT_EQ(StatusCode::OK_200, res->status);
  2676. }
  2677. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2678. SSLClient cli(REDIR_HOST);
  2679. cli.set_follow_location(true);
  2680. Params params;
  2681. params.emplace("url", "http://example.com");
  2682. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2684. EXPECT_EQ(StatusCode::OK_200, res->status);
  2685. }
  2686. TEST(UrlWithSpace, Redirect_Online) {
  2687. SSLClient cli("edge.forgecdn.net");
  2688. cli.set_follow_location(true);
  2689. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2691. EXPECT_EQ(StatusCode::OK_200, res->status);
  2692. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2693. }
  2694. #endif
  2695. #if !defined(_WIN32) && !defined(_WIN64)
  2696. TEST(ReceiveSignals, Signal) {
  2697. auto setupSignalHandlers = []() {
  2698. struct sigaction act;
  2699. sigemptyset(&act.sa_mask);
  2700. act.sa_flags = SA_SIGINFO;
  2701. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2702. switch (sig) {
  2703. case SIGINT:
  2704. default: break;
  2705. }
  2706. };
  2707. ::sigaction(SIGINT, &act, nullptr);
  2708. };
  2709. Server svr;
  2710. int port = 0;
  2711. auto thread = std::thread([&]() {
  2712. setupSignalHandlers();
  2713. port = svr.bind_to_any_port(HOST);
  2714. svr.listen_after_bind();
  2715. });
  2716. auto se = detail::scope_exit([&] {
  2717. svr.stop();
  2718. thread.join();
  2719. ASSERT_FALSE(svr.is_running());
  2720. });
  2721. svr.wait_until_ready();
  2722. ASSERT_TRUE(svr.is_running());
  2723. pthread_kill(thread.native_handle(), SIGINT);
  2724. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2725. ASSERT_TRUE(svr.is_running());
  2726. }
  2727. #endif
  2728. TEST(RedirectToDifferentPort, Redirect) {
  2729. Server svr1;
  2730. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2731. res.set_content("Hello World!", "text/plain");
  2732. });
  2733. int svr1_port = 0;
  2734. auto thread1 = std::thread([&]() {
  2735. svr1_port = svr1.bind_to_any_port(HOST);
  2736. svr1.listen_after_bind();
  2737. });
  2738. Server svr2;
  2739. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2740. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2741. });
  2742. int svr2_port = 0;
  2743. auto thread2 = std::thread([&]() {
  2744. svr2_port = svr2.bind_to_any_port(HOST);
  2745. svr2.listen_after_bind();
  2746. });
  2747. auto se = detail::scope_exit([&] {
  2748. svr2.stop();
  2749. thread2.join();
  2750. svr1.stop();
  2751. thread1.join();
  2752. ASSERT_FALSE(svr2.is_running());
  2753. ASSERT_FALSE(svr1.is_running());
  2754. });
  2755. svr1.wait_until_ready();
  2756. svr2.wait_until_ready();
  2757. Client cli("localhost", svr2_port);
  2758. cli.set_follow_location(true);
  2759. auto res = cli.Get("/2");
  2760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2761. EXPECT_EQ(StatusCode::OK_200, res->status);
  2762. EXPECT_EQ("Hello World!", res->body);
  2763. }
  2764. static void
  2765. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2766. Server svr1;
  2767. std::string captured_authorization;
  2768. svr1.Get("/target", [&](const Request &req, Response &res) {
  2769. captured_authorization = req.get_header_value("Authorization");
  2770. res.set_content("OK", "text/plain");
  2771. });
  2772. int svr1_port = 0;
  2773. auto thread1 = std::thread([&]() {
  2774. svr1_port = svr1.bind_to_any_port(HOST);
  2775. svr1.listen_after_bind();
  2776. });
  2777. Server svr2;
  2778. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2779. res.set_redirect(
  2780. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2781. });
  2782. int svr2_port = 0;
  2783. auto thread2 = std::thread([&]() {
  2784. svr2_port = svr2.bind_to_any_port(HOST);
  2785. svr2.listen_after_bind();
  2786. });
  2787. auto se = detail::scope_exit([&] {
  2788. svr2.stop();
  2789. thread2.join();
  2790. svr1.stop();
  2791. thread1.join();
  2792. ASSERT_FALSE(svr2.is_running());
  2793. ASSERT_FALSE(svr1.is_running());
  2794. });
  2795. svr1.wait_until_ready();
  2796. svr2.wait_until_ready();
  2797. Client cli("localhost", svr2_port);
  2798. cli.set_follow_location(true);
  2799. set_auth(cli);
  2800. auto res = cli.Get("/redir");
  2801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2802. EXPECT_EQ(StatusCode::OK_200, res->status);
  2803. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2804. EXPECT_TRUE(captured_authorization.empty());
  2805. }
  2806. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2807. TestDoNotForwardCredentialsOnRedirect(
  2808. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2809. }
  2810. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2811. TestDoNotForwardCredentialsOnRedirect(
  2812. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2813. }
  2814. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2815. Server svr1;
  2816. std::string captured_cookie;
  2817. bool target_hit = false;
  2818. svr1.Get("/target", [&](const Request &req, Response &res) {
  2819. captured_cookie = req.get_header_value("Cookie");
  2820. target_hit = true;
  2821. res.set_content("OK", "text/plain");
  2822. });
  2823. int svr1_port = 0;
  2824. auto thread1 = std::thread([&]() {
  2825. svr1_port = svr1.bind_to_any_port(HOST);
  2826. svr1.listen_after_bind();
  2827. });
  2828. Server svr2;
  2829. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2830. res.set_redirect(
  2831. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2832. });
  2833. int svr2_port = 0;
  2834. auto thread2 = std::thread([&]() {
  2835. svr2_port = svr2.bind_to_any_port(HOST);
  2836. svr2.listen_after_bind();
  2837. });
  2838. auto se = detail::scope_exit([&] {
  2839. svr2.stop();
  2840. thread2.join();
  2841. svr1.stop();
  2842. thread1.join();
  2843. ASSERT_FALSE(svr2.is_running());
  2844. ASSERT_FALSE(svr1.is_running());
  2845. });
  2846. svr1.wait_until_ready();
  2847. svr2.wait_until_ready();
  2848. Client cli("localhost", svr2_port);
  2849. cli.set_follow_location(true);
  2850. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2851. auto res = cli.Get("/redir", headers);
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. EXPECT_EQ(StatusCode::OK_200, res->status);
  2854. EXPECT_TRUE(target_hit);
  2855. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2856. EXPECT_TRUE(captured_cookie.empty());
  2857. }
  2858. TEST(RedirectToSamePort, ForwardCookie) {
  2859. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2860. // header so that ordinary session flows keep working.
  2861. Server svr;
  2862. std::string captured_cookie;
  2863. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2864. res.set_redirect("/target", 302);
  2865. });
  2866. svr.Get("/target", [&](const Request &req, Response &res) {
  2867. captured_cookie = req.get_header_value("Cookie");
  2868. res.set_content("OK", "text/plain");
  2869. });
  2870. auto port = svr.bind_to_any_port(HOST);
  2871. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2872. auto se = detail::scope_exit([&] {
  2873. svr.stop();
  2874. thread.join();
  2875. ASSERT_FALSE(svr.is_running());
  2876. });
  2877. svr.wait_until_ready();
  2878. Client cli(HOST, port);
  2879. cli.set_follow_location(true);
  2880. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2881. auto res = cli.Get("/redir", headers);
  2882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2883. EXPECT_EQ(StatusCode::OK_200, res->status);
  2884. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2885. }
  2886. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2887. Server svr;
  2888. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2889. // Port number that overflows int — should not crash
  2890. res.set_redirect("http://localhost:99999999999999999999/target");
  2891. });
  2892. auto port = svr.bind_to_any_port(HOST);
  2893. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2894. auto se = detail::scope_exit([&] {
  2895. svr.stop();
  2896. thread.join();
  2897. ASSERT_FALSE(svr.is_running());
  2898. });
  2899. svr.wait_until_ready();
  2900. Client cli(HOST, port);
  2901. cli.set_follow_location(true);
  2902. auto res = cli.Get("/redir");
  2903. // Should fail gracefully, not crash (no valid response due to bad port)
  2904. EXPECT_FALSE(res);
  2905. }
  2906. TEST(RedirectFromPageWithContent, Redirect) {
  2907. Server svr;
  2908. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2909. res.set_content("___", "text/plain");
  2910. res.set_redirect("/2");
  2911. });
  2912. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2913. res.set_content("Hello World!", "text/plain");
  2914. });
  2915. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2916. auto se = detail::scope_exit([&] {
  2917. svr.stop();
  2918. th.join();
  2919. ASSERT_FALSE(svr.is_running());
  2920. });
  2921. svr.wait_until_ready();
  2922. {
  2923. Client cli("localhost", PORT);
  2924. cli.set_follow_location(true);
  2925. std::string body;
  2926. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2927. body.append(data, data_length);
  2928. return true;
  2929. });
  2930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2931. EXPECT_EQ(StatusCode::OK_200, res->status);
  2932. EXPECT_EQ("Hello World!", body);
  2933. }
  2934. {
  2935. Client cli("localhost", PORT);
  2936. std::string body;
  2937. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2938. body.append(data, data_length);
  2939. return true;
  2940. });
  2941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2942. EXPECT_EQ(StatusCode::Found_302, res->status);
  2943. EXPECT_EQ("___", body);
  2944. }
  2945. }
  2946. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2947. Server svr;
  2948. auto port_str = std::to_string(PORT);
  2949. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2950. auto expected_host = "[::1]:" + port_str;
  2951. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2952. res.set_content("___", "text/plain");
  2953. // res.set_redirect("/2");
  2954. res.set_redirect(redirect_url);
  2955. });
  2956. svr.Get("/2", [&](const Request &req, Response &res) {
  2957. auto host_header = req.headers.find("Host");
  2958. ASSERT_TRUE(host_header != req.headers.end());
  2959. EXPECT_EQ(expected_host, host_header->second);
  2960. res.set_content("Hello World!", "text/plain");
  2961. });
  2962. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2963. auto se = detail::scope_exit([&] {
  2964. svr.stop();
  2965. th.join();
  2966. ASSERT_FALSE(svr.is_running());
  2967. });
  2968. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2969. // actually starts anything, so the condition !svr.is_running() will
  2970. // always remain true, and the loop never stops.
  2971. // This basically counts how many milliseconds have passed since the
  2972. // call to svr.listen(), and if after 5 seconds nothing started yet
  2973. // aborts the test.
  2974. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2975. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2976. ASSERT_LT(milliseconds, 5000U);
  2977. }
  2978. {
  2979. Client cli("::1", PORT);
  2980. cli.set_follow_location(true);
  2981. std::string body;
  2982. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2983. body.append(data, data_length);
  2984. return true;
  2985. });
  2986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2987. EXPECT_EQ(StatusCode::OK_200, res->status);
  2988. EXPECT_EQ("Hello World!", body);
  2989. }
  2990. {
  2991. Client cli("::1", PORT);
  2992. std::string body;
  2993. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2994. body.append(data, data_length);
  2995. return true;
  2996. });
  2997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2998. EXPECT_EQ(StatusCode::Found_302, res->status);
  2999. EXPECT_EQ("___", body);
  3000. }
  3001. }
  3002. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3003. Server svr;
  3004. svr.Get("/foo", [](const Request &req, Response &res) {
  3005. auto a = req.params.find("a");
  3006. if (a != req.params.end()) {
  3007. res.set_content((*a).second, "text/plain");
  3008. res.status = StatusCode::OK_200;
  3009. } else {
  3010. res.status = StatusCode::BadRequest_400;
  3011. }
  3012. });
  3013. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3014. auto se = detail::scope_exit([&] {
  3015. svr.stop();
  3016. thread.join();
  3017. ASSERT_FALSE(svr.is_running());
  3018. });
  3019. svr.wait_until_ready();
  3020. {
  3021. Client cli(HOST, PORT);
  3022. cli.set_path_encode(false);
  3023. auto res = cli.Get("/foo?a=explicitly+encoded");
  3024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3025. EXPECT_EQ(StatusCode::OK_200, res->status);
  3026. // This expects it back with a space, as the `+` won't have been
  3027. // url-encoded, and server-side the params get decoded turning `+`
  3028. // into spaces.
  3029. EXPECT_EQ("explicitly encoded", res->body);
  3030. }
  3031. }
  3032. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3033. // When path encoding is disabled the client must transmit the supplied
  3034. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3035. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3036. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3037. // than a space (0x20). Assert on the raw wire target to catch this.
  3038. Server svr;
  3039. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3040. svr.Get("/foo", [&](const Request &req, Response &res) {
  3041. EXPECT_EQ(expected_target, req.target);
  3042. res.status = StatusCode::OK_200;
  3043. });
  3044. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3045. auto se = detail::scope_exit([&] {
  3046. svr.stop();
  3047. thread.join();
  3048. ASSERT_FALSE(svr.is_running());
  3049. });
  3050. svr.wait_until_ready();
  3051. {
  3052. Client cli(HOST, PORT);
  3053. cli.set_path_encode(false);
  3054. auto res = cli.Get(expected_target.c_str());
  3055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3056. EXPECT_EQ(StatusCode::OK_200, res->status);
  3057. }
  3058. }
  3059. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3060. // `open_stream()` used to skip the path encoding that the buffered send
  3061. // path applies, so the same `path` produced different bytes in the request
  3062. // line depending on which API was used. Assert the two agree.
  3063. Server svr;
  3064. std::string target;
  3065. svr.Get(".*", [&](const Request &req, Response &res) {
  3066. target = req.target;
  3067. res.status = StatusCode::OK_200;
  3068. });
  3069. auto port = svr.bind_to_any_port(HOST);
  3070. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3071. auto se = detail::scope_exit([&] {
  3072. svr.stop();
  3073. thread.join();
  3074. ASSERT_FALSE(svr.is_running());
  3075. });
  3076. svr.wait_until_ready();
  3077. struct {
  3078. const char *path;
  3079. const char *expected;
  3080. } cases[] = {
  3081. {"/a b?x=1", "/a%20b?x=1"},
  3082. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3083. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3084. };
  3085. for (const auto &c : cases) {
  3086. Client cli(HOST, port);
  3087. target.clear();
  3088. auto res = cli.Get(c.path);
  3089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3090. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3091. auto buffered_target = target;
  3092. target.clear();
  3093. auto handle = cli.open_stream("GET", c.path);
  3094. EXPECT_TRUE(handle.is_valid())
  3095. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3096. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3097. }
  3098. }
  3099. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3100. // The `set_path_encode(false)` contract — transmit the supplied target
  3101. // verbatim — must hold for the streaming API too.
  3102. Server svr;
  3103. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3104. std::string target;
  3105. svr.Get("/foo", [&](const Request &req, Response &res) {
  3106. target = req.target;
  3107. res.status = StatusCode::OK_200;
  3108. });
  3109. auto port = svr.bind_to_any_port(HOST);
  3110. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3111. auto se = detail::scope_exit([&] {
  3112. svr.stop();
  3113. thread.join();
  3114. ASSERT_FALSE(svr.is_running());
  3115. });
  3116. svr.wait_until_ready();
  3117. {
  3118. Client cli(HOST, port);
  3119. cli.set_path_encode(false);
  3120. auto handle = cli.open_stream("GET", expected_target);
  3121. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3122. EXPECT_EQ(expected_target, target);
  3123. }
  3124. }
  3125. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3126. // With path encoding enabled a CR/LF in the target is percent-encoded
  3127. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3128. // write_request_line still backstops `set_path_encode(false)`, which is
  3129. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3130. Server svr;
  3131. // Captured before routing: the decoded path contains a newline, which a
  3132. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3133. std::string target;
  3134. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3135. target = req.target;
  3136. res.status = StatusCode::OK_200;
  3137. return Server::HandlerResponse::Handled;
  3138. });
  3139. auto port = svr.bind_to_any_port(HOST);
  3140. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3141. auto se = detail::scope_exit([&] {
  3142. svr.stop();
  3143. thread.join();
  3144. ASSERT_FALSE(svr.is_running());
  3145. });
  3146. svr.wait_until_ready();
  3147. {
  3148. Client cli(HOST, port);
  3149. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3150. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3151. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3152. }
  3153. }
  3154. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3155. // Nothing may reach the wire: a raw CR/LF target would split the request
  3156. // line and inject headers.
  3157. Server svr;
  3158. // Pre-routing so that "not called" means nothing reached the server at all,
  3159. // rather than merely failing to match a handler pattern.
  3160. auto handler_called = false;
  3161. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3162. handler_called = true;
  3163. res.status = StatusCode::OK_200;
  3164. return Server::HandlerResponse::Handled;
  3165. });
  3166. auto port = svr.bind_to_any_port(HOST);
  3167. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3168. auto se = detail::scope_exit([&] {
  3169. svr.stop();
  3170. thread.join();
  3171. ASSERT_FALSE(svr.is_running());
  3172. });
  3173. svr.wait_until_ready();
  3174. {
  3175. Client cli(HOST, port);
  3176. cli.set_path_encode(false);
  3177. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3178. EXPECT_FALSE(handle.is_valid());
  3179. EXPECT_EQ(Error::Write, handle.error);
  3180. EXPECT_FALSE(handler_called);
  3181. }
  3182. }
  3183. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3184. // Which of the two branches runs is decided by whether the query component
  3185. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3186. // an empty query and must still fall back to building one from
  3187. // `req.params`, while a non-empty query must win over `req.params`.
  3188. Server svr;
  3189. std::string target;
  3190. svr.Get("/foo", [&](const Request &req, Response &res) {
  3191. target = req.target;
  3192. res.status = StatusCode::OK_200;
  3193. });
  3194. auto port = svr.bind_to_any_port(HOST);
  3195. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3196. auto se = detail::scope_exit([&] {
  3197. svr.stop();
  3198. thread.join();
  3199. ASSERT_FALSE(svr.is_running());
  3200. });
  3201. svr.wait_until_ready();
  3202. {
  3203. // Trailing `?` -> empty query component -> `req.params` is used.
  3204. Client cli(HOST, port);
  3205. Request req;
  3206. req.method = "GET";
  3207. req.path = "/foo?";
  3208. req.params.emplace("a", "1");
  3209. target.clear();
  3210. auto res = cli.send(req);
  3211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3212. EXPECT_EQ("/foo?a=1", target);
  3213. }
  3214. {
  3215. // Non-empty query in `req.path` -> `req.params` is not appended.
  3216. Client cli(HOST, port);
  3217. Request req;
  3218. req.method = "GET";
  3219. req.path = "/foo?b=2";
  3220. req.params.emplace("a", "1");
  3221. target.clear();
  3222. auto res = cli.send(req);
  3223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3224. EXPECT_EQ("/foo?b=2", target);
  3225. }
  3226. }
  3227. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3228. Server svr;
  3229. svr.Get("/", [](const Request &req, Response &) {
  3230. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3231. });
  3232. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3233. auto se = detail::scope_exit([&] {
  3234. svr.stop();
  3235. thread.join();
  3236. ASSERT_FALSE(svr.is_running());
  3237. });
  3238. svr.wait_until_ready();
  3239. {
  3240. Client cli(HOST, PORT);
  3241. cli.set_path_encode(false);
  3242. auto res = cli.Get("/?something=%0A");
  3243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3244. EXPECT_EQ(StatusCode::OK_200, res->status);
  3245. }
  3246. }
  3247. TEST(BindServerTest, BindDualStack) {
  3248. Server svr;
  3249. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3250. res.set_content("Hello World!", "text/plain");
  3251. });
  3252. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3253. auto se = detail::scope_exit([&] {
  3254. svr.stop();
  3255. thread.join();
  3256. ASSERT_FALSE(svr.is_running());
  3257. });
  3258. svr.wait_until_ready();
  3259. {
  3260. Client cli("127.0.0.1", PORT);
  3261. auto res = cli.Get("/1");
  3262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3263. EXPECT_EQ(StatusCode::OK_200, res->status);
  3264. EXPECT_EQ("Hello World!", res->body);
  3265. }
  3266. {
  3267. Client cli("::1", PORT);
  3268. auto res = cli.Get("/1");
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. EXPECT_EQ(StatusCode::OK_200, res->status);
  3271. EXPECT_EQ("Hello World!", res->body);
  3272. }
  3273. }
  3274. TEST(BindServerTest, BindAndListenSeparately) {
  3275. Server svr;
  3276. int port = svr.bind_to_any_port("0.0.0.0");
  3277. ASSERT_TRUE(svr.is_valid());
  3278. ASSERT_TRUE(port > 0);
  3279. svr.stop();
  3280. }
  3281. // Reports whether anything is still listening on a loopback port. A plain
  3282. // connect() is used instead of a Client request because a socket left bound by
  3283. // mistake accepts the connection into its backlog and never answers, which
  3284. // would hang the test instead of failing it.
  3285. static bool is_loopback_port_accepting(int port) {
  3286. sockaddr_in addr{};
  3287. addr.sin_family = AF_INET;
  3288. addr.sin_port = htons(static_cast<uint16_t>(port));
  3289. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3290. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3291. EXPECT_NE(sock, INVALID_SOCKET);
  3292. if (sock == INVALID_SOCKET) { return false; }
  3293. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3294. static_cast<socklen_t>(sizeof(addr)));
  3295. detail::close_socket(sock);
  3296. return ret == 0;
  3297. }
  3298. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3299. Server svr;
  3300. auto port = svr.bind_to_any_port("127.0.0.1");
  3301. ASSERT_TRUE(port > 0);
  3302. svr.stop();
  3303. // bind_to_any_port() already called listen(2), so until stop() closed the
  3304. // descriptor the port kept accepting connections into the backlog. ASSERT
  3305. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3306. // below blocks forever in the accept loop.
  3307. ASSERT_FALSE(is_loopback_port_accepting(port));
  3308. // Nothing is left to accept on, so listen_after_bind() must report failure
  3309. // instead of returning success without ever serving.
  3310. EXPECT_FALSE(svr.listen_after_bind());
  3311. // The failed listen marks the server decommissioned, so a waiter returns
  3312. // instead of spinning forever.
  3313. svr.wait_until_ready();
  3314. }
  3315. #ifdef CPPHTTPLIB_SSL_ENABLED
  3316. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3317. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3318. CLIENT_CA_CERT_DIR);
  3319. int port = svr.bind_to_any_port("0.0.0.0");
  3320. ASSERT_TRUE(svr.is_valid());
  3321. ASSERT_TRUE(port > 0);
  3322. svr.stop();
  3323. }
  3324. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3325. // or a rejected CustomRoute() registration would not stop the server binding.
  3326. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3327. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3328. CLIENT_CA_CERT_DIR);
  3329. ASSERT_TRUE(svr.is_valid());
  3330. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3331. EXPECT_FALSE(svr.is_valid());
  3332. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3333. }
  3334. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3335. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3336. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3337. int port = svr.bind_to_any_port("0.0.0.0");
  3338. ASSERT_TRUE(svr.is_valid());
  3339. ASSERT_TRUE(port > 0);
  3340. svr.stop();
  3341. }
  3342. TEST(BindServerTest, UpdateCertsPem) {
  3343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3344. int port = svr.bind_to_any_port("0.0.0.0");
  3345. ASSERT_TRUE(svr.is_valid());
  3346. ASSERT_TRUE(port > 0);
  3347. // Read PEM files
  3348. std::string cert_pem, key_pem, ca_pem;
  3349. read_file(SERVER_CERT_FILE, cert_pem);
  3350. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3351. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3352. // Update server certificates using PEM API
  3353. ASSERT_TRUE(
  3354. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3355. ASSERT_TRUE(svr.is_valid());
  3356. svr.stop();
  3357. }
  3358. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3359. // Start server with client CA (enables client auth)
  3360. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3361. ASSERT_TRUE(svr.is_valid());
  3362. bool handler_called = false;
  3363. svr.Get("/test", [&](const Request &req, Response &res) {
  3364. handler_called = true;
  3365. // Verify client certificate is present
  3366. auto cert = req.peer_cert();
  3367. EXPECT_TRUE(static_cast<bool>(cert));
  3368. res.set_content("ok", "text/plain");
  3369. });
  3370. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3371. auto se = detail::scope_exit([&] {
  3372. svr.stop();
  3373. t.join();
  3374. ASSERT_FALSE(svr.is_running());
  3375. });
  3376. svr.wait_until_ready();
  3377. // Read PEM files
  3378. std::string cert_pem, key_pem, ca_pem;
  3379. read_file(SERVER_CERT_FILE, cert_pem);
  3380. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3381. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3382. // Update server certificates and client CA using PEM API while server running
  3383. ASSERT_TRUE(
  3384. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3385. // Connect with client certificate
  3386. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3387. cli.enable_server_certificate_verification(false);
  3388. cli.set_connection_timeout(30);
  3389. auto res = cli.Get("/test");
  3390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3391. ASSERT_EQ(StatusCode::OK_200, res->status);
  3392. ASSERT_TRUE(handler_called);
  3393. EXPECT_EQ("ok", res->body);
  3394. }
  3395. #endif
  3396. TEST(ErrorHandlerTest, ContentLength) {
  3397. Server svr;
  3398. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3399. res.status = StatusCode::OK_200;
  3400. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3401. "text/html"); // <= Content-Length still 13
  3402. });
  3403. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3404. res.set_content("Hello World!\n", "text/plain");
  3405. res.status = 524;
  3406. });
  3407. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3408. auto se = detail::scope_exit([&] {
  3409. svr.stop();
  3410. thread.join();
  3411. ASSERT_FALSE(svr.is_running());
  3412. });
  3413. svr.wait_until_ready();
  3414. {
  3415. Client cli(HOST, PORT);
  3416. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3418. EXPECT_EQ(StatusCode::OK_200, res->status);
  3419. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3420. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3421. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3422. }
  3423. }
  3424. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3425. TEST(ExceptionTest, WithoutExceptionHandler) {
  3426. Server svr;
  3427. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3428. throw std::runtime_error("exception...");
  3429. });
  3430. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3431. throw std::runtime_error("exception\r\n...");
  3432. });
  3433. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3434. auto se = detail::scope_exit([&] {
  3435. svr.stop();
  3436. listen_thread.join();
  3437. ASSERT_FALSE(svr.is_running());
  3438. });
  3439. svr.wait_until_ready();
  3440. Client cli("localhost", PORT);
  3441. {
  3442. auto res = cli.Get("/exception");
  3443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3444. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3445. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3446. }
  3447. {
  3448. auto res = cli.Get("/unknown");
  3449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3450. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3451. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3452. }
  3453. }
  3454. TEST(ExceptionTest, WithExceptionHandler) {
  3455. Server svr;
  3456. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3457. std::exception_ptr ep) {
  3458. EXPECT_FALSE(ep == nullptr);
  3459. try {
  3460. std::rethrow_exception(ep);
  3461. } catch (std::exception &e) {
  3462. EXPECT_EQ("abc", std::string(e.what()));
  3463. } catch (...) {}
  3464. res.status = StatusCode::InternalServerError_500;
  3465. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3466. "text/html"); // <= Content-Length still 13 at this point
  3467. });
  3468. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3469. res.set_content("Hello World!\n", "text/plain");
  3470. throw std::runtime_error("abc");
  3471. });
  3472. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3473. auto se = detail::scope_exit([&] {
  3474. svr.stop();
  3475. thread.join();
  3476. ASSERT_FALSE(svr.is_running());
  3477. });
  3478. svr.wait_until_ready();
  3479. for (size_t i = 0; i < 10; i++) {
  3480. Client cli(HOST, PORT);
  3481. for (size_t j = 0; j < 100; j++) {
  3482. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3484. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3485. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3486. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3487. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3488. }
  3489. cli.set_keep_alive(true);
  3490. for (size_t j = 0; j < 100; j++) {
  3491. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3493. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3494. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3495. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3496. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3497. }
  3498. }
  3499. }
  3500. TEST(ExceptionTest, AndErrorHandler) {
  3501. Server svr;
  3502. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3503. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3504. });
  3505. svr.set_exception_handler(
  3506. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3507. EXPECT_FALSE(ep == nullptr);
  3508. try {
  3509. std::rethrow_exception(ep);
  3510. } catch (std::exception &e) {
  3511. res.set_content(e.what(), "text/html");
  3512. } catch (...) {}
  3513. res.status = StatusCode::InternalServerError_500;
  3514. });
  3515. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3516. throw std::runtime_error("EXCEPTION");
  3517. });
  3518. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3519. res.set_content("ERROR", "text/html");
  3520. res.status = StatusCode::InternalServerError_500;
  3521. });
  3522. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3523. auto se = detail::scope_exit([&] {
  3524. svr.stop();
  3525. thread.join();
  3526. ASSERT_FALSE(svr.is_running());
  3527. });
  3528. svr.wait_until_ready();
  3529. Client cli(HOST, PORT);
  3530. {
  3531. auto res = cli.Get("/exception");
  3532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3533. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3534. EXPECT_EQ("EXCEPTION", res->body);
  3535. }
  3536. {
  3537. auto res = cli.Get("/error");
  3538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3539. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3540. EXPECT_EQ("ERROR", res->body);
  3541. }
  3542. {
  3543. auto res = cli.Get("/invalid");
  3544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3545. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3546. EXPECT_EQ("NOT_FOUND", res->body);
  3547. }
  3548. }
  3549. #endif
  3550. TEST(NoContentTest, ContentLength) {
  3551. Server svr;
  3552. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3553. res.status = StatusCode::NoContent_204;
  3554. });
  3555. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3556. auto se = detail::scope_exit([&] {
  3557. svr.stop();
  3558. thread.join();
  3559. ASSERT_FALSE(svr.is_running());
  3560. });
  3561. svr.wait_until_ready();
  3562. {
  3563. Client cli(HOST, PORT);
  3564. auto res = cli.Get("/hi");
  3565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3566. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3567. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3568. }
  3569. }
  3570. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3571. #ifdef CPPHTTPLIB_SSL_ENABLED
  3572. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3573. ASSERT_TRUE(svr.is_valid());
  3574. #else
  3575. Server svr;
  3576. #endif
  3577. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3578. if (req.path == "/routing_handler") {
  3579. res.set_header("PRE_ROUTING", "on");
  3580. res.set_content("Routing Handler", "text/plain");
  3581. return httplib::Server::HandlerResponse::Handled;
  3582. }
  3583. return httplib::Server::HandlerResponse::Unhandled;
  3584. });
  3585. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3586. res.set_content("Error", "text/html");
  3587. });
  3588. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3589. if (req.path == "/routing_handler") {
  3590. res.set_header("POST_ROUTING", "on");
  3591. }
  3592. });
  3593. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3594. res.set_content("Hello World!\n", "text/plain");
  3595. });
  3596. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3597. auto se = detail::scope_exit([&] {
  3598. svr.stop();
  3599. thread.join();
  3600. ASSERT_FALSE(svr.is_running());
  3601. });
  3602. svr.wait_until_ready();
  3603. {
  3604. #ifdef CPPHTTPLIB_SSL_ENABLED
  3605. SSLClient cli(HOST, PORT);
  3606. cli.enable_server_certificate_verification(false);
  3607. #else
  3608. Client cli(HOST, PORT);
  3609. #endif
  3610. auto res = cli.Get("/routing_handler");
  3611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3612. EXPECT_EQ(StatusCode::OK_200, res->status);
  3613. EXPECT_EQ("Routing Handler", res->body);
  3614. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3615. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3616. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3617. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3618. }
  3619. {
  3620. #ifdef CPPHTTPLIB_SSL_ENABLED
  3621. SSLClient cli(HOST, PORT);
  3622. cli.enable_server_certificate_verification(false);
  3623. #else
  3624. Client cli(HOST, PORT);
  3625. #endif
  3626. auto res = cli.Get("/hi");
  3627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3628. EXPECT_EQ(StatusCode::OK_200, res->status);
  3629. EXPECT_EQ("Hello World!\n", res->body);
  3630. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3631. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3632. }
  3633. {
  3634. #ifdef CPPHTTPLIB_SSL_ENABLED
  3635. SSLClient cli(HOST, PORT);
  3636. cli.enable_server_certificate_verification(false);
  3637. #else
  3638. Client cli(HOST, PORT);
  3639. #endif
  3640. auto res = cli.Get("/aaa");
  3641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3642. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3643. EXPECT_EQ("Error", res->body);
  3644. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3645. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3646. }
  3647. }
  3648. TEST(RequestHandlerTest, PreRequestHandler) {
  3649. auto route_path = "/user/:user";
  3650. Server svr;
  3651. svr.Get("/hi", [](const Request &, Response &res) {
  3652. res.set_content("hi", "text/plain");
  3653. });
  3654. svr.Get(route_path, [](const Request &req, Response &res) {
  3655. res.set_content(req.path_params.at("user"), "text/plain");
  3656. });
  3657. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3658. if (req.matched_route == route_path) {
  3659. auto user = req.path_params.at("user");
  3660. if (user != "john") {
  3661. res.status = StatusCode::Forbidden_403;
  3662. res.set_content("error", "text/html");
  3663. return Server::HandlerResponse::Handled;
  3664. }
  3665. }
  3666. return Server::HandlerResponse::Unhandled;
  3667. });
  3668. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3669. auto se = detail::scope_exit([&] {
  3670. svr.stop();
  3671. thread.join();
  3672. ASSERT_FALSE(svr.is_running());
  3673. });
  3674. svr.wait_until_ready();
  3675. Client cli(HOST, PORT);
  3676. {
  3677. auto res = cli.Get("/hi");
  3678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3679. EXPECT_EQ(StatusCode::OK_200, res->status);
  3680. EXPECT_EQ("hi", res->body);
  3681. }
  3682. {
  3683. auto res = cli.Get("/user/john");
  3684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3685. EXPECT_EQ(StatusCode::OK_200, res->status);
  3686. EXPECT_EQ("john", res->body);
  3687. }
  3688. {
  3689. auto res = cli.Get("/user/invalid-user");
  3690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3691. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3692. EXPECT_EQ("error", res->body);
  3693. }
  3694. }
  3695. // The pre-request handler must run before the request body is read, so a
  3696. // rejected request never forces the server to buffer a (potentially large)
  3697. // body. Here the posted body is larger than the payload limit: if the body
  3698. // were read first the server would answer 413, but because the pre-request
  3699. // handler runs first it answers 403 and the body is never read.
  3700. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3701. Server svr;
  3702. svr.set_payload_max_length(8);
  3703. auto handler_ran = false;
  3704. svr.Post("/reject", [&](const Request &req, Response &res) {
  3705. handler_ran = true;
  3706. res.set_content(req.body, "text/plain");
  3707. });
  3708. svr.Post("/accept", [](const Request &req, Response &res) {
  3709. res.set_content(req.body, "text/plain");
  3710. });
  3711. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3712. if (req.matched_route == "/reject") {
  3713. res.status = StatusCode::Forbidden_403;
  3714. res.set_content("denied", "text/plain");
  3715. return Server::HandlerResponse::Handled;
  3716. }
  3717. return Server::HandlerResponse::Unhandled;
  3718. });
  3719. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3720. auto se = detail::scope_exit([&] {
  3721. svr.stop();
  3722. thread.join();
  3723. ASSERT_FALSE(svr.is_running());
  3724. });
  3725. svr.wait_until_ready();
  3726. Client cli(HOST, PORT);
  3727. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3728. // rejects with 403 before the body is read, so 413 is never reached.
  3729. {
  3730. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3732. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3733. EXPECT_EQ("denied", res->body);
  3734. EXPECT_FALSE(handler_ran);
  3735. }
  3736. // An approved route still reads the body and enforces the payload limit.
  3737. {
  3738. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3740. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3741. }
  3742. }
  3743. TEST(UserDataTest, BasicOperations) {
  3744. httplib::UserData ud;
  3745. // Initially empty
  3746. EXPECT_FALSE(ud.has("key"));
  3747. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3748. // set and get
  3749. ud.set("key", 42);
  3750. EXPECT_TRUE(ud.has("key"));
  3751. auto *p = ud.get<int>("key");
  3752. ASSERT_NE(nullptr, p);
  3753. EXPECT_EQ(42, *p);
  3754. // Type mismatch → nullptr
  3755. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3756. // Overwrite with different type
  3757. ud.set("key", std::string("hello"));
  3758. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3759. auto *s = ud.get<std::string>("key");
  3760. ASSERT_NE(nullptr, s);
  3761. EXPECT_EQ("hello", *s);
  3762. // erase
  3763. ud.erase("key");
  3764. EXPECT_FALSE(ud.has("key"));
  3765. // clear
  3766. ud.set("a", 1);
  3767. ud.set("b", 2);
  3768. ud.clear();
  3769. EXPECT_FALSE(ud.has("a"));
  3770. EXPECT_FALSE(ud.has("b"));
  3771. }
  3772. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3773. struct AuthCtx {
  3774. std::string user_id;
  3775. };
  3776. Server svr;
  3777. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3778. res.user_data.set("auth", AuthCtx{"alice"});
  3779. return Server::HandlerResponse::Unhandled;
  3780. });
  3781. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3782. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3783. ASSERT_NE(nullptr, ctx);
  3784. res.set_content("Hello " + ctx->user_id, "text/plain");
  3785. });
  3786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3787. auto se = detail::scope_exit([&] {
  3788. svr.stop();
  3789. thread.join();
  3790. ASSERT_FALSE(svr.is_running());
  3791. });
  3792. svr.wait_until_ready();
  3793. Client cli(HOST, PORT);
  3794. auto res = cli.Get("/me");
  3795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. EXPECT_EQ("Hello alice", res->body);
  3798. }
  3799. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3800. struct RoleCtx {
  3801. std::string role;
  3802. };
  3803. Server svr;
  3804. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3805. res.user_data.set("role", RoleCtx{"admin"});
  3806. return Server::HandlerResponse::Unhandled;
  3807. });
  3808. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3809. auto *ctx = res.user_data.get<RoleCtx>("role");
  3810. ASSERT_NE(nullptr, ctx);
  3811. res.set_content(ctx->role, "text/plain");
  3812. });
  3813. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3814. auto se = detail::scope_exit([&] {
  3815. svr.stop();
  3816. thread.join();
  3817. ASSERT_FALSE(svr.is_running());
  3818. });
  3819. svr.wait_until_ready();
  3820. Client cli(HOST, PORT);
  3821. auto res = cli.Get("/role");
  3822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3823. EXPECT_EQ(StatusCode::OK_200, res->status);
  3824. EXPECT_EQ("admin", res->body);
  3825. }
  3826. TEST(InvalidFormatTest, StatusCode) {
  3827. Server svr;
  3828. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3829. res.set_content("Hello World!\n", "text/plain");
  3830. res.status = 9999; // Status should be a three-digit code...
  3831. });
  3832. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3833. auto se = detail::scope_exit([&] {
  3834. svr.stop();
  3835. thread.join();
  3836. ASSERT_FALSE(svr.is_running());
  3837. });
  3838. svr.wait_until_ready();
  3839. {
  3840. Client cli(HOST, PORT);
  3841. auto res = cli.Get("/hi");
  3842. ASSERT_FALSE(res);
  3843. }
  3844. }
  3845. TEST(URLFragmentTest, WithFragment) {
  3846. Server svr;
  3847. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3848. EXPECT_TRUE(req.target == "/hi");
  3849. });
  3850. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3851. auto se = detail::scope_exit([&] {
  3852. svr.stop();
  3853. thread.join();
  3854. ASSERT_FALSE(svr.is_running());
  3855. });
  3856. svr.wait_until_ready();
  3857. {
  3858. Client cli(HOST, PORT);
  3859. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3860. EXPECT_TRUE(res);
  3861. EXPECT_EQ(StatusCode::OK_200, res->status);
  3862. res = cli.Get("/hi%23key1=val1=key2=val2");
  3863. EXPECT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3865. }
  3866. }
  3867. TEST(HeaderWriter, SetHeaderWriter) {
  3868. Server svr;
  3869. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3870. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3871. return detail::write_headers(strm, hdrs);
  3872. });
  3873. svr.Get("/hi", [](const Request &req, Response &res) {
  3874. auto it = req.headers.find("CustomClientHeader");
  3875. EXPECT_TRUE(it != req.headers.end());
  3876. EXPECT_EQ(it->second, "CustomClientValue");
  3877. res.set_content("Hello World!\n", "text/plain");
  3878. });
  3879. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3880. auto se = detail::scope_exit([&] {
  3881. svr.stop();
  3882. thread.join();
  3883. ASSERT_FALSE(svr.is_running());
  3884. });
  3885. svr.wait_until_ready();
  3886. {
  3887. Client cli(HOST, PORT);
  3888. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3889. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3890. return detail::write_headers(strm, hdrs);
  3891. });
  3892. auto res = cli.Get("/hi");
  3893. EXPECT_TRUE(res);
  3894. EXPECT_EQ(StatusCode::OK_200, res->status);
  3895. auto it = res->headers.find("CustomServerHeader");
  3896. EXPECT_TRUE(it != res->headers.end());
  3897. EXPECT_EQ(it->second, "CustomServerValue");
  3898. }
  3899. }
  3900. class ServerTest : public ::testing::Test {
  3901. protected:
  3902. ServerTest()
  3903. : cli_(HOST, PORT)
  3904. #ifdef CPPHTTPLIB_SSL_ENABLED
  3905. ,
  3906. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3907. #endif
  3908. {
  3909. #ifdef CPPHTTPLIB_SSL_ENABLED
  3910. cli_.enable_server_certificate_verification(false);
  3911. #endif
  3912. // Allow LARGE_DATA (100MB) responses
  3913. cli_.set_payload_max_length(200 * 1024 * 1024);
  3914. }
  3915. virtual void SetUp() {
  3916. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3917. svr_.set_payload_max_length(200 * 1024 * 1024);
  3918. svr_.set_mount_point("/", "./www");
  3919. svr_.set_mount_point("/mount", "./www2");
  3920. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3921. svr_.Get("/hi",
  3922. [&](const Request & /*req*/, Response &res) {
  3923. res.set_content("Hello World!", "text/plain");
  3924. })
  3925. .Get("/file_content",
  3926. [&](const Request & /*req*/, Response &res) {
  3927. res.set_file_content("./www/dir/test.html");
  3928. })
  3929. .Get("/file_content_with_content_type",
  3930. [&](const Request & /*req*/, Response &res) {
  3931. res.set_file_content("./www/file", "text/plain");
  3932. })
  3933. .Get("/invalid_file_content",
  3934. [&](const Request & /*req*/, Response &res) {
  3935. res.set_file_content("./www/dir/invalid_file_path");
  3936. })
  3937. .Get("/http_response_splitting",
  3938. [&](const Request & /*req*/, Response &res) {
  3939. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3940. EXPECT_EQ(0U, res.headers.size());
  3941. EXPECT_FALSE(res.has_header("a"));
  3942. res.set_header("a", "1\nSet-Cookie: a=1");
  3943. EXPECT_EQ(0U, res.headers.size());
  3944. EXPECT_FALSE(res.has_header("a"));
  3945. res.set_header("a", "1\rSet-Cookie: a=1");
  3946. EXPECT_EQ(0U, res.headers.size());
  3947. EXPECT_FALSE(res.has_header("a"));
  3948. res.set_header("a\r\nb", "0");
  3949. EXPECT_EQ(0U, res.headers.size());
  3950. EXPECT_FALSE(res.has_header("a"));
  3951. res.set_header("a\rb", "0");
  3952. EXPECT_EQ(0U, res.headers.size());
  3953. EXPECT_FALSE(res.has_header("a"));
  3954. res.set_header("a\nb", "0");
  3955. EXPECT_EQ(0U, res.headers.size());
  3956. EXPECT_FALSE(res.has_header("a"));
  3957. res.set_redirect("1\r\nSet-Cookie: a=1");
  3958. EXPECT_EQ(0U, res.headers.size());
  3959. EXPECT_FALSE(res.has_header("Location"));
  3960. })
  3961. .Get("/slow",
  3962. [&](const Request & /*req*/, Response &res) {
  3963. std::this_thread::sleep_for(std::chrono::seconds(4));
  3964. res.set_content("slow", "text/plain");
  3965. })
  3966. #if 0
  3967. .Post("/slowpost",
  3968. [&](const Request & /*req*/, Response &res) {
  3969. std::this_thread::sleep_for(std::chrono::seconds(2));
  3970. res.set_content("slow", "text/plain");
  3971. })
  3972. #endif
  3973. .Get("/remote_addr",
  3974. [&](const Request &req, Response &res) {
  3975. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3976. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3977. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3978. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3979. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3980. #endif
  3981. res.set_content(req.remote_addr, "text/plain");
  3982. })
  3983. .Get("/local_addr",
  3984. [&](const Request &req, Response &res) {
  3985. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3986. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3987. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3988. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3989. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3990. #endif
  3991. auto local_addr = req.local_addr;
  3992. auto local_port = std::to_string(req.local_port);
  3993. res.set_content(local_addr.append(":").append(local_port),
  3994. "text/plain");
  3995. })
  3996. .Get("/endwith%",
  3997. [&](const Request & /*req*/, Response &res) {
  3998. res.set_content("Hello World!", "text/plain");
  3999. })
  4000. .Get("/a\\+\\+b",
  4001. [&](const Request &req, Response &res) {
  4002. ASSERT_TRUE(req.has_param("a +b"));
  4003. auto val = req.get_param_value("a +b");
  4004. res.set_content(val, "text/plain");
  4005. })
  4006. .Get("/", [&](const Request & /*req*/,
  4007. Response &res) { res.set_redirect("/hi"); })
  4008. .Post("/1",
  4009. [](const Request & /*req*/, Response &res) {
  4010. res.set_redirect("/2", StatusCode::SeeOther_303);
  4011. })
  4012. .Get("/2",
  4013. [](const Request & /*req*/, Response &res) {
  4014. res.set_content("redirected.", "text/plain");
  4015. res.status = StatusCode::OK_200;
  4016. })
  4017. .Post("/person",
  4018. [&](const Request &req, Response &res) {
  4019. if (req.has_param("name") && req.has_param("note")) {
  4020. persons_[req.get_param_value("name")] =
  4021. req.get_param_value("note");
  4022. } else {
  4023. res.status = StatusCode::BadRequest_400;
  4024. }
  4025. })
  4026. .Put("/person",
  4027. [&](const Request &req, Response &res) {
  4028. if (req.has_param("name") && req.has_param("note")) {
  4029. persons_[req.get_param_value("name")] =
  4030. req.get_param_value("note");
  4031. } else {
  4032. res.status = StatusCode::BadRequest_400;
  4033. }
  4034. })
  4035. .Get("/person/(.*)",
  4036. [&](const Request &req, Response &res) {
  4037. string name = req.matches[1];
  4038. if (persons_.find(name) != persons_.end()) {
  4039. auto note = persons_[name];
  4040. res.set_content(note, "text/plain");
  4041. } else {
  4042. res.status = StatusCode::NotFound_404;
  4043. }
  4044. })
  4045. .Delete("/person",
  4046. [&](const Request &req, Response &res) {
  4047. if (req.has_param("name")) {
  4048. string name = req.get_param_value("name");
  4049. if (persons_.find(name) != persons_.end()) {
  4050. persons_.erase(name);
  4051. res.set_content("DELETED", "text/plain");
  4052. } else {
  4053. res.status = StatusCode::NotFound_404;
  4054. }
  4055. } else {
  4056. res.status = StatusCode::BadRequest_400;
  4057. }
  4058. })
  4059. .Post("/x-www-form-urlencoded-json",
  4060. [&](const Request &req, Response &res) {
  4061. auto json = req.get_param_value("json");
  4062. ASSERT_EQ(JSON_DATA, json);
  4063. res.set_content(json, "appliation/json");
  4064. res.status = StatusCode::OK_200;
  4065. })
  4066. .Get("/streamed-chunked",
  4067. [&](const Request & /*req*/, Response &res) {
  4068. res.set_chunked_content_provider(
  4069. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4070. sink.os << "123";
  4071. sink.os << "456";
  4072. sink.os << "789";
  4073. sink.done();
  4074. return true;
  4075. });
  4076. })
  4077. .Get("/streamed-chunked-with-prohibited-trailer",
  4078. [&](const Request & /*req*/, Response &res) {
  4079. auto i = new int(0);
  4080. // Declare both a prohibited trailer (Content-Length) and an
  4081. // allowed one
  4082. res.set_header("Trailer", "Content-Length, X-Allowed");
  4083. res.set_chunked_content_provider(
  4084. "text/plain",
  4085. [i](size_t /*offset*/, DataSink &sink) {
  4086. switch (*i) {
  4087. case 0: sink.os << "123"; break;
  4088. case 1: sink.os << "456"; break;
  4089. case 2: sink.os << "789"; break;
  4090. case 3: {
  4091. sink.done_with_trailer(
  4092. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4093. } break;
  4094. }
  4095. (*i)++;
  4096. return true;
  4097. },
  4098. [i](bool success) {
  4099. EXPECT_TRUE(success);
  4100. delete i;
  4101. });
  4102. })
  4103. .Get("/streamed-chunked2",
  4104. [&](const Request & /*req*/, Response &res) {
  4105. auto i = new int(0);
  4106. res.set_chunked_content_provider(
  4107. "text/plain",
  4108. [i](size_t /*offset*/, DataSink &sink) {
  4109. switch (*i) {
  4110. case 0: sink.os << "123"; break;
  4111. case 1: sink.os << "456"; break;
  4112. case 2: sink.os << "789"; break;
  4113. case 3: sink.done(); break;
  4114. }
  4115. (*i)++;
  4116. return true;
  4117. },
  4118. [i](bool success) {
  4119. EXPECT_TRUE(success);
  4120. delete i;
  4121. });
  4122. })
  4123. .Get("/streamed-chunked-with-trailer",
  4124. [&](const Request & /*req*/, Response &res) {
  4125. auto i = new int(0);
  4126. res.set_header("Trailer", "Dummy1, Dummy2");
  4127. res.set_chunked_content_provider(
  4128. "text/plain",
  4129. [i](size_t /*offset*/, DataSink &sink) {
  4130. switch (*i) {
  4131. case 0: sink.os << "123"; break;
  4132. case 1: sink.os << "456"; break;
  4133. case 2: sink.os << "789"; break;
  4134. case 3: {
  4135. sink.done_with_trailer(
  4136. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4137. } break;
  4138. }
  4139. (*i)++;
  4140. return true;
  4141. },
  4142. [i](bool success) {
  4143. EXPECT_TRUE(success);
  4144. delete i;
  4145. });
  4146. })
  4147. .Get("/streamed",
  4148. [&](const Request & /*req*/, Response &res) {
  4149. res.set_content_provider(
  4150. 6, "text/plain",
  4151. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4152. sink.os << (offset < 3 ? "a" : "b");
  4153. return true;
  4154. });
  4155. })
  4156. .Get("/streamed-without-length",
  4157. [&](const Request & /*req*/, Response &res) {
  4158. auto data = new std::string("abcdefg");
  4159. res.set_content_provider(
  4160. "text/plain",
  4161. [data](size_t offset, DataSink &sink) {
  4162. if (offset < data->size()) {
  4163. sink.os << data->substr(offset);
  4164. }
  4165. sink.done();
  4166. return true;
  4167. },
  4168. [data](bool success) {
  4169. EXPECT_TRUE(success);
  4170. delete data;
  4171. });
  4172. })
  4173. .Get("/streamed-with-range",
  4174. [&](const Request &req, Response &res) {
  4175. auto data = new std::string("abcdefg");
  4176. // An explicit status keeps the server from picking the 206 it
  4177. // would otherwise choose for a ranged request, so the response
  4178. // is not a partial representation.
  4179. auto status = req.get_param_value("status");
  4180. if (status == "200") {
  4181. res.status = StatusCode::OK_200;
  4182. } else if (status == "403") {
  4183. res.status = StatusCode::Forbidden_403;
  4184. }
  4185. res.set_content_provider(
  4186. data->size(), "text/plain",
  4187. [data](size_t offset, size_t length, DataSink &sink) {
  4188. size_t DATA_CHUNK_SIZE = 4;
  4189. const auto &d = *data;
  4190. auto out_len =
  4191. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4192. auto ret =
  4193. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4194. EXPECT_TRUE(ret);
  4195. return true;
  4196. },
  4197. [data, &req](bool success) {
  4198. EXPECT_EQ(success, !req.has_param("error"));
  4199. delete data;
  4200. });
  4201. })
  4202. .Get("/streamed-cancel",
  4203. [&](const Request & /*req*/, Response &res) {
  4204. res.set_content_provider(
  4205. size_t(-1), "text/plain",
  4206. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4207. sink.os << "data_chunk";
  4208. return true;
  4209. });
  4210. })
  4211. .Get("/regex-with-delimiter",
  4212. [&](const Request &req, Response & /*res*/) {
  4213. ASSERT_TRUE(req.has_param("key"));
  4214. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4215. })
  4216. .Get("/with-range",
  4217. [&](const Request & /*req*/, Response &res) {
  4218. res.set_content("abcdefg", "text/plain");
  4219. })
  4220. .Get("/test-start-time",
  4221. [&](const Request &req, Response & /*res*/) {
  4222. EXPECT_NE(req.start_time_,
  4223. std::chrono::steady_clock::time_point::min());
  4224. })
  4225. .Get("/with-range-customized-response",
  4226. [&](const Request & /*req*/, Response &res) {
  4227. res.status = StatusCode::BadRequest_400;
  4228. res.set_content(JSON_DATA, "application/json");
  4229. })
  4230. .Post("/chunked",
  4231. [&](const Request &req, Response & /*res*/) {
  4232. EXPECT_EQ(req.body, "dechunked post body");
  4233. })
  4234. .Post("/large-chunked",
  4235. [&](const Request &req, Response & /*res*/) {
  4236. std::string expected(6 * 30 * 1024u, 'a');
  4237. EXPECT_EQ(req.body, expected);
  4238. })
  4239. .Post("/multipart",
  4240. [&](const Request &req, Response & /*res*/) {
  4241. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4242. req.form.get_field_count("text2") +
  4243. req.form.get_field_count("file3") +
  4244. req.form.get_field_count("file4"));
  4245. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4246. req.form.get_file_count("file2"));
  4247. ASSERT_TRUE(!req.form.has_file("???"));
  4248. ASSERT_TRUE(!req.form.has_field("???"));
  4249. ASSERT_TRUE(req.body.empty());
  4250. {
  4251. const auto &text = req.form.get_field("text1");
  4252. EXPECT_EQ("text default", text);
  4253. }
  4254. {
  4255. const auto &text = req.form.get_field("text2");
  4256. EXPECT_EQ("aωb", text);
  4257. }
  4258. {
  4259. const auto &file = req.form.get_file("file1");
  4260. EXPECT_EQ("hello.txt", file.filename);
  4261. EXPECT_EQ("text/plain", file.content_type);
  4262. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4263. }
  4264. {
  4265. const auto &file = req.form.get_file("file2");
  4266. EXPECT_EQ("world.json", file.filename);
  4267. EXPECT_EQ("application/json", file.content_type);
  4268. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4269. }
  4270. {
  4271. const auto &text = req.form.get_field("file3");
  4272. EXPECT_EQ(0u, text.size());
  4273. }
  4274. {
  4275. const auto &text = req.form.get_field("file4");
  4276. EXPECT_EQ(0u, text.size());
  4277. }
  4278. })
  4279. .Post("/multipart/multi_file_values",
  4280. [&](const Request &req, Response & /*res*/) {
  4281. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4282. req.form.get_field_count("multi_text1"));
  4283. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4284. ASSERT_TRUE(!req.form.has_file("???"));
  4285. ASSERT_TRUE(!req.form.has_field("???"));
  4286. ASSERT_TRUE(req.body.empty());
  4287. {
  4288. const auto &text = req.form.get_field("text");
  4289. EXPECT_EQ("default text", text);
  4290. }
  4291. {
  4292. const auto &text1_values = req.form.get_fields("multi_text1");
  4293. EXPECT_EQ(2u, text1_values.size());
  4294. EXPECT_EQ("aaaaa", text1_values[0]);
  4295. EXPECT_EQ("bbbbb", text1_values[1]);
  4296. }
  4297. {
  4298. const auto &file1_values = req.form.get_files("multi_file1");
  4299. EXPECT_EQ(2u, file1_values.size());
  4300. auto file1 = file1_values[0];
  4301. EXPECT_EQ(file1.filename, "hello.txt");
  4302. EXPECT_EQ(file1.content_type, "text/plain");
  4303. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4304. auto file2 = file1_values[1];
  4305. EXPECT_EQ(file2.filename, "world.json");
  4306. EXPECT_EQ(file2.content_type, "application/json");
  4307. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4308. }
  4309. })
  4310. .Post("/empty",
  4311. [&](const Request &req, Response &res) {
  4312. EXPECT_EQ(req.body, "");
  4313. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4314. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4315. res.set_content("empty", "text/plain");
  4316. })
  4317. .Post("/empty-no-content-type",
  4318. [&](const Request &req, Response &res) {
  4319. EXPECT_EQ(req.body, "");
  4320. EXPECT_FALSE(req.has_header("Content-Type"));
  4321. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4322. res.set_content("empty-no-content-type", "text/plain");
  4323. })
  4324. .Post("/path-only",
  4325. [&](const Request &req, Response &res) {
  4326. EXPECT_EQ(req.body, "");
  4327. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4328. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4329. res.set_content("path-only", "text/plain");
  4330. })
  4331. .Post("/path-headers-only",
  4332. [&](const Request &req, Response &res) {
  4333. EXPECT_EQ(req.body, "");
  4334. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4335. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4336. EXPECT_EQ("world", req.get_header_value("hello"));
  4337. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4338. res.set_content("path-headers-only", "text/plain");
  4339. })
  4340. .Post("/post-large",
  4341. [&](const Request &req, Response &res) {
  4342. EXPECT_EQ(req.body, LARGE_DATA);
  4343. res.set_content(req.body, "text/plain");
  4344. })
  4345. .Post("/post-loopback",
  4346. [&](const Request &, Response &res,
  4347. ContentReader const &content_reader) {
  4348. std::string body;
  4349. content_reader([&](const char *data, size_t data_length) {
  4350. body.append(data, data_length);
  4351. return true;
  4352. });
  4353. res.set_content(body, "text/plain");
  4354. })
  4355. .Put("/put-loopback",
  4356. [&](const Request &, Response &res,
  4357. ContentReader const &content_reader) {
  4358. std::string body;
  4359. content_reader([&](const char *data, size_t data_length) {
  4360. body.append(data, data_length);
  4361. return true;
  4362. });
  4363. res.set_content(body, "text/plain");
  4364. })
  4365. .Patch("/patch-loopback",
  4366. [&](const Request &, Response &res,
  4367. ContentReader const &content_reader) {
  4368. std::string body;
  4369. content_reader([&](const char *data, size_t data_length) {
  4370. body.append(data, data_length);
  4371. return true;
  4372. });
  4373. res.set_content(body, "text/plain");
  4374. })
  4375. .Put("/empty-no-content-type",
  4376. [&](const Request &req, Response &res) {
  4377. EXPECT_EQ(req.body, "");
  4378. EXPECT_FALSE(req.has_header("Content-Type"));
  4379. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4380. res.set_content("empty-no-content-type", "text/plain");
  4381. })
  4382. .Put("/put",
  4383. [&](const Request &req, Response &res) {
  4384. EXPECT_EQ(req.body, "PUT");
  4385. res.set_content(req.body, "text/plain");
  4386. })
  4387. .Put("/put-large",
  4388. [&](const Request &req, Response &res) {
  4389. EXPECT_EQ(req.body, LARGE_DATA);
  4390. res.set_content(req.body, "text/plain");
  4391. })
  4392. .Patch("/patch",
  4393. [&](const Request &req, Response &res) {
  4394. EXPECT_EQ(req.body, "PATCH");
  4395. res.set_content(req.body, "text/plain");
  4396. })
  4397. .Delete("/delete",
  4398. [&](const Request & /*req*/, Response &res) {
  4399. res.set_content("DELETE", "text/plain");
  4400. })
  4401. .Delete("/delete-body",
  4402. [&](const Request &req, Response &res) {
  4403. EXPECT_EQ(req.body, "content");
  4404. res.set_content(req.body, "text/plain");
  4405. })
  4406. .Options(R"(\*)",
  4407. [&](const Request & /*req*/, Response &res) {
  4408. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4409. })
  4410. .CustomRoute("PROPFIND", "/dav/:id",
  4411. [&](const Request &req, Response &res) {
  4412. res.set_header("x-body-size",
  4413. std::to_string(req.body.size()));
  4414. res.set_header("x-matched-route", req.matched_route);
  4415. res.set_header("x-dav-id", req.path_params.at("id"));
  4416. res.status = StatusCode::MultiStatus_207;
  4417. res.set_content(req.body, "application/xml");
  4418. })
  4419. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4420. [&](const Request &req, Response &res) {
  4421. res.set_header("x-dav-match", req.matches[1]);
  4422. res.status = StatusCode::MultiStatus_207;
  4423. })
  4424. .CustomRoute("MKCOL", "/dav-mkcol",
  4425. [&](const Request &req, Response &res) {
  4426. EXPECT_TRUE(req.body.empty());
  4427. res.status = StatusCode::Created_201;
  4428. })
  4429. .CustomRoute(
  4430. "REPORT", "/dav-report",
  4431. [&](const Request & /*req*/, Response &res,
  4432. const ContentReader &content_reader) {
  4433. std::string body;
  4434. content_reader([&](const char *data, size_t data_length) {
  4435. body.append(data, data_length);
  4436. return true;
  4437. });
  4438. res.set_header("x-body-size", std::to_string(body.size()));
  4439. res.status = StatusCode::MultiStatus_207;
  4440. res.set_content(body, "application/xml");
  4441. })
  4442. .Get("/request-target",
  4443. [&](const Request &req, Response & /*res*/) {
  4444. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4445. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4446. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4447. })
  4448. .Get("/long-query-value",
  4449. [&](const Request &req, Response & /*res*/) {
  4450. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4451. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4452. })
  4453. .Get("/too-long-query-value",
  4454. [&](const Request &req, Response & /*res*/) {
  4455. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4456. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4457. })
  4458. .Get("/array-param",
  4459. [&](const Request &req, Response & /*res*/) {
  4460. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4461. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4462. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4463. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4464. })
  4465. .Get("/array-param-values",
  4466. [&](const Request &req, Response & /*res*/) {
  4467. auto values = req.get_param_values("array");
  4468. EXPECT_EQ(3u, values.size());
  4469. EXPECT_EQ("value1", values[0]);
  4470. EXPECT_EQ("value2", values[1]);
  4471. EXPECT_EQ("value3", values[2]);
  4472. auto empty = req.get_param_values("nonexistent");
  4473. EXPECT_TRUE(empty.empty());
  4474. })
  4475. .Post("/validate-no-multiple-headers",
  4476. [&](const Request &req, Response & /*res*/) {
  4477. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4478. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4479. })
  4480. .Post("/content_receiver",
  4481. [&](const Request &req, Response &res,
  4482. const ContentReader &content_reader) {
  4483. if (req.is_multipart_form_data()) {
  4484. std::vector<FormData> items;
  4485. content_reader(
  4486. [&](const FormData &file) {
  4487. items.push_back(file);
  4488. return true;
  4489. },
  4490. [&](const char *data, size_t data_length) {
  4491. items.back().content.append(data, data_length);
  4492. return true;
  4493. });
  4494. EXPECT_EQ(5u, items.size());
  4495. {
  4496. const auto &file = get_file_value(items, "text1");
  4497. EXPECT_TRUE(file.filename.empty());
  4498. EXPECT_EQ("text default", file.content);
  4499. }
  4500. {
  4501. const auto &file = get_file_value(items, "text2");
  4502. EXPECT_TRUE(file.filename.empty());
  4503. EXPECT_EQ("aωb", file.content);
  4504. }
  4505. {
  4506. const auto &file = get_file_value(items, "file1");
  4507. EXPECT_EQ("hello.txt", file.filename);
  4508. EXPECT_EQ("text/plain", file.content_type);
  4509. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4510. }
  4511. {
  4512. const auto &file = get_file_value(items, "file2");
  4513. EXPECT_EQ("world.json", file.filename);
  4514. EXPECT_EQ("application/json", file.content_type);
  4515. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4516. }
  4517. {
  4518. const auto &file = get_file_value(items, "file3");
  4519. EXPECT_TRUE(file.filename.empty());
  4520. EXPECT_EQ("application/octet-stream", file.content_type);
  4521. EXPECT_EQ(0u, file.content.size());
  4522. }
  4523. } else {
  4524. std::string body;
  4525. content_reader([&](const char *data, size_t data_length) {
  4526. EXPECT_EQ(7U, data_length);
  4527. body.append(data, data_length);
  4528. return true;
  4529. });
  4530. EXPECT_EQ(body, "content");
  4531. res.set_content(body, "text/plain");
  4532. }
  4533. })
  4534. .Put("/content_receiver",
  4535. [&](const Request & /*req*/, Response &res,
  4536. const ContentReader &content_reader) {
  4537. std::string body;
  4538. content_reader([&](const char *data, size_t data_length) {
  4539. body.append(data, data_length);
  4540. return true;
  4541. });
  4542. EXPECT_EQ(body, "content");
  4543. res.set_content(body, "text/plain");
  4544. })
  4545. .Patch("/content_receiver",
  4546. [&](const Request & /*req*/, Response &res,
  4547. const ContentReader &content_reader) {
  4548. std::string body;
  4549. content_reader([&](const char *data, size_t data_length) {
  4550. body.append(data, data_length);
  4551. return true;
  4552. });
  4553. EXPECT_EQ(body, "content");
  4554. res.set_content(body, "text/plain");
  4555. })
  4556. .Post("/query-string-and-body",
  4557. [&](const Request &req, Response & /*res*/) {
  4558. ASSERT_TRUE(req.has_param("key"));
  4559. EXPECT_EQ(req.get_param_value("key"), "value");
  4560. EXPECT_EQ(req.body, "content");
  4561. })
  4562. .Get("/last-request",
  4563. [&](const Request &req, Response & /*res*/) {
  4564. EXPECT_EQ("close", req.get_header_value("Connection"));
  4565. })
  4566. .Get(R"(/redirect/(\d+))",
  4567. [&](const Request &req, Response &res) {
  4568. auto num = std::stoi(req.matches[1]) + 1;
  4569. std::string url = "/redirect/" + std::to_string(num);
  4570. res.set_redirect(url);
  4571. })
  4572. .Post("/binary",
  4573. [&](const Request &req, Response &res) {
  4574. EXPECT_EQ(4U, req.body.size());
  4575. EXPECT_EQ("application/octet-stream",
  4576. req.get_header_value("Content-Type"));
  4577. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4578. res.set_content(req.body, "application/octet-stream");
  4579. })
  4580. .Put("/binary",
  4581. [&](const Request &req, Response &res) {
  4582. EXPECT_EQ(4U, req.body.size());
  4583. EXPECT_EQ("application/octet-stream",
  4584. req.get_header_value("Content-Type"));
  4585. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4586. res.set_content(req.body, "application/octet-stream");
  4587. })
  4588. .Patch("/binary",
  4589. [&](const Request &req, Response &res) {
  4590. EXPECT_EQ(4U, req.body.size());
  4591. EXPECT_EQ("application/octet-stream",
  4592. req.get_header_value("Content-Type"));
  4593. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4594. res.set_content(req.body, "application/octet-stream");
  4595. })
  4596. .Delete("/binary",
  4597. [&](const Request &req, Response &res) {
  4598. EXPECT_EQ(4U, req.body.size());
  4599. EXPECT_EQ("application/octet-stream",
  4600. req.get_header_value("Content-Type"));
  4601. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4602. res.set_content(req.body, "application/octet-stream");
  4603. })
  4604. .Get("/issue1772",
  4605. [&](const Request & /*req*/, Response &res) {
  4606. res.status = 401;
  4607. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4608. })
  4609. .Delete("/issue609",
  4610. [](const httplib::Request &, httplib::Response &res,
  4611. const httplib::ContentReader &) {
  4612. res.set_content("ok", "text/plain");
  4613. })
  4614. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4615. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4616. .Get("/compress",
  4617. [&](const Request & /*req*/, Response &res) {
  4618. res.set_content(
  4619. "12345678901234567890123456789012345678901234567890123456789"
  4620. "01234567890123456789012345678901234567890",
  4621. "text/plain");
  4622. })
  4623. .Get("/compress-with-charset",
  4624. [&](const Request & /*req*/, Response &res) {
  4625. res.set_content(
  4626. "12345678901234567890123456789012345678901234567890123456789"
  4627. "01234567890123456789012345678901234567890",
  4628. "application/json; charset=utf-8");
  4629. })
  4630. .Get("/nocompress",
  4631. [&](const Request & /*req*/, Response &res) {
  4632. res.set_content(
  4633. "12345678901234567890123456789012345678901234567890123456789"
  4634. "01234567890123456789012345678901234567890",
  4635. "application/octet-stream");
  4636. })
  4637. .Post("/compress-multipart",
  4638. [&](const Request &req, Response & /*res*/) {
  4639. EXPECT_EQ(2u, req.form.fields.size());
  4640. ASSERT_TRUE(!req.form.has_field("???"));
  4641. {
  4642. const auto &text = req.form.get_field("key1");
  4643. EXPECT_EQ("test", text);
  4644. }
  4645. {
  4646. const auto &text = req.form.get_field("key2");
  4647. EXPECT_EQ("--abcdefg123", text);
  4648. }
  4649. })
  4650. #endif
  4651. ;
  4652. persons_["john"] = "programmer";
  4653. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4654. svr_.wait_until_ready();
  4655. }
  4656. virtual void TearDown() {
  4657. svr_.stop();
  4658. if (!request_threads_.empty()) {
  4659. std::this_thread::sleep_for(std::chrono::seconds(1));
  4660. for (auto &t : request_threads_) {
  4661. t.join();
  4662. }
  4663. }
  4664. t_.join();
  4665. }
  4666. map<string, string> persons_;
  4667. #ifdef CPPHTTPLIB_SSL_ENABLED
  4668. SSLClient cli_;
  4669. SSLServer svr_;
  4670. #else
  4671. Client cli_;
  4672. Server svr_;
  4673. #endif
  4674. thread t_;
  4675. std::vector<thread> request_threads_;
  4676. };
  4677. TEST_F(ServerTest, GetMethod200) {
  4678. auto res = cli_.Get("/hi");
  4679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4680. EXPECT_EQ("HTTP/1.1", res->version);
  4681. EXPECT_EQ(StatusCode::OK_200, res->status);
  4682. EXPECT_EQ("OK", res->reason);
  4683. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4684. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4685. EXPECT_EQ("Hello World!", res->body);
  4686. }
  4687. TEST_F(ServerTest, GetEmptyFile) {
  4688. auto res = cli_.Get("/empty_file");
  4689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4690. EXPECT_EQ(StatusCode::OK_200, res->status);
  4691. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4692. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4693. EXPECT_EQ("", res->body);
  4694. }
  4695. TEST_F(ServerTest, GetFileContent) {
  4696. auto res = cli_.Get("/file_content");
  4697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4698. EXPECT_EQ(StatusCode::OK_200, res->status);
  4699. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4700. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4701. EXPECT_EQ("test.html", res->body);
  4702. }
  4703. TEST_F(ServerTest, GetFileContentWithRange) {
  4704. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4706. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4707. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4708. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4709. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4710. EXPECT_EQ("est", res->body);
  4711. }
  4712. TEST_F(ServerTest, GetFileContentWithContentType) {
  4713. auto res = cli_.Get("/file_content_with_content_type");
  4714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4715. EXPECT_EQ(StatusCode::OK_200, res->status);
  4716. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4717. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4718. EXPECT_EQ("file\n", res->body);
  4719. }
  4720. TEST_F(ServerTest, GetInvalidFileContent) {
  4721. auto res = cli_.Get("/invalid_file_content");
  4722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4723. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4724. }
  4725. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4726. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4728. EXPECT_EQ("HTTP/1.1", res->version);
  4729. EXPECT_EQ(StatusCode::OK_200, res->status);
  4730. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4731. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4732. EXPECT_EQ("Hello World!", res->body);
  4733. }
  4734. TEST_F(ServerTest, GetMethod302) {
  4735. auto res = cli_.Get("/");
  4736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4737. EXPECT_EQ(StatusCode::Found_302, res->status);
  4738. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4739. }
  4740. TEST_F(ServerTest, GetMethod302Redirect) {
  4741. cli_.set_follow_location(true);
  4742. auto res = cli_.Get("/");
  4743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4744. EXPECT_EQ(StatusCode::OK_200, res->status);
  4745. EXPECT_EQ("Hello World!", res->body);
  4746. EXPECT_EQ("/hi", res->location);
  4747. }
  4748. TEST_F(ServerTest, GetMethod404) {
  4749. auto res = cli_.Get("/invalid");
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4752. }
  4753. TEST_F(ServerTest, HeadMethod200) {
  4754. auto res = cli_.Head("/hi");
  4755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4756. EXPECT_EQ(StatusCode::OK_200, res->status);
  4757. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4758. EXPECT_TRUE(res->body.empty());
  4759. }
  4760. TEST_F(ServerTest, HeadMethod200Static) {
  4761. auto res = cli_.Head("/mount/dir/index.html");
  4762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4763. EXPECT_EQ(StatusCode::OK_200, res->status);
  4764. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4765. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4766. EXPECT_TRUE(res->body.empty());
  4767. }
  4768. TEST_F(ServerTest, HeadMethod404) {
  4769. auto res = cli_.Head("/invalid");
  4770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4771. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4772. EXPECT_TRUE(res->body.empty());
  4773. }
  4774. TEST_F(ServerTest, GetMethodPersonJohn) {
  4775. auto res = cli_.Get("/person/john");
  4776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4777. EXPECT_EQ(StatusCode::OK_200, res->status);
  4778. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4779. EXPECT_EQ("programmer", res->body);
  4780. }
  4781. TEST_F(ServerTest, PostMethod1) {
  4782. auto res = cli_.Get("/person/john1");
  4783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4784. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4785. res = cli_.Post("/person", "name=john1&note=coder",
  4786. "application/x-www-form-urlencoded");
  4787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4788. ASSERT_EQ(StatusCode::OK_200, res->status);
  4789. res = cli_.Get("/person/john1");
  4790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4791. ASSERT_EQ(StatusCode::OK_200, res->status);
  4792. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4793. ASSERT_EQ("coder", res->body);
  4794. }
  4795. TEST_F(ServerTest, PostMethod2) {
  4796. auto res = cli_.Get("/person/john2");
  4797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4798. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4799. Params params;
  4800. params.emplace("name", "john2");
  4801. params.emplace("note", "coder");
  4802. res = cli_.Post("/person", params);
  4803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4804. ASSERT_EQ(StatusCode::OK_200, res->status);
  4805. res = cli_.Get("/person/john2");
  4806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4807. ASSERT_EQ(StatusCode::OK_200, res->status);
  4808. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4809. ASSERT_EQ("coder", res->body);
  4810. }
  4811. TEST_F(ServerTest, PutMethod3) {
  4812. auto res = cli_.Get("/person/john3");
  4813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4814. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4815. Params params;
  4816. params.emplace("name", "john3");
  4817. params.emplace("note", "coder");
  4818. res = cli_.Put("/person", params);
  4819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4820. ASSERT_EQ(StatusCode::OK_200, res->status);
  4821. res = cli_.Get("/person/john3");
  4822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4823. ASSERT_EQ(StatusCode::OK_200, res->status);
  4824. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4825. ASSERT_EQ("coder", res->body);
  4826. }
  4827. TEST_F(ServerTest, DeleteMethod1) {
  4828. auto res = cli_.Get("/person/john4");
  4829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4830. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4831. Params params;
  4832. params.emplace("name", "john4");
  4833. params.emplace("note", "coder");
  4834. res = cli_.Post("/person", params);
  4835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4836. ASSERT_EQ(StatusCode::OK_200, res->status);
  4837. res = cli_.Get("/person/john4");
  4838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4839. ASSERT_EQ(StatusCode::OK_200, res->status);
  4840. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4841. ASSERT_EQ("coder", res->body);
  4842. Params delete_params;
  4843. delete_params.emplace("name", "john4");
  4844. res = cli_.Delete("/person", delete_params);
  4845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4846. ASSERT_EQ(StatusCode::OK_200, res->status);
  4847. ASSERT_EQ("DELETED", res->body);
  4848. res = cli_.Get("/person/john4");
  4849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4850. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4851. }
  4852. TEST_F(ServerTest, DeleteMethod2) {
  4853. auto res = cli_.Get("/person/john5");
  4854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4855. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4856. Params params;
  4857. params.emplace("name", "john5");
  4858. params.emplace("note", "developer");
  4859. res = cli_.Post("/person", params);
  4860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4861. ASSERT_EQ(StatusCode::OK_200, res->status);
  4862. res = cli_.Get("/person/john5");
  4863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4864. ASSERT_EQ(StatusCode::OK_200, res->status);
  4865. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4866. ASSERT_EQ("developer", res->body);
  4867. Params delete_params;
  4868. delete_params.emplace("name", "john5");
  4869. Headers headers;
  4870. headers.emplace("Custom-Header", "test-value");
  4871. res = cli_.Delete("/person", headers, delete_params);
  4872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4873. ASSERT_EQ(StatusCode::OK_200, res->status);
  4874. ASSERT_EQ("DELETED", res->body);
  4875. res = cli_.Get("/person/john5");
  4876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4877. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4878. }
  4879. TEST_F(ServerTest, DeleteMethod3) {
  4880. auto res = cli_.Get("/person/john6");
  4881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4882. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4883. Params params;
  4884. params.emplace("name", "john6");
  4885. params.emplace("note", "tester");
  4886. res = cli_.Post("/person", params);
  4887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4888. ASSERT_EQ(StatusCode::OK_200, res->status);
  4889. res = cli_.Get("/person/john6");
  4890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4891. ASSERT_EQ(StatusCode::OK_200, res->status);
  4892. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4893. ASSERT_EQ("tester", res->body);
  4894. Params delete_params;
  4895. delete_params.emplace("name", "john6");
  4896. Headers headers;
  4897. headers.emplace("Custom-Header", "test-value");
  4898. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4900. ASSERT_EQ(StatusCode::OK_200, res->status);
  4901. ASSERT_EQ("DELETED", res->body);
  4902. res = cli_.Get("/person/john6");
  4903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4904. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4905. }
  4906. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4907. Params params;
  4908. params.emplace("json", JSON_DATA);
  4909. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4911. ASSERT_EQ(StatusCode::OK_200, res->status);
  4912. ASSERT_EQ(JSON_DATA, res->body);
  4913. }
  4914. TEST_F(ServerTest, PostEmptyContent) {
  4915. auto res = cli_.Post("/empty", "", "text/plain");
  4916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4917. ASSERT_EQ(StatusCode::OK_200, res->status);
  4918. ASSERT_EQ("empty", res->body);
  4919. }
  4920. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4921. auto res = cli_.Post("/empty-no-content-type");
  4922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4923. ASSERT_EQ(StatusCode::OK_200, res->status);
  4924. ASSERT_EQ("empty-no-content-type", res->body);
  4925. }
  4926. TEST_F(ServerTest, PostPathOnly) {
  4927. auto res = cli_.Post("/path-only");
  4928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4929. ASSERT_EQ(StatusCode::OK_200, res->status);
  4930. ASSERT_EQ("path-only", res->body);
  4931. }
  4932. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4933. auto res = cli_.Post("/path-headers-only",
  4934. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4936. ASSERT_EQ(StatusCode::OK_200, res->status);
  4937. ASSERT_EQ("path-headers-only", res->body);
  4938. }
  4939. TEST_F(ServerTest, PostLarge) {
  4940. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4942. ASSERT_EQ(StatusCode::OK_200, res->status);
  4943. EXPECT_EQ(LARGE_DATA, res->body);
  4944. }
  4945. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4946. auto res = cli_.Put("/empty-no-content-type");
  4947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4948. ASSERT_EQ(StatusCode::OK_200, res->status);
  4949. ASSERT_EQ("empty-no-content-type", res->body);
  4950. }
  4951. TEST_F(ServerTest, GetMethodDir) {
  4952. auto res = cli_.Get("/dir/");
  4953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4954. EXPECT_EQ(StatusCode::OK_200, res->status);
  4955. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4956. auto body = R"(<html>
  4957. <head>
  4958. </head>
  4959. <body>
  4960. <a href="/dir/test.html">Test</a>
  4961. <a href="/hi">hi</a>
  4962. </body>
  4963. </html>
  4964. )";
  4965. EXPECT_EQ(body, res->body);
  4966. }
  4967. TEST_F(ServerTest, GetMethodDirTest) {
  4968. auto res = cli_.Get("/dir/test.html");
  4969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4970. EXPECT_EQ(StatusCode::OK_200, res->status);
  4971. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4972. EXPECT_EQ("test.html", res->body);
  4973. }
  4974. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4975. auto res = cli_.Get("/dir/../dir/test.html");
  4976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4977. EXPECT_EQ(StatusCode::OK_200, res->status);
  4978. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4979. EXPECT_EQ("test.html", res->body);
  4980. }
  4981. TEST_F(ServerTest, GetMethodInvalidPath) {
  4982. auto res = cli_.Get("/dir/../test.html");
  4983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4984. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4985. }
  4986. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4987. auto res = cli_.Get("/../www/dir/test.html");
  4988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4989. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4990. }
  4991. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4992. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4994. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4995. }
  4996. TEST_F(ServerTest, GetMethodDirMountTest) {
  4997. auto res = cli_.Get("/mount/dir/test.html");
  4998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4999. EXPECT_EQ(StatusCode::OK_200, res->status);
  5000. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5001. EXPECT_EQ("test.html", res->body);
  5002. }
  5003. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5004. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5006. EXPECT_EQ(StatusCode::OK_200, res->status);
  5007. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5008. EXPECT_EQ("test.html", res->body);
  5009. }
  5010. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5011. auto res = cli_.Get("/mount/dir/../test.html");
  5012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5013. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5014. }
  5015. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5016. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5018. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5019. }
  5020. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5021. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5023. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5024. }
  5025. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5026. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5028. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5029. }
  5030. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5031. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5033. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5034. }
  5035. TEST_F(ServerTest, PostMethod303) {
  5036. auto res = cli_.Post("/1", "body", "text/plain");
  5037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5038. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5039. EXPECT_EQ("/2", res->get_header_value("Location"));
  5040. }
  5041. TEST_F(ServerTest, PostMethod303Redirect) {
  5042. cli_.set_follow_location(true);
  5043. auto res = cli_.Post("/1", "body", "text/plain");
  5044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5045. EXPECT_EQ(StatusCode::OK_200, res->status);
  5046. EXPECT_EQ("redirected.", res->body);
  5047. EXPECT_EQ("/2", res->location);
  5048. }
  5049. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5050. auto res = cli_.Get("/dir/test.abcde");
  5051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5052. EXPECT_EQ(StatusCode::OK_200, res->status);
  5053. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5054. EXPECT_EQ("abcde", res->body);
  5055. }
  5056. TEST_F(ServerTest, StaticFileRange) {
  5057. auto res =
  5058. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5061. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5062. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5063. EXPECT_EQ(true, res->has_header("Content-Range"));
  5064. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5065. EXPECT_EQ(std::string("cd"), res->body);
  5066. }
  5067. TEST_F(ServerTest, StaticFileRanges) {
  5068. auto res = cli_.Get("/dir/test.abcde",
  5069. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5071. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5072. EXPECT_TRUE(
  5073. res->get_header_value("Content-Type")
  5074. .find(
  5075. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5076. 0);
  5077. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5078. }
  5079. TEST_F(ServerTest, StaticFileRangeHead) {
  5080. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5082. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5083. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5084. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5085. EXPECT_EQ(true, res->has_header("Content-Range"));
  5086. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5087. }
  5088. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5089. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5091. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5092. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5093. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5094. EXPECT_EQ(true, res->has_header("Content-Range"));
  5095. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5096. res->get_header_value("Content-Range"));
  5097. EXPECT_EQ("LAST\n", res->body);
  5098. }
  5099. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5100. auto res =
  5101. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5103. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5105. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5106. EXPECT_EQ(true, res->has_header("Content-Range"));
  5107. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5108. }
  5109. TEST_F(ServerTest, StaticFileBigFile) {
  5110. auto res = cli_.Get("/dir/1MB.txt");
  5111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5112. EXPECT_EQ(StatusCode::OK_200, res->status);
  5113. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5114. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5115. }
  5116. TEST_F(ServerTest, InvalidBaseDirMount) {
  5117. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5118. }
  5119. TEST_F(ServerTest, Binary) {
  5120. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5121. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5122. "application/octet-stream");
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. ASSERT_EQ(StatusCode::OK_200, res->status);
  5125. ASSERT_EQ(4U, res->body.size());
  5126. res = cli_.Put("/binary", binary.data(), binary.size(),
  5127. "application/octet-stream");
  5128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5129. ASSERT_EQ(StatusCode::OK_200, res->status);
  5130. ASSERT_EQ(4U, res->body.size());
  5131. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5132. "application/octet-stream");
  5133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5134. ASSERT_EQ(StatusCode::OK_200, res->status);
  5135. ASSERT_EQ(4U, res->body.size());
  5136. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5137. "application/octet-stream");
  5138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5139. ASSERT_EQ(StatusCode::OK_200, res->status);
  5140. ASSERT_EQ(4U, res->body.size());
  5141. }
  5142. TEST_F(ServerTest, BinaryString) {
  5143. auto binary = std::string("\x00\x01\x02\x03", 4);
  5144. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5146. ASSERT_EQ(StatusCode::OK_200, res->status);
  5147. ASSERT_EQ(4U, res->body.size());
  5148. res = cli_.Put("/binary", binary, "application/octet-stream");
  5149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5150. ASSERT_EQ(StatusCode::OK_200, res->status);
  5151. ASSERT_EQ(4U, res->body.size());
  5152. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5154. ASSERT_EQ(StatusCode::OK_200, res->status);
  5155. ASSERT_EQ(4U, res->body.size());
  5156. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5158. ASSERT_EQ(StatusCode::OK_200, res->status);
  5159. ASSERT_EQ(4U, res->body.size());
  5160. }
  5161. TEST_F(ServerTest, EmptyRequest) {
  5162. auto res = cli_.Get("");
  5163. ASSERT_TRUE(!res);
  5164. EXPECT_EQ(Error::Connection, res.error());
  5165. }
  5166. TEST_F(ServerTest, LongRequest) {
  5167. std::string request;
  5168. for (size_t i = 0; i < 545; i++) {
  5169. request += "/TooLongRequest";
  5170. }
  5171. request += "OK";
  5172. auto res = cli_.Get(request.c_str());
  5173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5174. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5175. }
  5176. TEST_F(ServerTest, TooLongRequest) {
  5177. std::string request;
  5178. for (size_t i = 0; i < 546; i++) {
  5179. request += "/TooLongRequest";
  5180. }
  5181. request += "_NG";
  5182. auto start = std::chrono::high_resolution_clock::now();
  5183. cli_.set_keep_alive(true);
  5184. auto res = cli_.Get(request.c_str());
  5185. auto end = std::chrono::high_resolution_clock::now();
  5186. auto elapsed =
  5187. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5188. .count();
  5189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5190. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5191. EXPECT_LE(elapsed, 1000);
  5192. EXPECT_EQ("close", res->get_header_value("Connection"));
  5193. EXPECT_FALSE(cli_.is_socket_open());
  5194. }
  5195. TEST_F(ServerTest, AlmostTooLongRequest) {
  5196. // test for #2046 - URI length check shouldn't include other content on req
  5197. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5198. // leading /, space, HTTP/1.1)
  5199. std::string request =
  5200. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5201. auto res = cli_.Get(request.c_str());
  5202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5203. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5204. }
  5205. TEST_F(ServerTest, LongHeader) {
  5206. Request req;
  5207. req.method = "GET";
  5208. req.path = "/hi";
  5209. std::string host_and_port;
  5210. host_and_port += HOST;
  5211. host_and_port += ":";
  5212. host_and_port += std::to_string(PORT);
  5213. req.headers.emplace("Host", host_and_port.c_str());
  5214. req.headers.emplace("Accept", "*/*");
  5215. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5216. req.headers.emplace(
  5217. "Header-Name",
  5218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5219. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5220. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5221. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5222. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5223. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5224. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5225. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5226. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5227. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5228. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5229. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5230. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5231. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5232. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5233. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5234. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5235. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5236. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5237. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5238. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5239. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5240. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5241. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5242. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5243. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5244. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5245. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5246. "@@@@@@@@@@@@@@@@");
  5247. auto res = std::make_shared<Response>();
  5248. auto error = Error::Success;
  5249. auto ret = cli_.send(req, *res, error);
  5250. ASSERT_TRUE(ret);
  5251. EXPECT_EQ(StatusCode::OK_200, res->status);
  5252. }
  5253. TEST_F(ServerTest, LongQueryValue) {
  5254. auto start = std::chrono::high_resolution_clock::now();
  5255. cli_.set_keep_alive(true);
  5256. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5257. auto end = std::chrono::high_resolution_clock::now();
  5258. auto elapsed =
  5259. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5260. .count();
  5261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5262. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5263. EXPECT_LE(elapsed, 1000);
  5264. EXPECT_EQ("close", res->get_header_value("Connection"));
  5265. EXPECT_FALSE(cli_.is_socket_open());
  5266. }
  5267. TEST_F(ServerTest, TooLongQueryValue) {
  5268. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5269. ASSERT_FALSE(res);
  5270. EXPECT_EQ(Error::Read, res.error());
  5271. }
  5272. TEST_F(ServerTest, TooLongHeader) {
  5273. Request req;
  5274. req.method = "GET";
  5275. req.path = "/hi";
  5276. std::string host_and_port;
  5277. host_and_port += HOST;
  5278. host_and_port += ":";
  5279. host_and_port += std::to_string(PORT);
  5280. req.headers.emplace("Host", host_and_port.c_str());
  5281. req.headers.emplace("Accept", "*/*");
  5282. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5283. req.headers.emplace(
  5284. "Header-Name",
  5285. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5286. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5287. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5288. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5289. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5290. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5291. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5292. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5293. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5294. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5295. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5296. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5297. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5298. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5299. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5300. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5301. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5302. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5303. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5304. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5305. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5306. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5307. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5308. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5309. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5310. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5311. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5312. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5313. "@@@@@@@@@@@@@@@@@");
  5314. auto res = std::make_shared<Response>();
  5315. auto error = Error::Success;
  5316. auto ret = cli_.send(req, *res, error);
  5317. ASSERT_TRUE(ret);
  5318. EXPECT_EQ(StatusCode::OK_200, res->status);
  5319. }
  5320. TEST_F(ServerTest, HeaderCountAtLimit) {
  5321. // Test with headers just under the 100 limit
  5322. httplib::Headers headers;
  5323. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5324. // This should keep us just under the 100 header limit
  5325. for (int i = 0; i < 95; i++) {
  5326. std::string name = "X-Test-Header-" + std::to_string(i);
  5327. std::string value = "value" + std::to_string(i);
  5328. headers.emplace(name, value);
  5329. }
  5330. // This should work fine as we're under the limit
  5331. auto res = cli_.Get("/hi", headers);
  5332. EXPECT_TRUE(res);
  5333. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5334. }
  5335. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5336. // Test with many headers to exceed the 100 limit
  5337. httplib::Headers headers;
  5338. // Add 150 headers to definitely exceed the 100 limit
  5339. for (int i = 0; i < 150; i++) {
  5340. std::string name = "X-Test-Header-" + std::to_string(i);
  5341. std::string value = "value" + std::to_string(i);
  5342. headers.emplace(name, value);
  5343. }
  5344. // This should fail due to exceeding header count limit
  5345. cli_.set_keep_alive(true);
  5346. auto res = cli_.Get("/hi", headers);
  5347. // The server should respond with 400 Bad Request
  5348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5349. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5350. EXPECT_EQ("close", res->get_header_value("Connection"));
  5351. EXPECT_FALSE(cli_.is_socket_open());
  5352. }
  5353. TEST_F(ServerTest, PercentEncoding) {
  5354. auto res = cli_.Get("/e%6edwith%");
  5355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5356. EXPECT_EQ(StatusCode::OK_200, res->status);
  5357. }
  5358. TEST_F(ServerTest, PercentEncodingUnicode) {
  5359. auto res = cli_.Get("/e%u006edwith%");
  5360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5361. EXPECT_EQ(StatusCode::OK_200, res->status);
  5362. }
  5363. TEST_F(ServerTest, InvalidPercentEncoding) {
  5364. auto res = cli_.Get("/%endwith%");
  5365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5366. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5367. }
  5368. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5369. auto res = cli_.Get("/%uendwith%");
  5370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5371. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5372. }
  5373. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5374. auto res = cli_.Get("/hello?aaa=bbb%");
  5375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5376. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5377. }
  5378. TEST_F(ServerTest, PlusSignEncoding) {
  5379. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5381. EXPECT_EQ(StatusCode::OK_200, res->status);
  5382. EXPECT_EQ("a +b", res->body);
  5383. }
  5384. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5385. // This test simulates a potential DoS attack using many headers
  5386. // to verify our security fix prevents memory exhaustion
  5387. httplib::Headers attack_headers;
  5388. // Attempt to add many headers like an attacker would (200 headers to far
  5389. // exceed limit)
  5390. for (int i = 0; i < 200; i++) {
  5391. std::string name = "X-Attack-Header-" + std::to_string(i);
  5392. std::string value = "attack_payload_" + std::to_string(i);
  5393. attack_headers.emplace(name, value);
  5394. }
  5395. // Try to POST with excessive headers
  5396. cli_.set_keep_alive(true);
  5397. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5398. // Should either fail or return 400 Bad Request due to security limit
  5399. if (res) {
  5400. // If we get a response, it should be 400 Bad Request
  5401. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5402. EXPECT_EQ("close", res->get_header_value("Connection"));
  5403. }
  5404. EXPECT_FALSE(cli_.is_socket_open());
  5405. }
  5406. TEST_F(ServerTest, MultipartFormData) {
  5407. UploadFormDataItems items = {
  5408. {"text1", "text default", "", ""},
  5409. {"text2", "aωb", "", ""},
  5410. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5411. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5412. {"file3", "", "", "application/octet-stream"},
  5413. {"file4", "", "", " application/json tmp-string "}};
  5414. auto res = cli_.Post("/multipart", items);
  5415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5416. EXPECT_EQ(StatusCode::OK_200, res->status);
  5417. }
  5418. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5419. UploadFormDataItems items = {
  5420. {"text", "default text", "", ""},
  5421. {"multi_text1", "aaaaa", "", ""},
  5422. {"multi_text1", "bbbbb", "", ""},
  5423. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5424. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5425. "application/json"},
  5426. };
  5427. auto res = cli_.Post("/multipart/multi_file_values", items);
  5428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5429. EXPECT_EQ(StatusCode::OK_200, res->status);
  5430. }
  5431. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5432. auto res = cli_.Get("/hi");
  5433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5434. EXPECT_EQ(StatusCode::OK_200, res->status);
  5435. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5436. EXPECT_EQ("Hello World!", res->body);
  5437. }
  5438. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5439. Request req;
  5440. req.method = "POST";
  5441. req.path = "/chunked";
  5442. std::string host_and_port;
  5443. host_and_port += HOST;
  5444. host_and_port += ":";
  5445. host_and_port += std::to_string(PORT);
  5446. req.headers.emplace("Host", host_and_port.c_str());
  5447. req.headers.emplace("Accept", "*/*");
  5448. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5449. req.headers.emplace("Content-Type", "text/plain");
  5450. req.headers.emplace("Content-Length", "0");
  5451. req.headers.emplace(
  5452. "Transfer-Encoding",
  5453. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5454. // Client does not chunk, so make a chunked body manually.
  5455. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5456. auto res = std::make_shared<Response>();
  5457. auto error = Error::Success;
  5458. auto ret = cli_.send(req, *res, error);
  5459. ASSERT_TRUE(ret);
  5460. EXPECT_EQ(StatusCode::OK_200, res->status);
  5461. }
  5462. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5463. // rather than treat them as valid lengths.
  5464. template <typename ClientT>
  5465. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5466. Request req;
  5467. req.method = "POST";
  5468. req.path = "/chunked";
  5469. std::string host_and_port;
  5470. host_and_port += HOST;
  5471. host_and_port += ":";
  5472. host_and_port += std::to_string(PORT);
  5473. req.headers.emplace("Host", host_and_port.c_str());
  5474. req.headers.emplace("Content-Length", "0");
  5475. req.headers.emplace("Transfer-Encoding", "chunked");
  5476. req.body = body;
  5477. auto res = std::make_shared<Response>();
  5478. auto error = Error::Success;
  5479. ASSERT_TRUE(cli.send(req, *res, error));
  5480. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5481. }
  5482. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5483. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5484. }
  5485. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5486. expect_chunked_body_rejected(
  5487. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5488. }
  5489. TEST_F(ServerTest, GetStreamed2) {
  5490. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5492. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5493. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5494. EXPECT_EQ(true, res->has_header("Content-Range"));
  5495. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5496. EXPECT_EQ(std::string("ab"), res->body);
  5497. }
  5498. TEST_F(ServerTest, GetStreamed) {
  5499. auto res = cli_.Get("/streamed");
  5500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5501. EXPECT_EQ(StatusCode::OK_200, res->status);
  5502. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5503. EXPECT_EQ(std::string("aaabbb"), res->body);
  5504. }
  5505. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5506. auto res = cli_.Get("/streamed-without-length",
  5507. Headers{make_range_header({{0, -1}})});
  5508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5509. EXPECT_EQ(StatusCode::OK_200, res->status);
  5510. EXPECT_EQ(false, res->has_header("Content-Length"));
  5511. EXPECT_EQ(false, res->has_header("Content-Range"));
  5512. EXPECT_EQ(std::string("abcdefg"), res->body);
  5513. }
  5514. TEST_F(ServerTest, GetStreamedWithRange1) {
  5515. auto res =
  5516. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5518. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5519. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5520. EXPECT_EQ(true, res->has_header("Content-Range"));
  5521. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5522. EXPECT_EQ(std::string("def"), res->body);
  5523. }
  5524. TEST_F(ServerTest, GetStreamedWithRange2) {
  5525. auto res =
  5526. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5528. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5529. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5530. EXPECT_EQ(true, res->has_header("Content-Range"));
  5531. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5532. EXPECT_EQ(std::string("bcdefg"), res->body);
  5533. }
  5534. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5535. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5537. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5538. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5539. EXPECT_EQ(true, res->has_header("Content-Range"));
  5540. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5541. EXPECT_EQ(std::string("efg"), res->body);
  5542. }
  5543. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5544. auto res =
  5545. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5547. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5548. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5549. EXPECT_EQ(false, res->has_header("Content-Range"));
  5550. EXPECT_EQ(0U, res->body.size());
  5551. }
  5552. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5553. // Only a 206 is served as a partial representation. Under any other status
  5554. // `apply_ranges()` reported the full content length, so the body must match
  5555. // that header, and the content provider must never be asked for an offset
  5556. // outside the representation.
  5557. auto check = [&](int status, const char *range) {
  5558. auto path =
  5559. std::string("/streamed-with-range?status=") + std::to_string(status);
  5560. auto ctx = path + " Range: " + range;
  5561. auto res = cli_.Get(path, Headers{{"Range", range}});
  5562. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5563. EXPECT_EQ(status, res->status) << ctx;
  5564. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5565. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5566. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5567. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5568. };
  5569. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5570. check(403, "bytes=3-5");
  5571. // The offset is far past the representation.
  5572. check(403, "bytes=100000-100200");
  5573. // `first_pos` is still -1 here, and the bounds asserts in
  5574. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5575. check(403, "bytes=-3");
  5576. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5577. // multipart branch would have written one that is empty.
  5578. check(403, "bytes=1-2, 4-5");
  5579. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5580. // covers the whole representation.
  5581. check(200, "bytes=3-5");
  5582. check(200, "bytes=1-2, 4-5");
  5583. }
  5584. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5585. auto res =
  5586. cli_.Get("/streamed-with-range",
  5587. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5588. "92233720368547758079223372036854775807"}});
  5589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5590. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5591. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5592. EXPECT_EQ(false, res->has_header("Content-Range"));
  5593. EXPECT_EQ(0U, res->body.size());
  5594. }
  5595. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5596. auto res = cli_.Get(
  5597. "/with-range",
  5598. Headers{{"Range",
  5599. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5600. {"Accept-Encoding", ""}});
  5601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5602. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5603. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5604. EXPECT_EQ(true, res->has_header("Content-Range"));
  5605. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5606. EXPECT_EQ(std::string("abcdefg"), res->body);
  5607. }
  5608. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5609. auto res = cli_.Get("/with-range", Headers{
  5610. {"Range", "bytes=0-"},
  5611. {"Accept-Encoding", ""},
  5612. });
  5613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5614. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5615. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5616. EXPECT_EQ(true, res->has_header("Content-Range"));
  5617. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5618. EXPECT_EQ(std::string("abcdefg"), res->body);
  5619. }
  5620. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5621. auto res = cli_.Get("/streamed-with-range",
  5622. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5624. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5625. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5626. EXPECT_EQ(false, res->has_header("Content-Range"));
  5627. EXPECT_EQ(267U, res->body.size());
  5628. // Check that both range contents are present
  5629. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5630. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5631. // Check that Content-Range headers are present for both ranges
  5632. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5633. std::string::npos);
  5634. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5635. std::string::npos);
  5636. }
  5637. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5638. Ranges ranges;
  5639. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5640. ranges.emplace_back(0, -1);
  5641. }
  5642. auto res = cli_.Get("/streamed-with-range?error",
  5643. Headers{{make_range_header(ranges)}});
  5644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5645. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5646. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5647. EXPECT_EQ(false, res->has_header("Content-Range"));
  5648. EXPECT_EQ(0U, res->body.size());
  5649. }
  5650. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5651. auto res = cli_.Get("/streamed-with-range",
  5652. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5654. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5655. EXPECT_EQ(5U, res->body.size());
  5656. // Check that overlapping ranges are coalesced into a single range
  5657. EXPECT_EQ("bcdef", res->body);
  5658. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5659. // Should be single range, not multipart
  5660. EXPECT_TRUE(res->has_header("Content-Range"));
  5661. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5662. }
  5663. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5664. auto res = cli_.Get("/streamed-with-range",
  5665. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5667. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5668. EXPECT_EQ(268U, res->body.size());
  5669. // Check that both range contents are present
  5670. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5671. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5672. // Check that Content-Range headers are present for both ranges
  5673. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5674. std::string::npos);
  5675. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5676. std::string::npos);
  5677. }
  5678. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5679. auto res = cli_.Get("/streamed-with-range",
  5680. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5682. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5683. EXPECT_EQ(269U, res->body.size());
  5684. // Check that both duplicate range contents are present
  5685. size_t first_abc = res->body.find("abc\r\n");
  5686. EXPECT_TRUE(first_abc != std::string::npos);
  5687. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5688. EXPECT_TRUE(second_abc != std::string::npos);
  5689. // Check that Content-Range headers are present for both ranges
  5690. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5691. EXPECT_TRUE(first_range != std::string::npos);
  5692. size_t second_range =
  5693. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5694. EXPECT_TRUE(second_range != std::string::npos);
  5695. }
  5696. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5697. auto res =
  5698. cli_.Get("/streamed-with-range?error",
  5699. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5701. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5702. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5703. EXPECT_EQ(false, res->has_header("Content-Range"));
  5704. EXPECT_EQ(0U, res->body.size());
  5705. }
  5706. TEST_F(ServerTest, GetStreamedEndless) {
  5707. uint64_t offset = 0;
  5708. auto res = cli_.Get("/streamed-cancel",
  5709. [&](const char * /*data*/, uint64_t data_length) {
  5710. if (offset < 100) {
  5711. offset += data_length;
  5712. return true;
  5713. }
  5714. return false;
  5715. });
  5716. ASSERT_TRUE(!res);
  5717. EXPECT_EQ(Error::Canceled, res.error());
  5718. }
  5719. TEST_F(ServerTest, ClientStop) {
  5720. std::atomic_size_t count{4};
  5721. std::vector<std::thread> threads;
  5722. for (auto i = count.load(); i != 0; --i) {
  5723. threads.emplace_back([&]() {
  5724. auto res = cli_.Get("/streamed-cancel",
  5725. [&](const char *, uint64_t) { return true; });
  5726. --count;
  5727. ASSERT_TRUE(!res);
  5728. EXPECT_TRUE(res.error() == Error::Canceled ||
  5729. res.error() == Error::Read || res.error() == Error::Write);
  5730. });
  5731. }
  5732. std::this_thread::sleep_for(std::chrono::seconds(2));
  5733. while (count != 0) {
  5734. cli_.stop();
  5735. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5736. }
  5737. for (auto &t : threads) {
  5738. t.join();
  5739. }
  5740. }
  5741. TEST_F(ServerTest, GetWithRange1) {
  5742. auto res = cli_.Get("/with-range", Headers{
  5743. make_range_header({{3, 5}}),
  5744. {"Accept-Encoding", ""},
  5745. });
  5746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5747. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5748. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5749. EXPECT_EQ(true, res->has_header("Content-Range"));
  5750. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5751. EXPECT_EQ(std::string("def"), res->body);
  5752. }
  5753. TEST_F(ServerTest, GetWithRange2) {
  5754. auto res = cli_.Get("/with-range", Headers{
  5755. make_range_header({{1, -1}}),
  5756. {"Accept-Encoding", ""},
  5757. });
  5758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5759. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5760. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5761. EXPECT_EQ(true, res->has_header("Content-Range"));
  5762. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5763. EXPECT_EQ(std::string("bcdefg"), res->body);
  5764. }
  5765. TEST_F(ServerTest, GetWithRange3) {
  5766. auto res = cli_.Get("/with-range", Headers{
  5767. make_range_header({{0, 0}}),
  5768. {"Accept-Encoding", ""},
  5769. });
  5770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5771. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5772. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5773. EXPECT_EQ(true, res->has_header("Content-Range"));
  5774. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5775. EXPECT_EQ(std::string("a"), res->body);
  5776. }
  5777. TEST_F(ServerTest, GetWithRange4) {
  5778. auto res = cli_.Get("/with-range", Headers{
  5779. make_range_header({{-1, 2}}),
  5780. {"Accept-Encoding", ""},
  5781. });
  5782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5783. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5784. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5785. EXPECT_EQ(true, res->has_header("Content-Range"));
  5786. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5787. EXPECT_EQ(std::string("fg"), res->body);
  5788. }
  5789. TEST_F(ServerTest, GetWithRange5) {
  5790. auto res = cli_.Get("/with-range", Headers{
  5791. make_range_header({{0, 5}}),
  5792. {"Accept-Encoding", ""},
  5793. });
  5794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5795. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5796. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5797. EXPECT_EQ(true, res->has_header("Content-Range"));
  5798. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5799. EXPECT_EQ(std::string("abcdef"), res->body);
  5800. }
  5801. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5802. auto res =
  5803. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5805. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5806. }
  5807. TEST_F(ServerTest, GetWithRangeMultipart) {
  5808. auto res =
  5809. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5812. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5813. EXPECT_EQ(false, res->has_header("Content-Range"));
  5814. EXPECT_EQ(267U, res->body.size());
  5815. }
  5816. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5817. auto res = cli_.Get("/with-range",
  5818. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5820. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5821. }
  5822. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5823. auto res = cli_.Get("/with-range-customized-response",
  5824. Headers{{make_range_header({{1, 2}})}});
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5827. EXPECT_EQ(true, res->has_header("Content-Length"));
  5828. EXPECT_EQ(false, res->has_header("Content-Range"));
  5829. EXPECT_EQ(JSON_DATA, res->body);
  5830. }
  5831. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5832. auto res = cli_.Get("/with-range-customized-response",
  5833. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5835. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5836. EXPECT_EQ(true, res->has_header("Content-Length"));
  5837. EXPECT_EQ(false, res->has_header("Content-Range"));
  5838. EXPECT_EQ(JSON_DATA, res->body);
  5839. }
  5840. TEST_F(ServerTest, Issue1772) {
  5841. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5843. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5844. }
  5845. TEST_F(ServerTest, Issue609) {
  5846. auto res = cli_.Delete("/issue609");
  5847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5848. EXPECT_EQ(StatusCode::OK_200, res->status);
  5849. EXPECT_EQ(std::string("ok"), res->body);
  5850. }
  5851. TEST_F(ServerTest, GetStreamedChunked) {
  5852. auto res = cli_.Get("/streamed-chunked");
  5853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5854. EXPECT_EQ(StatusCode::OK_200, res->status);
  5855. EXPECT_EQ(std::string("123456789"), res->body);
  5856. }
  5857. TEST_F(ServerTest, GetStreamedChunked2) {
  5858. auto res = cli_.Get("/streamed-chunked2");
  5859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5860. EXPECT_EQ(StatusCode::OK_200, res->status);
  5861. EXPECT_EQ(std::string("123456789"), res->body);
  5862. }
  5863. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5864. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5866. EXPECT_EQ(StatusCode::OK_200, res->status);
  5867. EXPECT_EQ(std::string("123456789"), res->body);
  5868. EXPECT_TRUE(res->has_header("Trailer"));
  5869. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5870. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5871. // Trailers are now stored separately from headers (security fix)
  5872. EXPECT_EQ(2U, res->trailers.size());
  5873. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5874. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5875. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5876. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5877. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5878. // Verify trailers are NOT in headers (security verification)
  5879. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5880. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5881. }
  5882. TEST_F(ServerTest, LargeChunkedPost) {
  5883. Request req;
  5884. req.method = "POST";
  5885. req.path = "/large-chunked";
  5886. std::string host_and_port;
  5887. host_and_port += HOST;
  5888. host_and_port += ":";
  5889. host_and_port += std::to_string(PORT);
  5890. req.headers.emplace("Host", host_and_port.c_str());
  5891. req.headers.emplace("Accept", "*/*");
  5892. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5893. req.headers.emplace("Content-Type", "text/plain");
  5894. req.headers.emplace("Content-Length", "0");
  5895. req.headers.emplace("Transfer-Encoding", "chunked");
  5896. std::string long_string(30 * 1024u, 'a');
  5897. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5898. // Attempt to make a large enough post to exceed OS buffers, to test that
  5899. // the server handles short reads if the full chunk data isn't available.
  5900. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5901. auto res = std::make_shared<Response>();
  5902. auto error = Error::Success;
  5903. auto ret = cli_.send(req, *res, error);
  5904. ASSERT_TRUE(ret);
  5905. EXPECT_EQ(StatusCode::OK_200, res->status);
  5906. }
  5907. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5908. auto res = cli_.Get("/remote_addr");
  5909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5910. EXPECT_EQ(StatusCode::OK_200, res->status);
  5911. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5912. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5913. }
  5914. TEST_F(ServerTest, GetMethodLocalAddr) {
  5915. auto res = cli_.Get("/local_addr");
  5916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5917. EXPECT_EQ(StatusCode::OK_200, res->status);
  5918. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5919. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5920. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5921. }
  5922. TEST_F(ServerTest, HTTPResponseSplitting) {
  5923. auto res = cli_.Get("/http_response_splitting");
  5924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5925. EXPECT_EQ(StatusCode::OK_200, res->status);
  5926. }
  5927. TEST_F(ServerTest, SlowRequest) {
  5928. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5929. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5930. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5931. }
  5932. #if 0
  5933. TEST_F(ServerTest, SlowPost) {
  5934. char buffer[64 * 1024];
  5935. memset(buffer, 0x42, sizeof(buffer));
  5936. auto res = cli_.Post(
  5937. "/slowpost", 64 * 1024 * 1024,
  5938. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5939. auto ret = sink.write(buffer, sizeof(buffer));
  5940. EXPECT_TRUE(ret);
  5941. return true;
  5942. },
  5943. "text/plain");
  5944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5945. EXPECT_EQ(StatusCode::OK_200, res->status);
  5946. }
  5947. TEST_F(ServerTest, SlowPostFail) {
  5948. char buffer[64 * 1024];
  5949. memset(buffer, 0x42, sizeof(buffer));
  5950. cli_.set_write_timeout(std::chrono::seconds(0));
  5951. auto res = cli_.Post(
  5952. "/slowpost", 64 * 1024 * 1024,
  5953. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5954. sink.write(buffer, sizeof(buffer));
  5955. return true;
  5956. },
  5957. "text/plain");
  5958. ASSERT_TRUE(!res);
  5959. EXPECT_EQ(Error::Write, res.error());
  5960. }
  5961. #endif
  5962. TEST_F(ServerTest, Put) {
  5963. auto res = cli_.Put("/put", "PUT", "text/plain");
  5964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5965. EXPECT_EQ(StatusCode::OK_200, res->status);
  5966. EXPECT_EQ("PUT", res->body);
  5967. }
  5968. TEST_F(ServerTest, PutWithContentProvider) {
  5969. auto res = cli_.Put(
  5970. "/put", 3,
  5971. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5972. sink.os << "PUT";
  5973. return true;
  5974. },
  5975. "text/plain");
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::OK_200, res->status);
  5978. EXPECT_EQ("PUT", res->body);
  5979. }
  5980. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5981. auto res = cli_.Post(
  5982. "/post", 42,
  5983. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5984. return false;
  5985. },
  5986. "text/plain");
  5987. ASSERT_TRUE(!res);
  5988. EXPECT_EQ(Error::Canceled, res.error());
  5989. }
  5990. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5991. auto res = cli_.Put(
  5992. "/put",
  5993. [](size_t /*offset*/, DataSink &sink) {
  5994. sink.os << "PUT";
  5995. sink.done();
  5996. return true;
  5997. },
  5998. "text/plain");
  5999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. EXPECT_EQ("PUT", res->body);
  6002. }
  6003. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6004. auto res = cli_.Post(
  6005. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6006. "text/plain");
  6007. ASSERT_TRUE(!res);
  6008. EXPECT_EQ(Error::Canceled, res.error());
  6009. }
  6010. TEST_F(ServerTest, PostLoopBack) {
  6011. std::string body;
  6012. auto res = cli_.Post(
  6013. "/post-loopback", 9,
  6014. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6015. EXPECT_EQ(9u, length);
  6016. sink.write("123", 3);
  6017. sink.write("456", 3);
  6018. sink.write("789", 3);
  6019. return true;
  6020. },
  6021. "text/plain",
  6022. [&body](const char *data, size_t data_length) {
  6023. body.append(data, data_length);
  6024. return true;
  6025. });
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::OK_200, res->status);
  6028. EXPECT_EQ("123456789", body);
  6029. }
  6030. TEST_F(ServerTest, PutLoopBack) {
  6031. std::string body;
  6032. auto res = cli_.Put(
  6033. "/put-loopback", 9,
  6034. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6035. EXPECT_EQ(9u, length);
  6036. sink.write("123", 3);
  6037. sink.write("456", 3);
  6038. sink.write("789", 3);
  6039. return true;
  6040. },
  6041. "text/plain",
  6042. [&body](const char *data, size_t data_length) {
  6043. body.append(data, data_length);
  6044. return true;
  6045. });
  6046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6047. EXPECT_EQ(StatusCode::OK_200, res->status);
  6048. EXPECT_EQ("123456789", body);
  6049. }
  6050. TEST_F(ServerTest, PatchLoopBack) {
  6051. std::string body;
  6052. auto res = cli_.Patch(
  6053. "/patch-loopback", 9,
  6054. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6055. EXPECT_EQ(9u, length);
  6056. sink.write("123", 3);
  6057. sink.write("456", 3);
  6058. sink.write("789", 3);
  6059. return true;
  6060. },
  6061. "text/plain",
  6062. [&body](const char *data, size_t data_length) {
  6063. body.append(data, data_length);
  6064. return true;
  6065. });
  6066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6067. EXPECT_EQ(StatusCode::OK_200, res->status);
  6068. EXPECT_EQ("123456789", body);
  6069. }
  6070. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6071. std::string body;
  6072. auto res = cli_.Post(
  6073. "/post-loopback",
  6074. [](size_t /*offset*/, DataSink &sink) {
  6075. sink.write("123", 3);
  6076. sink.write("456", 3);
  6077. sink.write("789", 3);
  6078. sink.done();
  6079. return true;
  6080. },
  6081. "text/plain",
  6082. [&body](const char *data, size_t data_length) {
  6083. body.append(data, data_length);
  6084. return true;
  6085. });
  6086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6087. EXPECT_EQ(StatusCode::OK_200, res->status);
  6088. EXPECT_EQ("123456789", body);
  6089. }
  6090. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6091. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6092. cli_.set_compress(true);
  6093. auto res = cli_.Put(
  6094. "/put", 3,
  6095. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6096. sink.os << "PUT";
  6097. return true;
  6098. },
  6099. "text/plain");
  6100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6101. EXPECT_EQ(StatusCode::OK_200, res->status);
  6102. EXPECT_EQ("PUT", res->body);
  6103. }
  6104. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6105. cli_.set_compress(true);
  6106. auto res = cli_.Post(
  6107. "/post", 42,
  6108. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6109. return false;
  6110. },
  6111. "text/plain");
  6112. ASSERT_TRUE(!res);
  6113. EXPECT_EQ(Error::Canceled, res.error());
  6114. }
  6115. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6116. cli_.set_compress(true);
  6117. auto res = cli_.Put(
  6118. "/put",
  6119. [](size_t /*offset*/, DataSink &sink) {
  6120. sink.os << "PUT";
  6121. sink.done();
  6122. return true;
  6123. },
  6124. "text/plain");
  6125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6126. EXPECT_EQ(StatusCode::OK_200, res->status);
  6127. EXPECT_EQ("PUT", res->body);
  6128. }
  6129. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6130. cli_.set_compress(true);
  6131. auto res = cli_.Post(
  6132. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6133. "text/plain");
  6134. ASSERT_TRUE(!res);
  6135. EXPECT_EQ(Error::Canceled, res.error());
  6136. }
  6137. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6138. cli_.set_compress(true);
  6139. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. EXPECT_EQ(StatusCode::OK_200, res->status);
  6142. EXPECT_EQ(LARGE_DATA, res->body);
  6143. }
  6144. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6145. #ifdef CPPHTTPLIB_SSL_ENABLED
  6146. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6147. Client cli(s.c_str());
  6148. cli.enable_server_certificate_verification(false);
  6149. #else
  6150. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6151. Client cli(s.c_str());
  6152. #endif
  6153. cli.set_compress(true);
  6154. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. EXPECT_EQ(StatusCode::OK_200, res->status);
  6157. EXPECT_EQ(LARGE_DATA, res->body);
  6158. // The compressed size should be less than a 10th of the original. May vary
  6159. // depending on the zlib library.
  6160. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6161. static_cast<uint64_t>(10 * 1024 * 1024));
  6162. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6163. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6164. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6165. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6166. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6167. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6168. #endif
  6169. }
  6170. TEST_F(ServerTest, PutContentWithDeflate) {
  6171. cli_.set_compress(false);
  6172. Headers headers;
  6173. headers.emplace("Content-Encoding", "deflate");
  6174. // PUT in deflate format:
  6175. auto res = cli_.Put("/put", headers,
  6176. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6178. EXPECT_EQ(StatusCode::OK_200, res->status);
  6179. EXPECT_EQ("PUT", res->body);
  6180. }
  6181. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6182. Headers headers;
  6183. headers.emplace("Accept-Encoding", "gzip, deflate");
  6184. auto res = cli_.Get("/streamed-chunked", headers);
  6185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6186. EXPECT_EQ(StatusCode::OK_200, res->status);
  6187. EXPECT_EQ(std::string("123456789"), res->body);
  6188. }
  6189. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6190. Headers headers;
  6191. headers.emplace("Accept-Encoding", "gzip, deflate");
  6192. auto res = cli_.Get("/streamed-chunked2", headers);
  6193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6194. EXPECT_EQ(StatusCode::OK_200, res->status);
  6195. EXPECT_EQ(std::string("123456789"), res->body);
  6196. }
  6197. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6198. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6200. EXPECT_EQ(StatusCode::OK_200, res->status);
  6201. }
  6202. TEST(GzipDecompressor, ChunkedDecompression) {
  6203. std::string data;
  6204. for (size_t i = 0; i < 32 * 1024; ++i) {
  6205. data.push_back(static_cast<char>('a' + i % 26));
  6206. }
  6207. std::string compressed_data;
  6208. {
  6209. httplib::detail::gzip_compressor compressor;
  6210. bool result = compressor.compress(
  6211. data.data(), data.size(),
  6212. /*last=*/true,
  6213. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6214. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6215. compressed_data_size);
  6216. return true;
  6217. });
  6218. ASSERT_TRUE(result);
  6219. }
  6220. std::string decompressed_data;
  6221. {
  6222. httplib::detail::gzip_decompressor decompressor;
  6223. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6224. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6225. size_t chunk_size = 130;
  6226. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6227. chunk_begin += chunk_size) {
  6228. size_t current_chunk_size =
  6229. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6230. bool result = decompressor.decompress(
  6231. compressed_data.data() + chunk_begin, current_chunk_size,
  6232. [&](const char *decompressed_data_chunk,
  6233. size_t decompressed_data_chunk_size) {
  6234. decompressed_data.insert(decompressed_data.size(),
  6235. decompressed_data_chunk,
  6236. decompressed_data_chunk_size);
  6237. return true;
  6238. });
  6239. ASSERT_TRUE(result);
  6240. }
  6241. }
  6242. ASSERT_EQ(data, decompressed_data);
  6243. }
  6244. TEST(GzipDecompressor, DeflateDecompression) {
  6245. std::string original_text = "Raw deflate without gzip";
  6246. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6247. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6248. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6249. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6250. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6251. std::string decompressed_data;
  6252. {
  6253. httplib::detail::gzip_decompressor decompressor;
  6254. bool result = decompressor.decompress(
  6255. compressed_data.data(), compressed_data.size(),
  6256. [&](const char *decompressed_data_chunk,
  6257. size_t decompressed_data_chunk_size) {
  6258. decompressed_data.insert(decompressed_data.size(),
  6259. decompressed_data_chunk,
  6260. decompressed_data_chunk_size);
  6261. return true;
  6262. });
  6263. ASSERT_TRUE(result);
  6264. }
  6265. ASSERT_EQ(original_text, decompressed_data);
  6266. }
  6267. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6268. std::string original_text = "Raw deflate without gzip";
  6269. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6270. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6271. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6272. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6273. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6274. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6275. std::string decompressed_data;
  6276. {
  6277. httplib::detail::gzip_decompressor decompressor;
  6278. bool result = decompressor.decompress(
  6279. compressed_data.data(), compressed_data.size(),
  6280. [&](const char *decompressed_data_chunk,
  6281. size_t decompressed_data_chunk_size) {
  6282. decompressed_data.insert(decompressed_data.size(),
  6283. decompressed_data_chunk,
  6284. decompressed_data_chunk_size);
  6285. return true;
  6286. });
  6287. ASSERT_TRUE(result);
  6288. }
  6289. ASSERT_EQ(original_text, decompressed_data);
  6290. }
  6291. #endif
  6292. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6293. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6294. Headers headers;
  6295. headers.emplace("Accept-Encoding", "br");
  6296. auto res = cli_.Get("/streamed-chunked", headers);
  6297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6298. EXPECT_EQ(StatusCode::OK_200, res->status);
  6299. EXPECT_EQ(std::string("123456789"), res->body);
  6300. }
  6301. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6302. Headers headers;
  6303. headers.emplace("Accept-Encoding", "br");
  6304. auto res = cli_.Get("/streamed-chunked2", headers);
  6305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6306. EXPECT_EQ(StatusCode::OK_200, res->status);
  6307. EXPECT_EQ(std::string("123456789"), res->body);
  6308. }
  6309. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6310. cli_.set_compress(true);
  6311. auto res = cli_.Put(
  6312. "/put", 3,
  6313. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6314. sink.os << "PUT";
  6315. return true;
  6316. },
  6317. "text/plain");
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. EXPECT_EQ(StatusCode::OK_200, res->status);
  6320. EXPECT_EQ("PUT", res->body);
  6321. }
  6322. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6323. cli_.set_compress(true);
  6324. auto res = cli_.Put(
  6325. "/put",
  6326. [](size_t /*offset*/, DataSink &sink) {
  6327. sink.os << "PUT";
  6328. sink.done();
  6329. return true;
  6330. },
  6331. "text/plain");
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::OK_200, res->status);
  6334. EXPECT_EQ("PUT", res->body);
  6335. }
  6336. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6337. cli_.set_compress(true);
  6338. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::OK_200, res->status);
  6341. EXPECT_EQ(LARGE_DATA, res->body);
  6342. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6343. }
  6344. #endif
  6345. TEST_F(ServerTest, Patch) {
  6346. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6348. EXPECT_EQ(StatusCode::OK_200, res->status);
  6349. EXPECT_EQ("PATCH", res->body);
  6350. }
  6351. TEST_F(ServerTest, Delete) {
  6352. auto res = cli_.Delete("/delete");
  6353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6354. EXPECT_EQ(StatusCode::OK_200, res->status);
  6355. EXPECT_EQ("DELETE", res->body);
  6356. }
  6357. TEST_F(ServerTest, DeleteContentReceiver) {
  6358. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6360. EXPECT_EQ(StatusCode::OK_200, res->status);
  6361. EXPECT_EQ("content", res->body);
  6362. }
  6363. TEST_F(ServerTest, Options) {
  6364. auto res = cli_.Options("*");
  6365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6366. EXPECT_EQ(StatusCode::OK_200, res->status);
  6367. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6368. EXPECT_TRUE(res->body.empty());
  6369. }
  6370. TEST_F(ServerTest, URL) {
  6371. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6373. EXPECT_EQ(StatusCode::OK_200, res->status);
  6374. }
  6375. TEST_F(ServerTest, ArrayParam) {
  6376. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6378. EXPECT_EQ(StatusCode::OK_200, res->status);
  6379. }
  6380. TEST_F(ServerTest, ArrayParamValues) {
  6381. auto res =
  6382. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6384. EXPECT_EQ(StatusCode::OK_200, res->status);
  6385. }
  6386. TEST_F(ServerTest, NoMultipleHeaders) {
  6387. Headers headers = {{"Content-Length", "5"}};
  6388. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6389. "text/plain");
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. EXPECT_EQ(StatusCode::OK_200, res->status);
  6392. }
  6393. TEST_F(ServerTest, PostContentReceiver) {
  6394. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6396. ASSERT_EQ(StatusCode::OK_200, res->status);
  6397. ASSERT_EQ("content", res->body);
  6398. }
  6399. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6400. UploadFormDataItems items = {
  6401. {"text1", "text default", "", ""},
  6402. {"text2", "aωb", "", ""},
  6403. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6404. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6405. {"file3", "", "", "application/octet-stream"},
  6406. };
  6407. auto res = cli_.Post("/content_receiver", items);
  6408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6409. EXPECT_EQ(StatusCode::OK_200, res->status);
  6410. }
  6411. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6412. UploadFormDataItems items = {
  6413. {"text1", "text default", "", ""},
  6414. {"text2", "aωb", "", ""},
  6415. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6416. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6417. {"file3", "", "", "application/octet-stream"},
  6418. };
  6419. auto boundary = std::string("+++++");
  6420. std::string body;
  6421. for (const auto &item : items) {
  6422. body += "--" + boundary + "\r\n";
  6423. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6424. if (!item.filename.empty()) {
  6425. body += "; filename=\"" + item.filename + "\"";
  6426. }
  6427. body += "\r\n";
  6428. if (!item.content_type.empty()) {
  6429. body += "Content-Type: " + item.content_type + "\r\n";
  6430. }
  6431. body += "\r\n";
  6432. body += item.content + "\r\n";
  6433. }
  6434. body += "--" + boundary + "--\r\n";
  6435. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6436. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6438. EXPECT_EQ(StatusCode::OK_200, res->status);
  6439. }
  6440. TEST(MultipartFormDataTest, FieldEscaping) {
  6441. Server svr;
  6442. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6443. const ContentReader &content_reader) {
  6444. ASSERT_TRUE(req.is_multipart_form_data());
  6445. std::vector<FormData> received;
  6446. content_reader(
  6447. [&](const FormData &file) {
  6448. received.push_back(file);
  6449. return true;
  6450. },
  6451. [&](const char *data, size_t data_length) {
  6452. received.back().content.append(data, data_length);
  6453. return true;
  6454. });
  6455. // '"', CR and LF in names and filenames are escaped following the
  6456. // WHATWG HTML standard, so each part still parses as a single part
  6457. // with no injected headers. Content types get CR/LF escaped too,
  6458. // while '"' (legal there, e.g. quoted charset) is preserved.
  6459. ASSERT_EQ(4U, received.size());
  6460. EXPECT_EQ("na%22me", received[0].name);
  6461. EXPECT_EQ("quoted name", received[0].content);
  6462. EXPECT_EQ("file", received[1].name);
  6463. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6464. received[1].filename);
  6465. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6466. EXPECT_EQ("injected", received[1].content);
  6467. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6468. EXPECT_EQ("my%22file.txt", received[2].filename);
  6469. EXPECT_EQ("cr lf name", received[2].content);
  6470. EXPECT_EQ("typed", received[3].name);
  6471. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6472. received[3].content_type);
  6473. EXPECT_EQ("typed content", received[3].content);
  6474. });
  6475. auto port = svr.bind_to_any_port("localhost");
  6476. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6477. auto se = detail::scope_exit([&] {
  6478. svr.stop();
  6479. t.join();
  6480. ASSERT_FALSE(svr.is_running());
  6481. });
  6482. svr.wait_until_ready();
  6483. Client cli("localhost", port);
  6484. UploadFormDataItems items = {
  6485. {"na\"me", "quoted name", "", ""},
  6486. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6487. "application/octet-stream"},
  6488. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6489. {"typed", "typed content", "",
  6490. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6491. };
  6492. auto res = cli.Post("/post", items);
  6493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6494. EXPECT_EQ(StatusCode::OK_200, res->status);
  6495. }
  6496. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6497. const UploadFormDataItems items = {
  6498. {"name1", "Content 1", "", ""},
  6499. {"name2", "Content 2", "file2.txt", "text/plain"},
  6500. };
  6501. Server svr;
  6502. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6503. const ContentReader &content_reader) {
  6504. ASSERT_TRUE(req.is_multipart_form_data());
  6505. std::vector<FormData> received;
  6506. content_reader(
  6507. [&](const FormData &file) {
  6508. received.push_back(file);
  6509. return true;
  6510. },
  6511. [&](const char *data, size_t data_length) {
  6512. received.back().content.append(data, data_length);
  6513. return true;
  6514. });
  6515. ASSERT_EQ(2U, received.size());
  6516. EXPECT_EQ("name1", received[0].name);
  6517. EXPECT_EQ("Content 1", received[0].content);
  6518. EXPECT_EQ("name2", received[1].name);
  6519. EXPECT_EQ("Content 2", received[1].content);
  6520. EXPECT_EQ("file2.txt", received[1].filename);
  6521. EXPECT_EQ("text/plain", received[1].content_type);
  6522. });
  6523. auto port = svr.bind_to_any_port("localhost");
  6524. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6525. auto se = detail::scope_exit([&] {
  6526. svr.stop();
  6527. t.join();
  6528. ASSERT_FALSE(svr.is_running());
  6529. });
  6530. svr.wait_until_ready();
  6531. Client cli("localhost", port);
  6532. // Whole-body serialization with a generated boundary
  6533. {
  6534. MultipartFormDataWriter writer;
  6535. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6536. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6537. writer.content_type());
  6538. auto body = writer.serialize(items);
  6539. EXPECT_EQ(body.size(), writer.content_length(items));
  6540. auto res = cli.Post("/post", body, writer.content_type());
  6541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6542. EXPECT_EQ(StatusCode::OK_200, res->status);
  6543. }
  6544. // Per-part framing with a custom boundary via a content provider
  6545. {
  6546. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6547. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6548. MultipartFormDataWriter writer("custom-boundary_123");
  6549. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6550. std::string body;
  6551. for (const auto &item : items) {
  6552. body += writer.item_begin(item);
  6553. body += item.content;
  6554. body += MultipartFormDataWriter::item_end();
  6555. }
  6556. body += writer.finish();
  6557. EXPECT_EQ(body.size(), writer.content_length(items));
  6558. auto res = cli.Post(
  6559. "/post", body.size(),
  6560. [&](size_t offset, size_t length, DataSink &sink) {
  6561. sink.write(body.data() + offset, length);
  6562. return true;
  6563. },
  6564. writer.content_type());
  6565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6566. EXPECT_EQ(StatusCode::OK_200, res->status);
  6567. }
  6568. }
  6569. TEST_F(ServerTest, PostContentReceiverGzip) {
  6570. cli_.set_compress(true);
  6571. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6573. ASSERT_EQ(StatusCode::OK_200, res->status);
  6574. ASSERT_EQ("content", res->body);
  6575. }
  6576. TEST_F(ServerTest, PutContentReceiver) {
  6577. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6579. ASSERT_EQ(StatusCode::OK_200, res->status);
  6580. ASSERT_EQ("content", res->body);
  6581. }
  6582. TEST_F(ServerTest, PatchContentReceiver) {
  6583. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6585. ASSERT_EQ(StatusCode::OK_200, res->status);
  6586. ASSERT_EQ("content", res->body);
  6587. }
  6588. template <typename ClientType>
  6589. void TestWithHeadersAndContentReceiver(
  6590. ClientType &cli,
  6591. std::function<Result(ClientType &, const std::string &, const Headers &,
  6592. const std::string &, const std::string &,
  6593. ContentReceiver, DownloadProgress)>
  6594. request_func) {
  6595. Headers headers;
  6596. headers.emplace("X-Custom-Header", "test-value");
  6597. std::string received_body;
  6598. auto res = request_func(
  6599. cli, "/content_receiver", headers, "content", "application/json",
  6600. [&](const char *data, size_t data_length) {
  6601. received_body.append(data, data_length);
  6602. return true;
  6603. },
  6604. nullptr);
  6605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6606. EXPECT_EQ(StatusCode::OK_200, res->status);
  6607. EXPECT_EQ("content", received_body);
  6608. }
  6609. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6610. #ifdef CPPHTTPLIB_SSL_ENABLED
  6611. using ClientT = SSLClient;
  6612. #else
  6613. using ClientT = Client;
  6614. #endif
  6615. TestWithHeadersAndContentReceiver<ClientT>(
  6616. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6617. const std::string &body, const std::string &content_type,
  6618. ContentReceiver receiver, DownloadProgress progress) {
  6619. return cli.Post(path, headers, body, content_type, receiver, progress);
  6620. });
  6621. }
  6622. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6623. #ifdef CPPHTTPLIB_SSL_ENABLED
  6624. using ClientT = SSLClient;
  6625. #else
  6626. using ClientT = Client;
  6627. #endif
  6628. TestWithHeadersAndContentReceiver<ClientT>(
  6629. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6630. const std::string &body, const std::string &content_type,
  6631. ContentReceiver receiver, DownloadProgress progress) {
  6632. return cli.Put(path, headers, body, content_type, receiver, progress);
  6633. });
  6634. }
  6635. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6636. #ifdef CPPHTTPLIB_SSL_ENABLED
  6637. using ClientT = SSLClient;
  6638. #else
  6639. using ClientT = Client;
  6640. #endif
  6641. TestWithHeadersAndContentReceiver<ClientT>(
  6642. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6643. const std::string &body, const std::string &content_type,
  6644. ContentReceiver receiver, DownloadProgress progress) {
  6645. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6646. });
  6647. }
  6648. template <typename ClientType>
  6649. void TestWithHeadersAndContentReceiverWithProgress(
  6650. ClientType &cli,
  6651. std::function<Result(ClientType &, const std::string &, const Headers &,
  6652. const std::string &, const std::string &,
  6653. ContentReceiver, DownloadProgress)>
  6654. request_func) {
  6655. Headers headers;
  6656. headers.emplace("X-Test-Header", "progress-test");
  6657. std::string received_body;
  6658. auto progress_called = false;
  6659. auto res = request_func(
  6660. cli, "/content_receiver", headers, "content", "text/plain",
  6661. [&](const char *data, size_t data_length) {
  6662. received_body.append(data, data_length);
  6663. return true;
  6664. },
  6665. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6666. progress_called = true;
  6667. return true;
  6668. });
  6669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6670. EXPECT_EQ(StatusCode::OK_200, res->status);
  6671. EXPECT_EQ("content", received_body);
  6672. EXPECT_TRUE(progress_called);
  6673. }
  6674. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6675. #ifdef CPPHTTPLIB_SSL_ENABLED
  6676. using ClientT = SSLClient;
  6677. #else
  6678. using ClientT = Client;
  6679. #endif
  6680. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6681. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6682. const std::string &body, const std::string &content_type,
  6683. ContentReceiver receiver, DownloadProgress progress) {
  6684. return cli.Post(path, headers, body, content_type, receiver, progress);
  6685. });
  6686. }
  6687. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6688. #ifdef CPPHTTPLIB_SSL_ENABLED
  6689. using ClientT = SSLClient;
  6690. #else
  6691. using ClientT = Client;
  6692. #endif
  6693. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6694. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6695. const std::string &body, const std::string &content_type,
  6696. ContentReceiver receiver, DownloadProgress progress) {
  6697. return cli.Put(path, headers, body, content_type, receiver, progress);
  6698. });
  6699. }
  6700. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6701. #ifdef CPPHTTPLIB_SSL_ENABLED
  6702. using ClientT = SSLClient;
  6703. #else
  6704. using ClientT = Client;
  6705. #endif
  6706. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6707. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6708. const std::string &body, const std::string &content_type,
  6709. ContentReceiver receiver, DownloadProgress progress) {
  6710. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6711. });
  6712. }
  6713. template <typename ClientType>
  6714. void TestWithHeadersAndContentReceiverError(
  6715. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6716. const Headers &, const std::string &,
  6717. const std::string &, ContentReceiver)>
  6718. request_func) {
  6719. Headers headers;
  6720. headers.emplace("X-Error-Test", "true");
  6721. std::string received_body;
  6722. auto receiver_failed = false;
  6723. auto res =
  6724. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6725. [&](const char *data, size_t data_length) {
  6726. received_body.append(data, data_length);
  6727. receiver_failed = true;
  6728. return false;
  6729. });
  6730. ASSERT_FALSE(res);
  6731. EXPECT_TRUE(receiver_failed);
  6732. }
  6733. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6734. #ifdef CPPHTTPLIB_SSL_ENABLED
  6735. using ClientT = SSLClient;
  6736. #else
  6737. using ClientT = Client;
  6738. #endif
  6739. TestWithHeadersAndContentReceiverError<ClientT>(
  6740. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6741. const std::string &body, const std::string &content_type,
  6742. ContentReceiver receiver) {
  6743. return cli.Post(path, headers, body, content_type, receiver);
  6744. });
  6745. }
  6746. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6747. #ifdef CPPHTTPLIB_SSL_ENABLED
  6748. using ClientT = SSLClient;
  6749. #else
  6750. using ClientT = Client;
  6751. #endif
  6752. TestWithHeadersAndContentReceiverError<ClientT>(
  6753. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6754. const std::string &body, const std::string &content_type,
  6755. ContentReceiver receiver) {
  6756. return cli.Put(path, headers, body, content_type, receiver);
  6757. });
  6758. }
  6759. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6760. #ifdef CPPHTTPLIB_SSL_ENABLED
  6761. using ClientT = SSLClient;
  6762. #else
  6763. using ClientT = Client;
  6764. #endif
  6765. TestWithHeadersAndContentReceiverError<ClientT>(
  6766. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6767. const std::string &body, const std::string &content_type,
  6768. ContentReceiver receiver) {
  6769. return cli.Patch(path, headers, body, content_type, receiver);
  6770. });
  6771. }
  6772. TEST_F(ServerTest, PostQueryStringAndBody) {
  6773. auto res =
  6774. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6776. ASSERT_EQ(StatusCode::OK_200, res->status);
  6777. }
  6778. TEST_F(ServerTest, HTTP2Magic) {
  6779. Request req;
  6780. req.method = "PRI";
  6781. req.path = "*";
  6782. req.body = "SM";
  6783. auto res = std::make_shared<Response>();
  6784. auto error = Error::Success;
  6785. auto ret = cli_.send(req, *res, error);
  6786. ASSERT_TRUE(ret);
  6787. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6788. }
  6789. TEST_F(ServerTest, KeepAlive) {
  6790. auto res = cli_.Get("/hi");
  6791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6792. EXPECT_EQ(StatusCode::OK_200, res->status);
  6793. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6794. EXPECT_EQ("Hello World!", res->body);
  6795. res = cli_.Get("/hi");
  6796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6797. EXPECT_EQ(StatusCode::OK_200, res->status);
  6798. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6799. EXPECT_EQ("Hello World!", res->body);
  6800. res = cli_.Get("/hi");
  6801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6802. EXPECT_EQ(StatusCode::OK_200, res->status);
  6803. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6804. EXPECT_EQ("Hello World!", res->body);
  6805. res = cli_.Get("/not-exist");
  6806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6807. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6808. res = cli_.Post("/empty", "", "text/plain");
  6809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6810. EXPECT_EQ(StatusCode::OK_200, res->status);
  6811. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6812. EXPECT_EQ("empty", res->body);
  6813. EXPECT_EQ("close", res->get_header_value("Connection"));
  6814. res = cli_.Post(
  6815. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6816. "text/plain");
  6817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6818. EXPECT_EQ(StatusCode::OK_200, res->status);
  6819. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6820. EXPECT_EQ("empty", res->body);
  6821. cli_.set_keep_alive(false);
  6822. res = cli_.Get("/last-request");
  6823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6824. EXPECT_EQ(StatusCode::OK_200, res->status);
  6825. EXPECT_EQ("close", res->get_header_value("Connection"));
  6826. }
  6827. TEST_F(ServerTest, TooManyRedirect) {
  6828. cli_.set_follow_location(true);
  6829. auto res = cli_.Get("/redirect/0");
  6830. ASSERT_TRUE(!res);
  6831. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6832. }
  6833. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6834. Request req;
  6835. req.method = "FOOBAR";
  6836. req.path = "/hi";
  6837. cli_.set_keep_alive(true);
  6838. auto res = cli_.send(req);
  6839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6840. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6841. EXPECT_EQ("close", res->get_header_value("Connection"));
  6842. EXPECT_FALSE(cli_.is_socket_open());
  6843. }
  6844. TEST_F(ServerTest, CustomRouteReadsBody) {
  6845. const std::string xml =
  6846. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  6847. Request req;
  6848. req.method = "PROPFIND";
  6849. req.path = "/dav/dir";
  6850. req.set_header("Depth", "1");
  6851. req.body = xml;
  6852. auto res = cli_.send(req);
  6853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6854. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6855. EXPECT_EQ(xml, res->body);
  6856. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  6857. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  6858. }
  6859. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  6860. Request req;
  6861. req.method = "PROPFIND";
  6862. req.path = "/dav/42";
  6863. auto res = cli_.send(req);
  6864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6865. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6866. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  6867. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  6868. }
  6869. TEST_F(ServerTest, CustomRouteRegexPattern) {
  6870. Request req;
  6871. req.method = "PROPFIND";
  6872. req.path = "/dav-re/123";
  6873. auto res = cli_.send(req);
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6876. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  6877. }
  6878. TEST_F(ServerTest, CustomRouteWithoutBody) {
  6879. Request req;
  6880. req.method = "MKCOL";
  6881. req.path = "/dav-mkcol";
  6882. auto res = cli_.send(req);
  6883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6884. EXPECT_EQ(StatusCode::Created_201, res->status);
  6885. }
  6886. TEST_F(ServerTest, CustomRouteWithContentReader) {
  6887. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  6888. Request req;
  6889. req.method = "REPORT";
  6890. req.path = "/dav-report";
  6891. req.body = xml;
  6892. auto res = cli_.send(req);
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6895. EXPECT_EQ(xml, res->body);
  6896. }
  6897. // A content reader route must fire even when the request carries no body,
  6898. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  6899. // Without that, a body-less PROPFIND-style request would fall through to 404.
  6900. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  6901. Request req;
  6902. req.method = "REPORT";
  6903. req.path = "/dav-report";
  6904. auto res = cli_.send(req);
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6907. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  6908. }
  6909. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  6910. Request req;
  6911. req.method = "PROPFIND";
  6912. req.path = "/not-dav";
  6913. auto res = cli_.send(req);
  6914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6915. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6916. }
  6917. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  6918. Request req;
  6919. req.method = "UNLOCK";
  6920. req.path = "/dav/dir";
  6921. cli_.set_keep_alive(true);
  6922. auto res = cli_.send(req);
  6923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6924. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6925. EXPECT_EQ("close", res->get_header_value("Connection"));
  6926. EXPECT_FALSE(cli_.is_socket_open());
  6927. }
  6928. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  6929. // The mount point serves this path, but only for GET and HEAD.
  6930. auto get_res = cli_.Get("/dir/index.html");
  6931. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  6932. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  6933. Request req;
  6934. req.method = "PROPFIND";
  6935. req.path = "/dir/index.html";
  6936. auto res = cli_.send(req);
  6937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6938. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6939. }
  6940. TEST_F(ServerTest, CustomRouteKeepAlive) {
  6941. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  6942. cli_.set_keep_alive(true);
  6943. for (auto i = 0; i < 2; i++) {
  6944. Request req;
  6945. req.method = "PROPFIND";
  6946. req.path = "/dav/dir";
  6947. req.body = xml;
  6948. auto res = cli_.send(req);
  6949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6950. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6951. EXPECT_EQ(xml, res->body);
  6952. EXPECT_TRUE(cli_.is_socket_open());
  6953. }
  6954. // A built-in method must still be served on the same connection.
  6955. cli_.set_keep_alive(false);
  6956. auto res = cli_.Get("/hi");
  6957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6958. EXPECT_EQ(StatusCode::OK_200, res->status);
  6959. EXPECT_EQ("close", res->get_header_value("Connection"));
  6960. }
  6961. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  6962. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  6963. Request req;
  6964. req.method = "PROPFIND";
  6965. req.path = "/dav/dir";
  6966. req.set_header("Expect", "100-continue");
  6967. req.body = xml;
  6968. auto res = cli_.send(req);
  6969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6970. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6971. EXPECT_EQ(xml, res->body);
  6972. }
  6973. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6974. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6975. TEST_F(ServerTest, Gzip) {
  6976. Headers headers;
  6977. headers.emplace("Accept-Encoding", "gzip, deflate");
  6978. auto res = cli_.Get("/compress", headers);
  6979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6980. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6981. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6982. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6983. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6984. "7890123456789012345678901234567890",
  6985. res->body);
  6986. EXPECT_EQ(StatusCode::OK_200, res->status);
  6987. }
  6988. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6989. Headers headers;
  6990. headers.emplace("Accept-Encoding", "gzip, deflate");
  6991. auto res = cli_.Get("/compress-with-charset", headers);
  6992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6993. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6994. EXPECT_EQ("application/json; charset=utf-8",
  6995. res->get_header_value("Content-Type"));
  6996. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6997. "7890123456789012345678901234567890",
  6998. res->body);
  6999. EXPECT_EQ(StatusCode::OK_200, res->status);
  7000. }
  7001. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7002. Headers headers;
  7003. headers.emplace("Accept-Encoding", "");
  7004. auto res = cli_.Get("/compress", headers);
  7005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7006. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7007. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7008. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7009. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7010. "7890123456789012345678901234567890",
  7011. res->body);
  7012. EXPECT_EQ(StatusCode::OK_200, res->status);
  7013. }
  7014. TEST_F(ServerTest, GzipWithContentReceiver) {
  7015. Headers headers;
  7016. headers.emplace("Accept-Encoding", "gzip, deflate");
  7017. std::string body;
  7018. auto res = cli_.Get("/compress", headers,
  7019. [&](const char *data, uint64_t data_length) {
  7020. EXPECT_EQ(100U, data_length);
  7021. body.append(data, data_length);
  7022. return true;
  7023. });
  7024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7025. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7026. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7027. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7028. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7029. "7890123456789012345678901234567890",
  7030. body);
  7031. EXPECT_EQ(StatusCode::OK_200, res->status);
  7032. }
  7033. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7034. Headers headers;
  7035. headers.emplace("Accept-Encoding", "gzip, deflate");
  7036. cli_.set_decompress(false);
  7037. auto res = cli_.Get("/compress", headers);
  7038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7039. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7040. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7041. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7042. EXPECT_EQ(33U, res->body.size());
  7043. EXPECT_EQ(StatusCode::OK_200, res->status);
  7044. }
  7045. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7046. Headers headers;
  7047. headers.emplace("Accept-Encoding", "");
  7048. std::string body;
  7049. auto res = cli_.Get("/compress", headers,
  7050. [&](const char *data, uint64_t data_length) {
  7051. EXPECT_EQ(100U, data_length);
  7052. body.append(data, data_length);
  7053. return true;
  7054. });
  7055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7056. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7057. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7058. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7059. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7060. "7890123456789012345678901234567890",
  7061. body);
  7062. EXPECT_EQ(StatusCode::OK_200, res->status);
  7063. }
  7064. TEST_F(ServerTest, NoGzip) {
  7065. Headers headers;
  7066. headers.emplace("Accept-Encoding", "gzip, deflate");
  7067. auto res = cli_.Get("/nocompress", headers);
  7068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7069. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7070. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7071. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7072. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7073. "7890123456789012345678901234567890",
  7074. res->body);
  7075. EXPECT_EQ(StatusCode::OK_200, res->status);
  7076. }
  7077. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7078. Headers headers;
  7079. headers.emplace("Accept-Encoding", "gzip, deflate");
  7080. std::string body;
  7081. auto res = cli_.Get("/nocompress", headers,
  7082. [&](const char *data, uint64_t data_length) {
  7083. EXPECT_EQ(100U, data_length);
  7084. body.append(data, data_length);
  7085. return true;
  7086. });
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7089. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7090. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7091. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7092. "7890123456789012345678901234567890",
  7093. body);
  7094. EXPECT_EQ(StatusCode::OK_200, res->status);
  7095. }
  7096. TEST_F(ServerTest, MultipartFormDataGzip) {
  7097. UploadFormDataItems items = {
  7098. {"key1", "test", "", ""},
  7099. {"key2", "--abcdefg123", "", ""},
  7100. };
  7101. cli_.set_compress(true);
  7102. auto res = cli_.Post("/compress-multipart", items);
  7103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7104. EXPECT_EQ(StatusCode::OK_200, res->status);
  7105. }
  7106. #endif
  7107. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7108. TEST_F(ServerTest, Brotli) {
  7109. Headers headers;
  7110. headers.emplace("Accept-Encoding", "br");
  7111. auto res = cli_.Get("/compress", headers);
  7112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7113. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7114. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7115. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7116. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7117. "7890123456789012345678901234567890",
  7118. res->body);
  7119. EXPECT_EQ(StatusCode::OK_200, res->status);
  7120. }
  7121. #endif
  7122. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7123. TEST_F(ServerTest, Zstd) {
  7124. Headers headers;
  7125. headers.emplace("Accept-Encoding", "zstd");
  7126. auto res = cli_.Get("/compress", headers);
  7127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7128. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7129. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7130. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7131. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7132. "7890123456789012345678901234567890",
  7133. res->body);
  7134. EXPECT_EQ(StatusCode::OK_200, res->status);
  7135. }
  7136. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7137. Headers headers;
  7138. headers.emplace("Accept-Encoding", "");
  7139. auto res = cli_.Get("/compress", headers);
  7140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7141. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7142. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7143. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7144. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7145. "7890123456789012345678901234567890",
  7146. res->body);
  7147. EXPECT_EQ(StatusCode::OK_200, res->status);
  7148. }
  7149. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7150. Headers headers;
  7151. headers.emplace("Accept-Encoding", "zstd");
  7152. std::string body;
  7153. auto res = cli_.Get("/compress", headers,
  7154. [&](const char *data, uint64_t data_length) {
  7155. EXPECT_EQ(100U, data_length);
  7156. body.append(data, data_length);
  7157. return true;
  7158. });
  7159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7160. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7161. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7162. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7163. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7164. "7890123456789012345678901234567890",
  7165. body);
  7166. EXPECT_EQ(StatusCode::OK_200, res->status);
  7167. }
  7168. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7169. Headers headers;
  7170. headers.emplace("Accept-Encoding", "zstd");
  7171. cli_.set_decompress(false);
  7172. auto res = cli_.Get("/compress", headers);
  7173. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7174. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7175. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7176. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7178. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7179. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7180. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7181. EXPECT_EQ(StatusCode::OK_200, res->status);
  7182. ASSERT_EQ(26U, res->body.size());
  7183. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7184. 0);
  7185. }
  7186. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7187. Headers headers;
  7188. headers.emplace("Accept-Encoding", "");
  7189. std::string body;
  7190. auto res = cli_.Get("/compress", headers,
  7191. [&](const char *data, uint64_t data_length) {
  7192. EXPECT_EQ(100U, data_length);
  7193. body.append(data, data_length);
  7194. return true;
  7195. });
  7196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7197. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7198. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7199. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7200. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7201. "7890123456789012345678901234567890",
  7202. body);
  7203. EXPECT_EQ(StatusCode::OK_200, res->status);
  7204. }
  7205. TEST_F(ServerTest, NoZstd) {
  7206. Headers headers;
  7207. headers.emplace("Accept-Encoding", "zstd");
  7208. auto res = cli_.Get("/nocompress", headers);
  7209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7210. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7211. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7212. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7213. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7214. "7890123456789012345678901234567890",
  7215. res->body);
  7216. EXPECT_EQ(StatusCode::OK_200, res->status);
  7217. }
  7218. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7219. Headers headers;
  7220. headers.emplace("Accept-Encoding", "zstd");
  7221. std::string body;
  7222. auto res = cli_.Get("/nocompress", headers,
  7223. [&](const char *data, uint64_t data_length) {
  7224. EXPECT_EQ(100U, data_length);
  7225. body.append(data, data_length);
  7226. return true;
  7227. });
  7228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7229. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7230. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7231. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7232. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7233. "7890123456789012345678901234567890",
  7234. body);
  7235. EXPECT_EQ(StatusCode::OK_200, res->status);
  7236. }
  7237. // TODO: How to enable zstd ??
  7238. TEST_F(ServerTest, MultipartFormDataZstd) {
  7239. UploadFormDataItems items = {
  7240. {"key1", "test", "", ""},
  7241. {"key2", "--abcdefg123", "", ""},
  7242. };
  7243. Headers headers;
  7244. headers.emplace("Accept-Encoding", "zstd");
  7245. cli_.set_compress(true);
  7246. auto res = cli_.Post("/compress-multipart", headers, items);
  7247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7248. EXPECT_EQ(StatusCode::OK_200, res->status);
  7249. }
  7250. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7251. Headers headers;
  7252. headers.emplace("Accept-Encoding", "zstd");
  7253. cli_.set_compress(true);
  7254. auto res = cli_.Put(
  7255. "/put", headers, 3,
  7256. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7257. sink.os << "PUT";
  7258. return true;
  7259. },
  7260. "text/plain");
  7261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7262. EXPECT_EQ(StatusCode::OK_200, res->status);
  7263. EXPECT_EQ("PUT", res->body);
  7264. }
  7265. // Pre-compression logging tests
  7266. TEST_F(ServerTest, PreCompressionLogging) {
  7267. // Test data for compression (matches the actual /compress endpoint content)
  7268. const std::string test_content =
  7269. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7270. "3456789012345678901234567890";
  7271. // Variables to capture logging data
  7272. std::string pre_compression_body;
  7273. std::string pre_compression_content_type;
  7274. std::string pre_compression_content_encoding;
  7275. std::string post_compression_body;
  7276. std::string post_compression_content_type;
  7277. std::string post_compression_content_encoding;
  7278. // Set up pre-compression logger
  7279. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7280. const Response &res) {
  7281. pre_compression_body = res.body;
  7282. pre_compression_content_type = res.get_header_value("Content-Type");
  7283. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7284. });
  7285. // Set up post-compression logger
  7286. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7287. post_compression_body = res.body;
  7288. post_compression_content_type = res.get_header_value("Content-Type");
  7289. post_compression_content_encoding =
  7290. res.get_header_value("Content-Encoding");
  7291. });
  7292. // Test with gzip compression
  7293. Headers headers;
  7294. headers.emplace("Accept-Encoding", "gzip");
  7295. auto res = cli_.Get("/compress", headers);
  7296. // Verify response was compressed
  7297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7298. EXPECT_EQ(StatusCode::OK_200, res->status);
  7299. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7300. // Verify pre-compression logger captured uncompressed content
  7301. EXPECT_EQ(test_content, pre_compression_body);
  7302. EXPECT_EQ("text/plain", pre_compression_content_type);
  7303. EXPECT_TRUE(pre_compression_content_encoding
  7304. .empty()); // No encoding header before compression
  7305. // Verify post-compression logger captured compressed content
  7306. EXPECT_NE(test_content,
  7307. post_compression_body); // Should be different after compression
  7308. EXPECT_EQ("text/plain", post_compression_content_type);
  7309. EXPECT_EQ("gzip", post_compression_content_encoding);
  7310. // Verify compressed content is smaller
  7311. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7312. }
  7313. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7314. const std::string test_content =
  7315. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7316. "3456789012345678901234567890";
  7317. std::string pre_compression_body;
  7318. std::string post_compression_body;
  7319. svr_.set_pre_compression_logger(
  7320. [&](const Request & /*req*/, const Response &res) {
  7321. pre_compression_body = res.body;
  7322. });
  7323. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7324. post_compression_body = res.body;
  7325. });
  7326. Headers headers;
  7327. headers.emplace("Accept-Encoding", "br");
  7328. auto res = cli_.Get("/compress", headers);
  7329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7330. EXPECT_EQ(StatusCode::OK_200, res->status);
  7331. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7332. // Verify pre-compression content is uncompressed
  7333. EXPECT_EQ(test_content, pre_compression_body);
  7334. // Verify post-compression content is compressed
  7335. EXPECT_NE(test_content, post_compression_body);
  7336. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7337. }
  7338. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7339. const std::string test_content =
  7340. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7341. "3456789012345678901234567890";
  7342. std::string pre_compression_body;
  7343. std::string post_compression_body;
  7344. svr_.set_pre_compression_logger(
  7345. [&](const Request & /*req*/, const Response &res) {
  7346. pre_compression_body = res.body;
  7347. });
  7348. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7349. post_compression_body = res.body;
  7350. });
  7351. // Request without compression (use /nocompress endpoint)
  7352. Headers headers;
  7353. auto res = cli_.Get("/nocompress", headers);
  7354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7355. EXPECT_EQ(StatusCode::OK_200, res->status);
  7356. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7357. // Pre-compression logger should not be called when no compression is applied
  7358. EXPECT_TRUE(
  7359. pre_compression_body.empty()); // Pre-compression logger not called
  7360. EXPECT_EQ(
  7361. test_content,
  7362. post_compression_body); // Post-compression logger captures final content
  7363. }
  7364. TEST_F(ServerTest, LoggerSeesContentLength) {
  7365. size_t logged_content_length = 0;
  7366. std::string logged_content_length_header;
  7367. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7368. logged_content_length = res.content_length_;
  7369. logged_content_length_header = res.get_header_value("Content-Length");
  7370. });
  7371. auto res = cli_.Get("/nocompress");
  7372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7373. EXPECT_EQ(StatusCode::OK_200, res->status);
  7374. EXPECT_EQ(res->body.size(), logged_content_length);
  7375. EXPECT_EQ(std::to_string(logged_content_length),
  7376. logged_content_length_header);
  7377. }
  7378. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7379. const std::string test_content =
  7380. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7381. "3456789012345678901234567890";
  7382. std::string pre_compression_body;
  7383. bool pre_logger_called = false;
  7384. // Set only pre-compression logger
  7385. svr_.set_pre_compression_logger(
  7386. [&](const Request & /*req*/, const Response &res) {
  7387. pre_compression_body = res.body;
  7388. pre_logger_called = true;
  7389. });
  7390. Headers headers;
  7391. headers.emplace("Accept-Encoding", "gzip");
  7392. auto res = cli_.Get("/compress", headers);
  7393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7394. EXPECT_EQ(StatusCode::OK_200, res->status);
  7395. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7396. // Verify pre-compression logger was called
  7397. EXPECT_TRUE(pre_logger_called);
  7398. EXPECT_EQ(test_content, pre_compression_body);
  7399. }
  7400. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7401. {
  7402. // Test with Expect: 100-continue header - success case
  7403. // Server returns 100 Continue, client sends body, server returns 200 OK
  7404. Request req;
  7405. req.method = "POST";
  7406. req.path = "/post-large";
  7407. req.set_header("Expect", "100-continue");
  7408. req.body = LARGE_DATA;
  7409. Response res;
  7410. auto error = Error::Success;
  7411. cli_.set_keep_alive(true);
  7412. auto ret = cli_.send(req, res, error);
  7413. EXPECT_TRUE(ret);
  7414. EXPECT_EQ(StatusCode::OK_200, res.status);
  7415. EXPECT_EQ(LARGE_DATA, res.body);
  7416. }
  7417. {
  7418. // Test with Expect: 100-continue header - error case
  7419. // Client should not send the body when server returns an error
  7420. Request req;
  7421. req.method = "POST";
  7422. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7423. req.set_header("Expect", "100-continue");
  7424. req.body = LARGE_DATA;
  7425. Response res;
  7426. auto error = Error::Success;
  7427. auto start = std::chrono::high_resolution_clock::now();
  7428. cli_.set_keep_alive(true);
  7429. auto ret = cli_.send(req, res, error);
  7430. auto end = std::chrono::high_resolution_clock::now();
  7431. auto elapsed =
  7432. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7433. .count();
  7434. // With Expect: 100-continue, request completes successfully but with error
  7435. EXPECT_TRUE(ret);
  7436. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7437. EXPECT_EQ("close", res.get_header_value("Connection"));
  7438. EXPECT_FALSE(cli_.is_socket_open());
  7439. EXPECT_LE(elapsed, 2000);
  7440. }
  7441. {
  7442. // Send an extra GET request to ensure error recovery without hanging
  7443. Request req;
  7444. req.method = "GET";
  7445. req.path = "/hi";
  7446. auto start = std::chrono::high_resolution_clock::now();
  7447. auto res = cli_.send(req);
  7448. auto end = std::chrono::high_resolution_clock::now();
  7449. auto elapsed =
  7450. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7451. .count();
  7452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7453. EXPECT_EQ(StatusCode::OK_200, res->status);
  7454. EXPECT_EQ("Hello World!", res->body);
  7455. EXPECT_LE(elapsed, 500);
  7456. }
  7457. }
  7458. TEST(ZstdDecompressor, ChunkedDecompression) {
  7459. std::string data;
  7460. for (size_t i = 0; i < 32 * 1024; ++i) {
  7461. data.push_back(static_cast<char>('a' + i % 26));
  7462. }
  7463. std::string compressed_data;
  7464. {
  7465. httplib::detail::zstd_compressor compressor;
  7466. bool result = compressor.compress(
  7467. data.data(), data.size(),
  7468. /*last=*/true,
  7469. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7470. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7471. compressed_data_size);
  7472. return true;
  7473. });
  7474. ASSERT_TRUE(result);
  7475. }
  7476. std::string decompressed_data;
  7477. {
  7478. httplib::detail::zstd_decompressor decompressor;
  7479. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7480. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7481. size_t chunk_size = 130;
  7482. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7483. chunk_begin += chunk_size) {
  7484. size_t current_chunk_size =
  7485. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7486. bool result = decompressor.decompress(
  7487. compressed_data.data() + chunk_begin, current_chunk_size,
  7488. [&](const char *decompressed_data_chunk,
  7489. size_t decompressed_data_chunk_size) {
  7490. decompressed_data.insert(decompressed_data.size(),
  7491. decompressed_data_chunk,
  7492. decompressed_data_chunk_size);
  7493. return true;
  7494. });
  7495. ASSERT_TRUE(result);
  7496. }
  7497. }
  7498. ASSERT_EQ(data, decompressed_data);
  7499. }
  7500. TEST(ZstdDecompressor, Decompress) {
  7501. std::string original_text = "Compressed with ZSTD";
  7502. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7503. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7504. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7505. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7506. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7507. std::string decompressed_data;
  7508. {
  7509. httplib::detail::zstd_decompressor decompressor;
  7510. bool result = decompressor.decompress(
  7511. compressed_data.data(), compressed_data.size(),
  7512. [&](const char *decompressed_data_chunk,
  7513. size_t decompressed_data_chunk_size) {
  7514. decompressed_data.insert(decompressed_data.size(),
  7515. decompressed_data_chunk,
  7516. decompressed_data_chunk_size);
  7517. return true;
  7518. });
  7519. ASSERT_TRUE(result);
  7520. }
  7521. ASSERT_EQ(original_text, decompressed_data);
  7522. }
  7523. #endif
  7524. // Sends a raw request to a server listening at HOST:PORT, writing it in
  7525. // separate chunks so that the server sees each part in its own read(). Used to
  7526. // place a read boundary at a specific offset of a request body.
  7527. static bool send_request_in_parts(time_t read_timeout_sec,
  7528. const std::vector<std::string> &parts,
  7529. std::string *resp = nullptr,
  7530. int port = PORT) {
  7531. auto error = Error::Success;
  7532. auto client_sock = detail::create_client_socket(
  7533. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7534. /*connection_timeout_sec=*/5, 0,
  7535. /*read_timeout_sec=*/5, 0,
  7536. /*write_timeout_sec=*/5, 0, std::string(), error);
  7537. if (client_sock == INVALID_SOCKET) { return false; }
  7538. auto ret = detail::process_client_socket(
  7539. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7540. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7541. for (size_t i = 0; i < parts.size(); i++) {
  7542. const auto &part = parts[i];
  7543. if (part.size() !=
  7544. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  7545. return false;
  7546. }
  7547. if (i + 1 < parts.size()) {
  7548. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7549. }
  7550. }
  7551. char buf[512];
  7552. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7553. while (line_reader.getline()) {
  7554. if (resp) { *resp += line_reader.ptr(); }
  7555. }
  7556. return true;
  7557. });
  7558. detail::close_socket(client_sock);
  7559. return ret;
  7560. }
  7561. // Sends a raw request to a server listening at HOST:PORT.
  7562. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7563. std::string *resp = nullptr, int port = PORT) {
  7564. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  7565. }
  7566. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7567. Server svr;
  7568. std::string header_value;
  7569. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7570. header_value = req.get_header_value("foo");
  7571. res.set_content("ok", "text/plain");
  7572. });
  7573. thread t = thread([&] { svr.listen(HOST, PORT); });
  7574. auto se = detail::scope_exit([&] {
  7575. svr.stop();
  7576. t.join();
  7577. ASSERT_FALSE(svr.is_running());
  7578. });
  7579. svr.wait_until_ready();
  7580. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7581. // like characters are not treated the same - use vertical tab and escape.
  7582. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7583. "foo: \t \v bar \x1B\t \r\n"
  7584. "Connection: close\r\n"
  7585. "\r\n";
  7586. std::string res;
  7587. ASSERT_TRUE(send_request(5, req, &res));
  7588. EXPECT_EQ(header_value, "");
  7589. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7590. }
  7591. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7592. Server svr;
  7593. std::string received;
  7594. svr.Get("/order", [&](const Request &req, Response &res) {
  7595. received = entries_to_string(req.headers);
  7596. res.set_content("ok", "text/plain");
  7597. });
  7598. auto port = svr.bind_to_any_port(HOST);
  7599. thread t = thread([&] { svr.listen_after_bind(); });
  7600. auto se = detail::scope_exit([&] {
  7601. svr.stop();
  7602. t.join();
  7603. ASSERT_FALSE(svr.is_running());
  7604. });
  7605. svr.wait_until_ready();
  7606. const std::string req = "GET /order HTTP/1.1\r\n"
  7607. "X-First: 1\r\n"
  7608. "X-Dup: a\r\n"
  7609. "X-Second: 2\r\n"
  7610. "X-Dup: b\r\n"
  7611. "Connection: close\r\n"
  7612. "\r\n";
  7613. std::string res;
  7614. ASSERT_TRUE(send_request(5, req, &res, port));
  7615. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7616. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7617. }
  7618. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7619. Server svr;
  7620. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7621. res.set_header("Set-Cookie", "first=1");
  7622. res.set_header("X-Between", "y");
  7623. res.set_header("Set-Cookie", "second=2");
  7624. res.set_content("ok", "text/plain");
  7625. });
  7626. auto port = svr.bind_to_any_port(HOST);
  7627. thread t = thread([&] { svr.listen_after_bind(); });
  7628. auto se = detail::scope_exit([&] {
  7629. svr.stop();
  7630. t.join();
  7631. ASSERT_FALSE(svr.is_running());
  7632. });
  7633. svr.wait_until_ready();
  7634. Client cli(HOST, port);
  7635. auto res = cli.Get("/cookies");
  7636. ASSERT_TRUE(res);
  7637. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7638. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7639. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7640. }
  7641. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7642. Server svr;
  7643. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7644. auto i = new int(0);
  7645. res.set_header("Trailer", "X-Safe, X-Reflected");
  7646. res.set_chunked_content_provider(
  7647. "text/plain",
  7648. [i](size_t /*offset*/, DataSink &sink) {
  7649. if (*i == 0) {
  7650. sink.os << "body";
  7651. } else {
  7652. Headers trailer;
  7653. // A valid trailer that must survive.
  7654. trailer.emplace("X-Safe", "safe");
  7655. // Attacker-controlled value carrying CR/LF (response splitting).
  7656. trailer.emplace("X-Reflected",
  7657. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7658. // Attacker-controlled name carrying CR/LF.
  7659. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7660. sink.done_with_trailer(trailer);
  7661. }
  7662. (*i)++;
  7663. return true;
  7664. },
  7665. [i](bool /*success*/) { delete i; });
  7666. });
  7667. thread t = thread([&] { svr.listen(HOST, PORT); });
  7668. auto se = detail::scope_exit([&] {
  7669. svr.stop();
  7670. t.join();
  7671. ASSERT_FALSE(svr.is_running());
  7672. });
  7673. svr.wait_until_ready();
  7674. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7675. "Host: " + HOST +
  7676. "\r\n"
  7677. "Connection: close\r\n"
  7678. "\r\n";
  7679. std::string res;
  7680. ASSERT_TRUE(send_request(5, req, &res));
  7681. // The injected fields must not appear anywhere in the raw response.
  7682. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7683. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7684. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7685. // Invalid trailers are dropped entirely, matching set_header().
  7686. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7687. // The valid trailer still passes through.
  7688. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7689. }
  7690. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7691. Server svr;
  7692. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7693. // res.headers is a public field an application can populate directly,
  7694. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7695. // A valid header that must survive.
  7696. res.headers.emplace("X-Safe", "safe");
  7697. // Attacker-controlled value carrying CR/LF (response splitting).
  7698. res.headers.emplace("X-Reflected",
  7699. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7700. // Attacker-controlled name carrying CR/LF.
  7701. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7702. res.set_content("body", "text/plain");
  7703. });
  7704. thread t = thread([&] { svr.listen(HOST, PORT); });
  7705. auto se = detail::scope_exit([&] {
  7706. svr.stop();
  7707. t.join();
  7708. ASSERT_FALSE(svr.is_running());
  7709. });
  7710. svr.wait_until_ready();
  7711. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7712. "Host: " + HOST +
  7713. "\r\n"
  7714. "Connection: close\r\n"
  7715. "\r\n";
  7716. std::string res;
  7717. ASSERT_TRUE(send_request(5, req, &res));
  7718. // The injected fields must not appear anywhere in the raw response.
  7719. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7720. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7721. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7722. // Invalid headers are dropped entirely, matching set_header().
  7723. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7724. // The valid header still passes through.
  7725. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7726. }
  7727. // Forward declaration: in split builds split.py strips `inline` and moves the
  7728. // definition into httplib.cc, so detail::write_request_line is not visible from
  7729. // the public httplib.h. Re-declaring it here lets the tests link against the
  7730. // symbol in both header-only and split builds.
  7731. namespace httplib {
  7732. namespace detail {
  7733. ssize_t write_request_line(Stream &strm, const std::string &method,
  7734. const std::string &path);
  7735. } // namespace detail
  7736. } // namespace httplib
  7737. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7738. // A well-formed target is written verbatim.
  7739. {
  7740. detail::BufferStream strm;
  7741. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7742. EXPECT_GT(n, 0);
  7743. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7744. }
  7745. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7746. // otherwise it splits the request line and injects a header or a whole
  7747. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7748. // when path encoding is disabled.
  7749. const std::string evil_targets[] = {
  7750. "/a\r\nInjected: pwned",
  7751. "/a\rInjected",
  7752. "/a\nInjected",
  7753. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7754. };
  7755. for (const auto &evil : evil_targets) {
  7756. detail::BufferStream strm;
  7757. auto n = detail::write_request_line(strm, "GET", evil);
  7758. EXPECT_LT(n, 0);
  7759. EXPECT_TRUE(strm.get_buffer().empty());
  7760. }
  7761. }
  7762. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7763. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7764. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7765. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7766. // client must fail cleanly with Error::Write instead of putting a
  7767. // request-line-less, header-injecting request on the wire.
  7768. Server svr;
  7769. svr.Get("/a", [](const Request &, Response &res) {
  7770. res.set_content("ok", "text/plain");
  7771. });
  7772. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7773. auto se = detail::scope_exit([&] {
  7774. svr.stop();
  7775. thread.join();
  7776. ASSERT_FALSE(svr.is_running());
  7777. });
  7778. svr.wait_until_ready();
  7779. {
  7780. Client cli(HOST, PORT);
  7781. cli.set_path_encode(false);
  7782. // The request is rejected before anything is written, so the connection
  7783. // stays silent and the subsequent response read would otherwise block for
  7784. // the full default read timeout. Shorten it -- the assertion is on the
  7785. // error, not the timeout.
  7786. cli.set_read_timeout(1, 0);
  7787. auto res = cli.Get("/a\r\nInjected: pwned");
  7788. EXPECT_FALSE(res);
  7789. EXPECT_EQ(Error::Write, res.error());
  7790. }
  7791. }
  7792. // Sends a raw request and verifies that there isn't a crash or exception.
  7793. static void test_raw_request(const std::string &req,
  7794. std::string *out = nullptr) {
  7795. Server svr;
  7796. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7797. res.set_content("ok", "text/plain");
  7798. });
  7799. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7800. res.set_content("ok", "text/plain");
  7801. });
  7802. svr.Get("/header_field_value_check",
  7803. [&](const Request & /*req*/, Response &res) {
  7804. res.set_content("ok", "text/plain");
  7805. });
  7806. svr.CustomRoute("PROPFIND", "/dav",
  7807. [&](const Request & /*req*/, Response &res) {
  7808. res.status = StatusCode::MultiStatus_207;
  7809. });
  7810. // Server read timeout must be longer than the client read timeout for the
  7811. // bug to reproduce, probably to force the server to process a request
  7812. // without a trailing blank line.
  7813. const time_t client_read_timeout_sec = 1;
  7814. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7815. bool listen_thread_ok = false;
  7816. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7817. auto se = detail::scope_exit([&] {
  7818. svr.stop();
  7819. t.join();
  7820. ASSERT_FALSE(svr.is_running());
  7821. EXPECT_TRUE(listen_thread_ok);
  7822. });
  7823. svr.wait_until_ready();
  7824. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7825. }
  7826. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7827. // A certain header line causes an exception if the header property is parsed
  7828. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7829. test_raw_request(
  7830. "GET /hi HTTP/1.1\r\n"
  7831. " : "
  7832. " "
  7833. " ");
  7834. }
  7835. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7836. // A certain header line causes an exception if the header property *name* is
  7837. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7838. // greedy matcher and requires backtracking when there are a lot of ":"
  7839. // characters.
  7840. // This occurs with libc++ but not libstdc++.
  7841. test_raw_request(
  7842. "GET /hi HTTP/1.1\r\n"
  7843. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7844. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7845. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7846. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7847. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7848. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7849. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7850. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7851. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7852. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7853. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7854. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7855. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7856. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7857. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7858. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7859. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7860. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7861. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7862. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7863. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7864. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7865. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7866. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7867. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7868. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7869. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7870. "&&&%%%");
  7871. }
  7872. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7873. // Make sure this doesn't crash the server.
  7874. // In a previous version of the header line regex, the "\r" rendered the line
  7875. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7876. // a new position where the leading white space ended and the field value
  7877. // began.
  7878. // The crash occurs with libc++ but not libstdc++.
  7879. test_raw_request("GET /hi HTTP/1.1\r\n"
  7880. "a:" +
  7881. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7882. "\r\n"
  7883. "\r\n");
  7884. }
  7885. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7886. std::string out;
  7887. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7888. "Content-Type: text/plain\r\n"
  7889. "Transfer-Encoding: chunked\r\n"
  7890. "\r\n"
  7891. "nothex\r\n",
  7892. &out);
  7893. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7894. }
  7895. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7896. std::string out;
  7897. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7898. "Content-Type: text/plain\r\n"
  7899. "Transfer-Encoding: chunked\r\n"
  7900. "\r\n"
  7901. "3\r\n"
  7902. "xyz\r\n"
  7903. "NaN\r\n",
  7904. &out);
  7905. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7906. }
  7907. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7908. std::string out;
  7909. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7910. "Content-Type: text/plain\r\n"
  7911. "Transfer-Encoding: chunked\r\n"
  7912. "\r\n"
  7913. // Length is too large for 64 bits.
  7914. "1ffffffffffffffff\r\n"
  7915. "xyz\r\n",
  7916. &out);
  7917. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7918. }
  7919. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7920. test_raw_request("GET /hi HTTP/1.1\r\n"
  7921. "Content-Type: text/plain\r\n\r");
  7922. }
  7923. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7924. std::string out;
  7925. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7926. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7927. }
  7928. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7929. Server svr;
  7930. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7931. EXPECT_TRUE(!req.remote_addr.empty());
  7932. });
  7933. thread t = thread([&] { svr.listen(HOST, PORT); });
  7934. auto se = detail::scope_exit([&] {
  7935. svr.stop();
  7936. t.join();
  7937. ASSERT_FALSE(svr.is_running());
  7938. });
  7939. svr.wait_until_ready();
  7940. // Send an invalid request line to trigger Bad Request
  7941. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7942. std::string out;
  7943. ASSERT_TRUE(send_request(5, bad_req, &out));
  7944. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7945. }
  7946. // A custom method with neither Content-Length nor Transfer-Encoding must be
  7947. // answered right away rather than blocking on a read that waits for EOF.
  7948. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  7949. std::string out;
  7950. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  7951. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  7952. }
  7953. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  7954. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  7955. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  7956. for (const auto *method : methods) {
  7957. Server svr;
  7958. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  7959. EXPECT_FALSE(svr.is_valid()) << method;
  7960. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  7961. }
  7962. }
  7963. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  7964. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  7965. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  7966. for (const auto *method : methods) {
  7967. Server svr;
  7968. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  7969. EXPECT_FALSE(svr.is_valid()) << method;
  7970. }
  7971. }
  7972. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  7973. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  7974. "COPY", "MOVE", "LOCK",
  7975. "UNLOCK", "REPORT", "SUBSCRIBE"};
  7976. Server svr;
  7977. for (const auto *method : methods) {
  7978. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  7979. }
  7980. EXPECT_TRUE(svr.is_valid());
  7981. }
  7982. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  7983. Server svr;
  7984. svr.CustomRoute("POST", "/x",
  7985. [](const Request &, Response &, const ContentReader &) {});
  7986. EXPECT_FALSE(svr.is_valid());
  7987. }
  7988. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  7989. Server svr;
  7990. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  7991. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  7992. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  7993. EXPECT_FALSE(svr.is_valid());
  7994. }
  7995. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  7996. Server svr;
  7997. auto captured = Error::Success;
  7998. svr.set_error_logger(
  7999. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8000. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8001. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8002. }
  8003. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8004. std::string out;
  8005. std::string request(
  8006. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8007. test_raw_request(request, &out);
  8008. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8009. }
  8010. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8011. std::string out;
  8012. std::string request(
  8013. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8014. test_raw_request(request, &out);
  8015. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8016. }
  8017. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8018. std::string out;
  8019. std::string request(
  8020. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8021. test_raw_request(request, &out);
  8022. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8023. }
  8024. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8025. std::string out;
  8026. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8027. "Test: \r\n\r\n",
  8028. &out);
  8029. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8030. }
  8031. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8032. Server svr;
  8033. std::string x_custom;
  8034. std::string cookie;
  8035. std::string xff;
  8036. std::string x_unicode;
  8037. std::string x_iis;
  8038. svr.Get("/check", [&](const Request &req, Response &res) {
  8039. x_custom = req.get_header_value("X-Custom");
  8040. cookie = req.get_header_value("Cookie");
  8041. xff = req.get_header_value("X-Forwarded-For");
  8042. x_unicode = req.get_header_value("X-Unicode");
  8043. x_iis = req.get_header_value("X-IIS");
  8044. res.set_content("ok", "text/plain");
  8045. });
  8046. thread t = thread([&] { svr.listen(HOST, PORT); });
  8047. auto se = detail::scope_exit([&] {
  8048. svr.stop();
  8049. t.join();
  8050. ASSERT_FALSE(svr.is_running());
  8051. });
  8052. svr.wait_until_ready();
  8053. const std::string req = "GET /check HTTP/1.1\r\n"
  8054. "Host: localhost\r\n"
  8055. "X-Custom: a%0D%0AInjected: b\r\n"
  8056. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8057. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8058. "X-Unicode: %E3%81%82\r\n"
  8059. "X-IIS: %u00E9\r\n"
  8060. "Connection: close\r\n"
  8061. "\r\n";
  8062. std::string res;
  8063. ASSERT_TRUE(send_request(5, req, &res));
  8064. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8065. // Every value must be returned verbatim (wire form), with no decoding.
  8066. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8067. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8068. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8069. EXPECT_EQ("%E3%81%82", x_unicode);
  8070. EXPECT_EQ("%u00E9", x_iis);
  8071. }
  8072. // Applications that previously relied on automatic percent-decoding can
  8073. // reproduce the old behavior by explicitly calling decode_path_component()
  8074. // or, for RFC 3986 conformance, decode_uri_component().
  8075. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8076. Server svr;
  8077. std::string decoded;
  8078. svr.Get("/check", [&](const Request &req, Response &res) {
  8079. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8080. res.set_content("ok", "text/plain");
  8081. });
  8082. thread t = thread([&] { svr.listen(HOST, PORT); });
  8083. auto se = detail::scope_exit([&] {
  8084. svr.stop();
  8085. t.join();
  8086. ASSERT_FALSE(svr.is_running());
  8087. });
  8088. svr.wait_until_ready();
  8089. const std::string req = "GET /check HTTP/1.1\r\n"
  8090. "Host: localhost\r\n"
  8091. "X-Custom: hello%20world\r\n"
  8092. "Connection: close\r\n"
  8093. "\r\n";
  8094. std::string res;
  8095. ASSERT_TRUE(send_request(5, req, &res));
  8096. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8097. EXPECT_EQ("hello world", decoded);
  8098. }
  8099. // Regression test for #2033. Browsers send Referer values that include
  8100. // percent-encoded characters such as %0A inside the URL. Decoding the
  8101. // header value would either trip the post-decode CR/LF/NUL guard (the
  8102. // original bug, returning 400) or, after that guard was relaxed, silently
  8103. // store a literal LF — both unacceptable. The wire form must round-trip.
  8104. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8105. Server svr;
  8106. std::string referer;
  8107. svr.Get("/check", [&](const Request &req, Response &res) {
  8108. referer = req.get_header_value("Referer");
  8109. res.set_content("ok", "text/plain");
  8110. });
  8111. thread t = thread([&] { svr.listen(HOST, PORT); });
  8112. auto se = detail::scope_exit([&] {
  8113. svr.stop();
  8114. t.join();
  8115. ASSERT_FALSE(svr.is_running());
  8116. });
  8117. svr.wait_until_ready();
  8118. const std::string req = "GET /check HTTP/1.1\r\n"
  8119. "Host: localhost\r\n"
  8120. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8121. "Connection: close\r\n"
  8122. "\r\n";
  8123. std::string res;
  8124. ASSERT_TRUE(send_request(5, req, &res));
  8125. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8126. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8127. }
  8128. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8129. Server svr;
  8130. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8131. res.set_header("Cache-Control", "no-cache");
  8132. res.set_chunked_content_provider(
  8133. "text/event-stream", [](size_t offset, DataSink &sink) {
  8134. std::string s = "data:";
  8135. s += std::to_string(offset);
  8136. s += "\n\n";
  8137. auto ret = sink.write(s.data(), s.size());
  8138. EXPECT_TRUE(ret);
  8139. std::this_thread::sleep_for(std::chrono::seconds(1));
  8140. return true;
  8141. });
  8142. });
  8143. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8144. svr.wait_until_ready();
  8145. Client client(HOST, PORT);
  8146. const Headers headers = {{"Accept", "text/event-stream"}};
  8147. auto get_thread = std::thread([&client, &headers]() {
  8148. auto res = client.Get(
  8149. "/events", headers,
  8150. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  8151. });
  8152. auto se = detail::scope_exit([&] {
  8153. svr.stop();
  8154. get_thread.join();
  8155. listen_thread.join();
  8156. ASSERT_FALSE(svr.is_running());
  8157. });
  8158. // Give GET time to get a few messages.
  8159. std::this_thread::sleep_for(std::chrono::seconds(2));
  8160. }
  8161. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  8162. httplib::Server svr;
  8163. svr.Post("/hi",
  8164. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8165. res.status = StatusCode::OK_200;
  8166. });
  8167. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8168. svr.wait_until_ready();
  8169. Client cli(HOST, PORT);
  8170. auto res = cli.Post("/hi", "data", "text/plain");
  8171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8172. EXPECT_EQ(StatusCode::OK_200, res->status);
  8173. svr.stop();
  8174. thread.join();
  8175. ASSERT_FALSE(svr.is_running());
  8176. res = cli.Post("/hi", "data", "text/plain");
  8177. ASSERT_FALSE(res);
  8178. }
  8179. TEST(ServerStopTest, ListenFailure) {
  8180. Server svr;
  8181. auto t = thread([&]() {
  8182. auto ret = svr.listen("????", PORT);
  8183. EXPECT_FALSE(ret);
  8184. });
  8185. svr.wait_until_ready();
  8186. svr.stop();
  8187. t.join();
  8188. }
  8189. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8190. TEST(ServerStopTest, Decommision) {
  8191. Server svr;
  8192. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  8193. for (int i = 0; i < 4; i++) {
  8194. auto is_even = !(i % 2);
  8195. std::thread t{[&] {
  8196. try {
  8197. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8198. if (is_even) {
  8199. throw std::runtime_error("Some thing that happens to go wrong.");
  8200. }
  8201. svr.listen(HOST, PORT);
  8202. } catch (...) { svr.decommission(); }
  8203. }};
  8204. svr.wait_until_ready();
  8205. // Server is up
  8206. {
  8207. Client cli(HOST, PORT);
  8208. auto res = cli.Get("/hi");
  8209. if (is_even) {
  8210. EXPECT_FALSE(res);
  8211. } else {
  8212. EXPECT_TRUE(res);
  8213. EXPECT_EQ("hi...", res->body);
  8214. }
  8215. }
  8216. svr.stop();
  8217. t.join();
  8218. // Server is down...
  8219. {
  8220. Client cli(HOST, PORT);
  8221. auto res = cli.Get("/hi");
  8222. EXPECT_FALSE(res);
  8223. }
  8224. }
  8225. }
  8226. #endif
  8227. // Helper function for string body upload progress tests
  8228. template <typename SetupHandler, typename ClientCall>
  8229. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  8230. ClientCall &&client_call,
  8231. const string &body) {
  8232. Server svr;
  8233. setup_handler(svr);
  8234. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8235. auto se = detail::scope_exit([&] {
  8236. svr.stop();
  8237. t.join();
  8238. });
  8239. svr.wait_until_ready();
  8240. Client cli(HOST, PORT);
  8241. vector<uint64_t> progress_values;
  8242. bool progress_called = false;
  8243. auto res =
  8244. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8245. progress_values.push_back(current);
  8246. progress_called = true;
  8247. return true;
  8248. });
  8249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8250. EXPECT_EQ(200, res->status);
  8251. EXPECT_TRUE(progress_called);
  8252. }
  8253. TEST(UploadProgressTest, PostStringBodyBasic) {
  8254. TestStringBodyUploadProgress(
  8255. [](Server &svr) {
  8256. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8257. res.set_content("received", "text/plain");
  8258. });
  8259. },
  8260. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8261. return cli.Post("/test", body, "text/plain", progress_callback);
  8262. },
  8263. "test data for upload progress");
  8264. }
  8265. TEST(UploadProgressTest, PutStringBodyBasic) {
  8266. TestStringBodyUploadProgress(
  8267. [](Server &svr) {
  8268. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  8269. res.set_content("put received", "text/plain");
  8270. });
  8271. },
  8272. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8273. return cli.Put("/test", body, "text/plain", progress_callback);
  8274. },
  8275. "put test data for upload progress");
  8276. }
  8277. TEST(UploadProgressTest, PatchStringBodyBasic) {
  8278. TestStringBodyUploadProgress(
  8279. [](Server &svr) {
  8280. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  8281. res.set_content("patch received", "text/plain");
  8282. });
  8283. },
  8284. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8285. return cli.Patch("/test", body, "text/plain", progress_callback);
  8286. },
  8287. "patch test data for upload progress");
  8288. }
  8289. // Helper function for content provider upload progress tests
  8290. template <typename SetupHandler, typename ClientCall>
  8291. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  8292. ClientCall &&client_call) {
  8293. Server svr;
  8294. setup_handler(svr);
  8295. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8296. auto se = detail::scope_exit([&] {
  8297. svr.stop();
  8298. t.join();
  8299. });
  8300. svr.wait_until_ready();
  8301. Client cli(HOST, PORT);
  8302. vector<uint64_t> progress_values;
  8303. auto res =
  8304. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8305. progress_values.push_back(current);
  8306. return true;
  8307. });
  8308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8309. EXPECT_EQ(200, res->status);
  8310. EXPECT_FALSE(progress_values.empty());
  8311. }
  8312. TEST(UploadProgressTest, PostContentProviderProgress) {
  8313. TestContentProviderUploadProgress(
  8314. [](Server &svr) {
  8315. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8316. res.set_content("provider received", "text/plain");
  8317. });
  8318. },
  8319. [](Client &cli, UploadProgress progress_callback) {
  8320. return cli.Post(
  8321. "/test", 10,
  8322. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  8323. sink.os << "test data";
  8324. return true;
  8325. },
  8326. "text/plain", progress_callback);
  8327. });
  8328. }
  8329. // Helper function for multipart upload progress tests
  8330. template <typename SetupHandler, typename ClientCall>
  8331. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  8332. ClientCall &&client_call,
  8333. const string &endpoint) {
  8334. Server svr;
  8335. setup_handler(svr);
  8336. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8337. auto se = detail::scope_exit([&] {
  8338. svr.stop();
  8339. t.join();
  8340. });
  8341. svr.wait_until_ready();
  8342. Client cli(HOST, PORT);
  8343. vector<uint64_t> progress_values;
  8344. UploadFormDataItems items = {
  8345. {"field1", "value1", "", ""},
  8346. {"field2", "longer value for progress tracking test", "", ""},
  8347. {"file1", "file content data for upload progress", "test.txt",
  8348. "text/plain"}};
  8349. auto res = client_call(cli, endpoint, items,
  8350. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8351. progress_values.push_back(current);
  8352. return true;
  8353. });
  8354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8355. EXPECT_EQ(200, res->status);
  8356. EXPECT_FALSE(progress_values.empty());
  8357. }
  8358. TEST(UploadProgressTest, PostMultipartProgress) {
  8359. TestMultipartUploadProgress(
  8360. [](Server &svr) {
  8361. svr.Post("/multipart", [](const Request &req, Response &res) {
  8362. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  8363. res.set_content("multipart received", "text/plain");
  8364. });
  8365. },
  8366. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  8367. UploadProgress progress_callback) {
  8368. return cli.Post(endpoint, items, progress_callback);
  8369. },
  8370. "/multipart");
  8371. }
  8372. // Helper function for basic download progress tests
  8373. template <typename SetupHandler, typename ClientCall>
  8374. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8375. ClientCall &&client_call, const string &endpoint,
  8376. size_t expected_content_size) {
  8377. Server svr;
  8378. setup_handler(svr);
  8379. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8380. auto se = detail::scope_exit([&] {
  8381. svr.stop();
  8382. t.join();
  8383. });
  8384. svr.wait_until_ready();
  8385. Client cli(HOST, PORT);
  8386. vector<uint64_t> progress_values;
  8387. auto res = client_call(cli, endpoint,
  8388. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8389. progress_values.push_back(current);
  8390. return true;
  8391. });
  8392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8393. EXPECT_EQ(200, res->status);
  8394. EXPECT_FALSE(progress_values.empty());
  8395. EXPECT_EQ(expected_content_size, res->body.size());
  8396. }
  8397. TEST(DownloadProgressTest, GetBasic) {
  8398. TestBasicDownloadProgress(
  8399. [](Server &svr) {
  8400. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8401. string content(1000, 'D');
  8402. res.set_content(content, "text/plain");
  8403. });
  8404. },
  8405. [](Client &cli, const string &endpoint,
  8406. DownloadProgress progress_callback) {
  8407. return cli.Get(endpoint, progress_callback);
  8408. },
  8409. "/download", 1000u);
  8410. }
  8411. // Helper function for content receiver download progress tests
  8412. template <typename SetupHandler, typename ClientCall>
  8413. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8414. ClientCall &&client_call,
  8415. const string &endpoint,
  8416. size_t expected_content_size) {
  8417. Server svr;
  8418. setup_handler(svr);
  8419. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8420. auto se = detail::scope_exit([&] {
  8421. svr.stop();
  8422. t.join();
  8423. });
  8424. svr.wait_until_ready();
  8425. Client cli(HOST, PORT);
  8426. vector<uint64_t> progress_values;
  8427. string received_body;
  8428. auto res = client_call(
  8429. cli, endpoint,
  8430. [&](const char *data, size_t data_length) -> bool {
  8431. received_body.append(data, data_length);
  8432. return true;
  8433. },
  8434. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8435. progress_values.push_back(current);
  8436. return true;
  8437. });
  8438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8439. EXPECT_EQ(200, res->status);
  8440. EXPECT_FALSE(progress_values.empty());
  8441. EXPECT_EQ(expected_content_size, received_body.size());
  8442. EXPECT_TRUE(res->body.empty());
  8443. }
  8444. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8445. TestContentReceiverDownloadProgress(
  8446. [](Server &svr) {
  8447. svr.Get("/download-receiver",
  8448. [](const Request & /*req*/, Response &res) {
  8449. string content(2000, 'R');
  8450. res.set_content(content, "text/plain");
  8451. });
  8452. },
  8453. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8454. DownloadProgress progress_callback) {
  8455. return cli.Get(endpoint, content_receiver, progress_callback);
  8456. },
  8457. "/download-receiver", 2000u);
  8458. }
  8459. TEST(StreamingTest, NoContentLengthStreaming) {
  8460. Server svr;
  8461. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8462. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8463. if (offset < 6) {
  8464. sink.os << (offset < 3 ? "a" : "b");
  8465. } else {
  8466. sink.done();
  8467. }
  8468. return true;
  8469. });
  8470. });
  8471. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8472. auto listen_se = detail::scope_exit([&] {
  8473. svr.stop();
  8474. listen_thread.join();
  8475. ASSERT_FALSE(svr.is_running());
  8476. });
  8477. svr.wait_until_ready();
  8478. Client client(HOST, PORT);
  8479. auto get_thread = std::thread([&client]() {
  8480. std::string s;
  8481. auto res =
  8482. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8483. s += std::string(data, len);
  8484. return true;
  8485. });
  8486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8487. EXPECT_EQ(StatusCode::OK_200, res->status);
  8488. EXPECT_EQ("aaabbb", s);
  8489. });
  8490. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8491. // Give GET time to get a few messages.
  8492. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8493. }
  8494. TEST(MountTest, Unmount) {
  8495. Server svr;
  8496. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8497. auto se = detail::scope_exit([&] {
  8498. svr.stop();
  8499. listen_thread.join();
  8500. ASSERT_FALSE(svr.is_running());
  8501. });
  8502. svr.wait_until_ready();
  8503. Client cli("localhost", PORT);
  8504. svr.set_mount_point("/mount2", "./www2");
  8505. auto res = cli.Get("/");
  8506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8507. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8508. res = cli.Get("/mount2/dir/test.html");
  8509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8510. EXPECT_EQ(StatusCode::OK_200, res->status);
  8511. svr.set_mount_point("/", "./www");
  8512. res = cli.Get("/dir/");
  8513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8514. EXPECT_EQ(StatusCode::OK_200, res->status);
  8515. svr.remove_mount_point("/");
  8516. res = cli.Get("/dir/");
  8517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8518. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8519. svr.remove_mount_point("/mount2");
  8520. res = cli.Get("/mount2/dir/test.html");
  8521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8522. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8523. }
  8524. TEST(MountTest, PathSegmentBoundary) {
  8525. Server svr;
  8526. svr.set_mount_point("/mount2", "./www2");
  8527. svr.set_mount_point("/", "./www");
  8528. auto port = svr.bind_to_any_port(HOST);
  8529. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8530. auto se = detail::scope_exit([&] {
  8531. svr.stop();
  8532. listen_thread.join();
  8533. ASSERT_FALSE(svr.is_running());
  8534. });
  8535. svr.wait_until_ready();
  8536. Client cli(HOST, port);
  8537. auto res = cli.Get("/mount2/dir/test.html");
  8538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8539. EXPECT_EQ(StatusCode::OK_200, res->status);
  8540. // "/mount2" must not match part-way through a path segment.
  8541. res = cli.Get("/mount2dir/test.html");
  8542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8543. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8544. // A mount point ending in '/' keeps matching every path below it.
  8545. res = cli.Get("/dir/test.html");
  8546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8547. EXPECT_EQ(StatusCode::OK_200, res->status);
  8548. }
  8549. TEST(MountTest, Redicect) {
  8550. Server svr;
  8551. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8552. auto se = detail::scope_exit([&] {
  8553. svr.stop();
  8554. listen_thread.join();
  8555. ASSERT_FALSE(svr.is_running());
  8556. });
  8557. svr.set_mount_point("/", "./www");
  8558. svr.wait_until_ready();
  8559. Client cli("localhost", PORT);
  8560. auto res = cli.Get("/dir/");
  8561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8562. EXPECT_EQ(StatusCode::OK_200, res->status);
  8563. res = cli.Get("/dir");
  8564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8565. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8566. res = cli.Get("/file");
  8567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8568. EXPECT_EQ(StatusCode::OK_200, res->status);
  8569. res = cli.Get("/file/");
  8570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8571. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8572. cli.set_follow_location(true);
  8573. res = cli.Get("/dir");
  8574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8575. EXPECT_EQ(StatusCode::OK_200, res->status);
  8576. }
  8577. TEST(MountTest, MultibytesPathName) {
  8578. Server svr;
  8579. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8580. auto se = detail::scope_exit([&] {
  8581. svr.stop();
  8582. listen_thread.join();
  8583. ASSERT_FALSE(svr.is_running());
  8584. });
  8585. svr.set_mount_point("/", "./www");
  8586. svr.wait_until_ready();
  8587. Client cli("localhost", PORT);
  8588. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8590. EXPECT_EQ(StatusCode::OK_200, res->status);
  8591. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8592. }
  8593. #ifdef _WIN32
  8594. // Issue #2435: mmap::open() must succeed even when another handle holds
  8595. // the file open for writing (e.g. an active log file).
  8596. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8597. const char *path = "mmap_concurrent_writer_test.txt";
  8598. const char *content = "hello";
  8599. {
  8600. std::ofstream f(path, std::ios::binary);
  8601. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8602. }
  8603. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8604. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8605. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8606. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8607. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8608. detail::mmap m(path);
  8609. ASSERT_TRUE(m.is_open());
  8610. EXPECT_EQ(strlen(content), m.size());
  8611. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8612. }
  8613. #endif
  8614. #ifndef _WIN32
  8615. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8616. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8617. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8618. TEST(MmapTest, FailedMappingIsNotOpen) {
  8619. const char *path = "./mmap_failed_mapping_test_dir";
  8620. ASSERT_EQ(0, ::mkdir(path, 0755));
  8621. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8622. detail::mmap m(path);
  8623. EXPECT_FALSE(m.is_open());
  8624. EXPECT_EQ(0U, m.size());
  8625. EXPECT_NE(static_cast<const void *>(m.data()),
  8626. static_cast<const void *>(MAP_FAILED));
  8627. }
  8628. #endif
  8629. TEST(KeepAliveTest, ReadTimeout) {
  8630. Server svr;
  8631. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8632. std::this_thread::sleep_for(std::chrono::seconds(2));
  8633. res.set_content("a", "text/plain");
  8634. });
  8635. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8636. res.set_content("b", "text/plain");
  8637. });
  8638. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8639. auto se = detail::scope_exit([&] {
  8640. svr.stop();
  8641. listen_thread.join();
  8642. ASSERT_FALSE(svr.is_running());
  8643. });
  8644. svr.wait_until_ready();
  8645. Client cli("localhost", PORT);
  8646. cli.set_keep_alive(true);
  8647. cli.set_read_timeout(std::chrono::seconds(1));
  8648. auto resa = cli.Get("/a");
  8649. ASSERT_FALSE(resa);
  8650. EXPECT_EQ(Error::Read, resa.error());
  8651. auto resb = cli.Get("/b");
  8652. ASSERT_TRUE(resb);
  8653. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8654. EXPECT_EQ("b", resb->body);
  8655. }
  8656. TEST(KeepAliveTest, MaxCount) {
  8657. size_t keep_alive_max_count = 3;
  8658. Server svr;
  8659. svr.set_keep_alive_max_count(keep_alive_max_count);
  8660. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8661. res.set_content("Hello World!", "text/plain");
  8662. });
  8663. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8664. auto se = detail::scope_exit([&] {
  8665. svr.stop();
  8666. listen_thread.join();
  8667. ASSERT_FALSE(svr.is_running());
  8668. });
  8669. svr.wait_until_ready();
  8670. Client cli(HOST, PORT);
  8671. cli.set_keep_alive(true);
  8672. for (size_t i = 0; i < 5; i++) {
  8673. auto result = cli.Get("/hi");
  8674. ASSERT_TRUE(result);
  8675. EXPECT_EQ(StatusCode::OK_200, result->status);
  8676. if (i == keep_alive_max_count - 1) {
  8677. EXPECT_EQ("close", result->get_header_value("Connection"));
  8678. } else {
  8679. EXPECT_FALSE(result->has_header("Connection"));
  8680. }
  8681. }
  8682. }
  8683. TEST(KeepAliveTest, Issue1041) {
  8684. Server svr;
  8685. svr.set_keep_alive_timeout(3);
  8686. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8687. res.set_content("Hello World!", "text/plain");
  8688. });
  8689. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8690. auto se = detail::scope_exit([&] {
  8691. svr.stop();
  8692. listen_thread.join();
  8693. ASSERT_FALSE(svr.is_running());
  8694. });
  8695. svr.wait_until_ready();
  8696. Client cli(HOST, PORT);
  8697. cli.set_keep_alive(true);
  8698. auto result = cli.Get("/hi");
  8699. ASSERT_TRUE(result);
  8700. EXPECT_EQ(StatusCode::OK_200, result->status);
  8701. std::this_thread::sleep_for(std::chrono::seconds(5));
  8702. result = cli.Get("/hi");
  8703. ASSERT_TRUE(result);
  8704. EXPECT_EQ(StatusCode::OK_200, result->status);
  8705. }
  8706. TEST(KeepAliveTest, Issue1959) {
  8707. Server svr;
  8708. svr.set_keep_alive_timeout(5);
  8709. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8710. res.set_content("a", "text/plain");
  8711. });
  8712. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8713. auto se = detail::scope_exit([&] {
  8714. if (!svr.is_running()) return;
  8715. svr.stop();
  8716. listen_thread.join();
  8717. ASSERT_FALSE(svr.is_running());
  8718. });
  8719. svr.wait_until_ready();
  8720. Client cli("localhost", PORT);
  8721. cli.set_keep_alive(true);
  8722. using namespace std::chrono;
  8723. auto start = steady_clock::now();
  8724. cli.Get("/a");
  8725. svr.stop();
  8726. listen_thread.join();
  8727. auto end = steady_clock::now();
  8728. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8729. EXPECT_LT(elapsed, 5000);
  8730. }
  8731. #ifdef CPPHTTPLIB_SSL_ENABLED
  8732. TEST(KeepAliveTest, SSLClientReconnection) {
  8733. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8734. ASSERT_TRUE(svr.is_valid());
  8735. svr.set_keep_alive_timeout(1);
  8736. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8737. res.set_content("Hello World!", "text/plain");
  8738. });
  8739. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8740. auto se = detail::scope_exit([&] {
  8741. svr.stop();
  8742. listen_thread.join();
  8743. ASSERT_FALSE(svr.is_running());
  8744. });
  8745. svr.wait_until_ready();
  8746. SSLClient cli(HOST, PORT);
  8747. cli.enable_server_certificate_verification(false);
  8748. cli.set_keep_alive(true);
  8749. auto result = cli.Get("/hi");
  8750. ASSERT_TRUE(result);
  8751. EXPECT_EQ(StatusCode::OK_200, result->status);
  8752. result = cli.Get("/hi");
  8753. ASSERT_TRUE(result);
  8754. EXPECT_EQ(StatusCode::OK_200, result->status);
  8755. std::this_thread::sleep_for(std::chrono::seconds(2));
  8756. // Recoonect
  8757. result = cli.Get("/hi");
  8758. ASSERT_TRUE(result);
  8759. EXPECT_EQ(StatusCode::OK_200, result->status);
  8760. result = cli.Get("/hi");
  8761. ASSERT_TRUE(result);
  8762. EXPECT_EQ(StatusCode::OK_200, result->status);
  8763. }
  8764. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8765. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8766. ASSERT_TRUE(svr.is_valid());
  8767. svr.set_keep_alive_timeout(1);
  8768. std::string content = "reconnect";
  8769. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8770. res.set_content("Hello World!", "text/plain");
  8771. });
  8772. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8773. auto se = detail::scope_exit([&] {
  8774. svr.stop();
  8775. listen_thread.join();
  8776. ASSERT_FALSE(svr.is_running());
  8777. });
  8778. svr.wait_until_ready();
  8779. SSLClient cli(HOST, PORT);
  8780. cli.enable_server_certificate_verification(false);
  8781. cli.set_keep_alive(true);
  8782. auto result = cli.Post(
  8783. "/hi", content.size(),
  8784. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8785. sink.write(content.c_str(), content.size());
  8786. return true;
  8787. },
  8788. "text/plain");
  8789. ASSERT_TRUE(result);
  8790. EXPECT_EQ(200, result->status);
  8791. std::this_thread::sleep_for(std::chrono::seconds(2));
  8792. // Recoonect
  8793. result = cli.Post(
  8794. "/hi", content.size(),
  8795. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8796. sink.write(content.c_str(), content.size());
  8797. return true;
  8798. },
  8799. "text/plain");
  8800. ASSERT_TRUE(result);
  8801. EXPECT_EQ(200, result->status);
  8802. result = cli.Post(
  8803. "/hi", content.size(),
  8804. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8805. sink.write(content.c_str(), content.size());
  8806. return true;
  8807. },
  8808. "text/plain");
  8809. ASSERT_TRUE(result);
  8810. EXPECT_EQ(200, result->status);
  8811. }
  8812. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8813. using namespace httplib::tls;
  8814. {
  8815. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8816. ASSERT_TRUE(svr.is_valid());
  8817. svr.Get("/sni", [&](const Request &req, Response &res) {
  8818. std::string expected = req.sni();
  8819. EXPECT_EQ(expected, req.get_param_value("expected"));
  8820. res.set_content("ok", "text/plain");
  8821. });
  8822. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8823. auto se = detail::scope_exit([&] {
  8824. svr.stop();
  8825. listen_thread.join();
  8826. ASSERT_FALSE(svr.is_running());
  8827. });
  8828. svr.wait_until_ready();
  8829. {
  8830. SSLClient cli("localhost", PORT);
  8831. cli.enable_server_certificate_verification(false);
  8832. auto res = cli.Get("/sni?expected=localhost");
  8833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8834. }
  8835. {
  8836. SSLClient cli("::1", PORT);
  8837. cli.enable_server_certificate_verification(false);
  8838. auto res = cli.Get("/sni?expected=");
  8839. // NOTE: This may fail if the server is listening on IPv4 only
  8840. // (e.g., when localhost resolves to 127.0.0.1 only)
  8841. if (res) {
  8842. EXPECT_EQ(StatusCode::OK_200, res->status);
  8843. } else {
  8844. EXPECT_EQ(Error::Connection, res.error());
  8845. }
  8846. }
  8847. }
  8848. }
  8849. #endif
  8850. TEST(ClientProblemDetectionTest, ContentProvider) {
  8851. Server svr;
  8852. size_t content_length = 1024 * 1024;
  8853. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8854. res.set_content_provider(
  8855. content_length, "text/plain",
  8856. [&](size_t offset, size_t length, DataSink &sink) {
  8857. auto out_len = std::min(length, static_cast<size_t>(1024));
  8858. std::string out(out_len, '@');
  8859. sink.write(out.data(), out_len);
  8860. return offset < 4096;
  8861. },
  8862. [](bool success) { ASSERT_FALSE(success); });
  8863. });
  8864. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8865. res.set_content_provider(
  8866. 0, "text/plain",
  8867. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8868. EXPECT_TRUE(false);
  8869. return true;
  8870. },
  8871. [](bool success) { ASSERT_FALSE(success); });
  8872. });
  8873. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8874. auto se = detail::scope_exit([&] {
  8875. svr.stop();
  8876. listen_thread.join();
  8877. ASSERT_FALSE(svr.is_running());
  8878. });
  8879. svr.wait_until_ready();
  8880. Client cli("localhost", PORT);
  8881. {
  8882. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8883. size_t /*data_length*/) { return false; });
  8884. ASSERT_FALSE(res);
  8885. }
  8886. {
  8887. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8888. size_t /*data_length*/) { return false; });
  8889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8890. }
  8891. }
  8892. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8893. Server svr;
  8894. svr.set_error_handler([](Request const &, Response &res) -> void {
  8895. res.set_chunked_content_provider(
  8896. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8897. sink.os << "hello";
  8898. sink.os << "world";
  8899. sink.done();
  8900. return true;
  8901. });
  8902. });
  8903. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8904. auto se = detail::scope_exit([&] {
  8905. svr.stop();
  8906. listen_thread.join();
  8907. ASSERT_FALSE(svr.is_running());
  8908. });
  8909. svr.wait_until_ready();
  8910. Client cli("localhost", PORT);
  8911. auto res = cli.Get("/");
  8912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8913. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8914. EXPECT_EQ("helloworld", res->body);
  8915. }
  8916. TEST(LongPollingTest, ClientCloseDetection) {
  8917. Server svr;
  8918. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8919. res.set_chunked_content_provider(
  8920. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8921. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8922. sink.os << "hello";
  8923. auto count = 10;
  8924. while (count > 0 && sink.is_writable()) {
  8925. this_thread::sleep_for(chrono::milliseconds(10));
  8926. count--;
  8927. }
  8928. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8929. return true;
  8930. });
  8931. });
  8932. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8933. auto se = detail::scope_exit([&] {
  8934. svr.stop();
  8935. listen_thread.join();
  8936. ASSERT_FALSE(svr.is_running());
  8937. });
  8938. svr.wait_until_ready();
  8939. Client cli("localhost", PORT);
  8940. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8941. EXPECT_EQ("hello", string(data, data_length));
  8942. return false; // close the socket immediately.
  8943. });
  8944. ASSERT_FALSE(res);
  8945. }
  8946. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8947. Server svr;
  8948. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8949. res.set_chunked_content_provider(
  8950. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8951. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8952. sink.os << "hello";
  8953. EXPECT_TRUE(sink.os.good());
  8954. // Wait for the client to close the connection
  8955. auto count = 10;
  8956. while (count > 0 && sink.is_writable()) {
  8957. this_thread::sleep_for(chrono::milliseconds(10));
  8958. count--;
  8959. }
  8960. // After client disconnect, write repeatedly until the socket
  8961. // write actually fails (small writes may be absorbed by the
  8962. // kernel buffer)
  8963. std::string chunk(1024, 'x');
  8964. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8965. sink.os << chunk;
  8966. }
  8967. EXPECT_TRUE(sink.os.fail());
  8968. return true;
  8969. });
  8970. });
  8971. auto port = svr.bind_to_any_port("localhost");
  8972. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8973. auto se = detail::scope_exit([&] {
  8974. svr.stop();
  8975. listen_thread.join();
  8976. ASSERT_FALSE(svr.is_running());
  8977. });
  8978. svr.wait_until_ready();
  8979. Client cli("localhost", port);
  8980. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8981. EXPECT_EQ("hello", string(data, data_length));
  8982. return false; // close the socket immediately.
  8983. });
  8984. ASSERT_FALSE(res);
  8985. }
  8986. TEST(GetWithParametersTest, GetWithParameters) {
  8987. Server svr;
  8988. svr.Get("/", [&](const Request &req, Response &) {
  8989. EXPECT_EQ("world", req.get_param_value("hello"));
  8990. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8991. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8992. });
  8993. svr.Get("/params", [&](const Request &req, Response &) {
  8994. EXPECT_EQ("world", req.get_param_value("hello"));
  8995. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8996. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8997. });
  8998. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8999. EXPECT_EQ("resource-id", req.matches[1]);
  9000. EXPECT_EQ("foo", req.get_param_value("param1"));
  9001. EXPECT_EQ("bar", req.get_param_value("param2"));
  9002. });
  9003. svr.Get("/users/:id", [&](const Request &req, Response &) {
  9004. EXPECT_EQ("user-id", req.path_params.at("id"));
  9005. EXPECT_EQ("foo", req.get_param_value("param1"));
  9006. EXPECT_EQ("bar", req.get_param_value("param2"));
  9007. });
  9008. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9009. auto se = detail::scope_exit([&] {
  9010. svr.stop();
  9011. listen_thread.join();
  9012. ASSERT_FALSE(svr.is_running());
  9013. });
  9014. svr.wait_until_ready();
  9015. {
  9016. Client cli(HOST, PORT);
  9017. Params params;
  9018. params.emplace("hello", "world");
  9019. params.emplace("hello2", "world2");
  9020. params.emplace("hello3", "world3");
  9021. auto res = cli.Get("/", params, Headers{});
  9022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9023. EXPECT_EQ(StatusCode::OK_200, res->status);
  9024. }
  9025. {
  9026. Client cli(HOST, PORT);
  9027. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  9028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9029. EXPECT_EQ(StatusCode::OK_200, res->status);
  9030. }
  9031. {
  9032. Client cli(HOST, PORT);
  9033. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  9034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9035. EXPECT_EQ(StatusCode::OK_200, res->status);
  9036. }
  9037. {
  9038. Client cli(HOST, PORT);
  9039. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  9040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9041. EXPECT_EQ(StatusCode::OK_200, res->status);
  9042. }
  9043. }
  9044. TEST(GetWithParametersTest, GetWithParameters2) {
  9045. Server svr;
  9046. svr.Get("/", [&](const Request &req, Response &res) {
  9047. auto text = req.get_param_value("hello");
  9048. res.set_content(text, "text/plain");
  9049. });
  9050. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9051. auto se = detail::scope_exit([&] {
  9052. svr.stop();
  9053. listen_thread.join();
  9054. ASSERT_FALSE(svr.is_running());
  9055. });
  9056. svr.wait_until_ready();
  9057. Client cli("localhost", PORT);
  9058. Params params;
  9059. params.emplace("hello", "world");
  9060. std::string body;
  9061. auto res = cli.Get("/", params, Headers{},
  9062. [&](const char *data, size_t data_length) {
  9063. body.append(data, data_length);
  9064. return true;
  9065. });
  9066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9067. EXPECT_EQ(StatusCode::OK_200, res->status);
  9068. EXPECT_EQ("world", body);
  9069. }
  9070. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  9071. Server svr;
  9072. svr.Get("/search", [&](const Request &req, Response &res) {
  9073. auto q = req.get_param_value("q");
  9074. res.set_content(q, "text/plain");
  9075. });
  9076. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9077. auto se = detail::scope_exit([&] {
  9078. svr.stop();
  9079. listen_thread.join();
  9080. ASSERT_FALSE(svr.is_running());
  9081. });
  9082. svr.wait_until_ready();
  9083. Client cli("localhost", PORT);
  9084. // Verify that Get(path, params) works without requiring Headers argument
  9085. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  9086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9087. EXPECT_EQ(StatusCode::OK_200, res->status);
  9088. EXPECT_EQ("cpp-httplib", res->body);
  9089. }
  9090. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  9091. auto host = "httpbingo.org";
  9092. auto path = std::string{"/range/32"};
  9093. #ifdef CPPHTTPLIB_SSL_ENABLED
  9094. SSLClient cli(host);
  9095. #else
  9096. Client cli(host);
  9097. #endif
  9098. cli.set_default_headers({make_range_header({{1, 10}})});
  9099. cli.set_connection_timeout(5);
  9100. {
  9101. auto res = cli.Get(path);
  9102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9103. EXPECT_EQ("bcdefghijk", res->body);
  9104. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9105. }
  9106. {
  9107. auto res = cli.Get(path);
  9108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9109. EXPECT_EQ("bcdefghijk", res->body);
  9110. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9111. }
  9112. }
  9113. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  9114. Server svr;
  9115. svr.set_default_headers({{"Hello", "World"}});
  9116. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9117. res.set_content("ok", "text/plain");
  9118. });
  9119. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9120. auto se = detail::scope_exit([&] {
  9121. svr.stop();
  9122. listen_thread.join();
  9123. ASSERT_FALSE(svr.is_running());
  9124. });
  9125. svr.wait_until_ready();
  9126. Client cli("localhost", PORT);
  9127. auto res = cli.Get("/");
  9128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9129. EXPECT_EQ(StatusCode::OK_200, res->status);
  9130. EXPECT_EQ("ok", res->body);
  9131. EXPECT_EQ("World", res->get_header_value("Hello"));
  9132. }
  9133. #ifdef CPPHTTPLIB_SSL_ENABLED
  9134. TEST(KeepAliveTest, ReadTimeoutSSL) {
  9135. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9136. ASSERT_TRUE(svr.is_valid());
  9137. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9138. std::this_thread::sleep_for(std::chrono::seconds(2));
  9139. res.set_content("a", "text/plain");
  9140. });
  9141. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9142. res.set_content("b", "text/plain");
  9143. });
  9144. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9145. auto se = detail::scope_exit([&] {
  9146. svr.stop();
  9147. listen_thread.join();
  9148. ASSERT_FALSE(svr.is_running());
  9149. });
  9150. svr.wait_until_ready();
  9151. SSLClient cli("localhost", PORT);
  9152. cli.enable_server_certificate_verification(false);
  9153. cli.set_keep_alive(true);
  9154. cli.set_read_timeout(std::chrono::seconds(1));
  9155. auto resa = cli.Get("/a");
  9156. ASSERT_TRUE(!resa);
  9157. EXPECT_EQ(Error::Read, resa.error());
  9158. auto resb = cli.Get("/b");
  9159. ASSERT_TRUE(resb);
  9160. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9161. EXPECT_EQ("b", resb->body);
  9162. }
  9163. #endif
  9164. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  9165. protected:
  9166. ServerTestWithAI_PASSIVE()
  9167. : cli_(HOST, PORT)
  9168. #ifdef CPPHTTPLIB_SSL_ENABLED
  9169. ,
  9170. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9171. #endif
  9172. {
  9173. #ifdef CPPHTTPLIB_SSL_ENABLED
  9174. cli_.enable_server_certificate_verification(false);
  9175. #endif
  9176. }
  9177. virtual void SetUp() {
  9178. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9179. res.set_content("Hello World!", "text/plain");
  9180. });
  9181. t_ = thread(
  9182. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  9183. svr_.wait_until_ready();
  9184. }
  9185. virtual void TearDown() {
  9186. svr_.stop();
  9187. t_.join();
  9188. }
  9189. #ifdef CPPHTTPLIB_SSL_ENABLED
  9190. SSLClient cli_;
  9191. SSLServer svr_;
  9192. #else
  9193. Client cli_;
  9194. Server svr_;
  9195. #endif
  9196. thread t_;
  9197. };
  9198. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  9199. auto res = cli_.Get("/hi");
  9200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9201. EXPECT_EQ(StatusCode::OK_200, res->status);
  9202. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9203. EXPECT_EQ("Hello World!", res->body);
  9204. }
  9205. class ServerUpDownTest : public ::testing::Test {
  9206. protected:
  9207. ServerUpDownTest() : cli_(HOST, PORT) {}
  9208. virtual void SetUp() {
  9209. t_ = thread([&]() {
  9210. svr_.bind_to_any_port(HOST);
  9211. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9212. ASSERT_TRUE(svr_.listen_after_bind());
  9213. });
  9214. svr_.wait_until_ready();
  9215. }
  9216. virtual void TearDown() {
  9217. svr_.stop();
  9218. t_.join();
  9219. }
  9220. Client cli_;
  9221. Server svr_;
  9222. thread t_;
  9223. };
  9224. TEST_F(ServerUpDownTest, QuickStartStop) {
  9225. // Should not crash, especially when run with
  9226. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  9227. }
  9228. class PayloadMaxLengthTest : public ::testing::Test {
  9229. protected:
  9230. PayloadMaxLengthTest()
  9231. : cli_(HOST, PORT)
  9232. #ifdef CPPHTTPLIB_SSL_ENABLED
  9233. ,
  9234. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9235. #endif
  9236. {
  9237. #ifdef CPPHTTPLIB_SSL_ENABLED
  9238. cli_.enable_server_certificate_verification(false);
  9239. #endif
  9240. }
  9241. virtual void SetUp() {
  9242. svr_.set_payload_max_length(8);
  9243. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9244. res.set_content("test", "text/plain");
  9245. });
  9246. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9247. svr_.wait_until_ready();
  9248. }
  9249. virtual void TearDown() {
  9250. svr_.stop();
  9251. t_.join();
  9252. }
  9253. #ifdef CPPHTTPLIB_SSL_ENABLED
  9254. SSLClient cli_;
  9255. SSLServer svr_;
  9256. #else
  9257. Client cli_;
  9258. Server svr_;
  9259. #endif
  9260. thread t_;
  9261. };
  9262. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  9263. auto res = cli_.Post("/test", "123456789", "text/plain");
  9264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9265. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9266. res = cli_.Post("/test", "12345678", "text/plain");
  9267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9268. EXPECT_EQ(StatusCode::OK_200, res->status);
  9269. }
  9270. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  9271. // Test chunked encoding with payload exceeding the 8-byte limit
  9272. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  9273. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  9274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9275. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9276. }
  9277. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  9278. // Test chunked encoding with payload within the 8-byte limit
  9279. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  9280. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  9281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9282. EXPECT_EQ(StatusCode::OK_200, res->status);
  9283. }
  9284. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  9285. // Test using send_request to send chunked data exceeding payload limit
  9286. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  9287. "Host: " +
  9288. std::string(HOST) + ":" + std::to_string(PORT) +
  9289. "\r\n"
  9290. "Transfer-Encoding: chunked\r\n"
  9291. "Connection: close\r\n"
  9292. "\r\n"
  9293. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  9294. "0123456789\r\n"
  9295. "0\r\n" // End chunk
  9296. "\r\n";
  9297. std::string response;
  9298. bool result = send_request(1, chunked_request, &response);
  9299. if (!result) {
  9300. // If send_request fails, it might be because the server closed the
  9301. // connection due to payload limit enforcement, which is acceptable
  9302. SUCCEED()
  9303. << "Server rejected oversized chunked request (connection closed)";
  9304. } else {
  9305. // If we got a response, check if it's an error response or connection was
  9306. // closed early Short response length indicates connection was closed due to
  9307. // payload limit
  9308. if (response.length() <= 10) {
  9309. SUCCEED() << "Server closed connection for oversized chunked request";
  9310. } else {
  9311. // Check for error status codes
  9312. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9313. response.find("Payload Too Large") != std::string::npos ||
  9314. response.find("400") != std::string::npos);
  9315. }
  9316. }
  9317. }
  9318. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  9319. // Test request without Content-Length header exceeding payload limit
  9320. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9321. "Host: " +
  9322. std::string(HOST) + ":" +
  9323. std::to_string(PORT) +
  9324. "\r\n"
  9325. "Connection: close\r\n"
  9326. "\r\n";
  9327. // Add payload exceeding the 8-byte limit
  9328. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  9329. request_without_content_length += large_payload;
  9330. std::string response;
  9331. bool result = send_request(1, request_without_content_length, &response);
  9332. if (!result) {
  9333. // If send_request fails, server likely closed connection due to payload
  9334. // limit
  9335. SUCCEED() << "Server rejected oversized request without Content-Length "
  9336. "(connection closed)";
  9337. } else {
  9338. // Check if server responded with error or closed connection early
  9339. if (response.length() <= 10) {
  9340. SUCCEED() << "Server closed connection for oversized request without "
  9341. "Content-Length";
  9342. } else {
  9343. // Check for error status codes
  9344. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9345. response.find("Payload Too Large") != std::string::npos ||
  9346. response.find("400") != std::string::npos);
  9347. }
  9348. }
  9349. }
  9350. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  9351. // Test request without Content-Length header within payload limit
  9352. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9353. "Host: " +
  9354. std::string(HOST) + ":" +
  9355. std::to_string(PORT) +
  9356. "\r\n"
  9357. "Connection: close\r\n"
  9358. "\r\n";
  9359. // Add payload within the 8-byte limit
  9360. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  9361. request_without_content_length += small_payload;
  9362. std::string response;
  9363. bool result = send_request(1, request_without_content_length, &response);
  9364. // For requests without Content-Length, the server may have different behavior
  9365. // The key is that it should not reject due to payload limit for small
  9366. // payloads
  9367. if (result) {
  9368. // Check for any HTTP response (success or error, but not connection closed)
  9369. if (response.length() > 10) {
  9370. SUCCEED()
  9371. << "Server processed request without Content-Length within limit";
  9372. } else {
  9373. // Short response might indicate connection closed, which is acceptable
  9374. SUCCEED() << "Server closed connection for request without "
  9375. "Content-Length (acceptable behavior)";
  9376. }
  9377. } else {
  9378. // Connection failure might be due to protocol requirements
  9379. SUCCEED() << "Connection issue with request without Content-Length "
  9380. "(environment-specific)";
  9381. }
  9382. }
  9383. class LargePayloadMaxLengthTest : public ::testing::Test {
  9384. protected:
  9385. LargePayloadMaxLengthTest()
  9386. : cli_(HOST, PORT)
  9387. #ifdef CPPHTTPLIB_SSL_ENABLED
  9388. ,
  9389. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9390. #endif
  9391. {
  9392. #ifdef CPPHTTPLIB_SSL_ENABLED
  9393. cli_.enable_server_certificate_verification(false);
  9394. #endif
  9395. }
  9396. virtual void SetUp() {
  9397. // Set 10MB payload limit
  9398. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9399. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9400. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9401. res.set_content("Large payload test", "text/plain");
  9402. });
  9403. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9404. svr_.wait_until_ready();
  9405. }
  9406. virtual void TearDown() {
  9407. svr_.stop();
  9408. t_.join();
  9409. }
  9410. #ifdef CPPHTTPLIB_SSL_ENABLED
  9411. SSLClient cli_;
  9412. SSLServer svr_;
  9413. #else
  9414. Client cli_;
  9415. Server svr_;
  9416. #endif
  9417. thread t_;
  9418. };
  9419. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9420. // Test chunked encoding with payload within 10MB limit
  9421. std::string medium_payload(5 * 1024 * 1024,
  9422. 'A'); // 5MB payload, within 10MB limit
  9423. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9425. EXPECT_EQ(StatusCode::OK_200, res->status);
  9426. }
  9427. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9428. // Test chunked encoding with payload exceeding 10MB limit
  9429. std::string large_payload(12 * 1024 * 1024,
  9430. 'B'); // 12MB payload, exceeds 10MB limit
  9431. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9432. // Server may either return 413 or close the connection
  9433. if (res) {
  9434. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9435. } else {
  9436. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9437. }
  9438. }
  9439. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9440. // Test request without Content-Length header within 10MB limit
  9441. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9442. "Host: " +
  9443. std::string(HOST) + ":" +
  9444. std::to_string(PORT) +
  9445. "\r\n"
  9446. "Connection: close\r\n"
  9447. "\r\n";
  9448. // Add 1MB payload (within 10MB limit)
  9449. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9450. request_without_content_length += medium_payload;
  9451. std::string response;
  9452. bool result = send_request(5, request_without_content_length, &response);
  9453. if (result) {
  9454. // Should get a proper HTTP response for payloads within limit
  9455. if (response.length() > 10) {
  9456. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9457. "10MB limit";
  9458. } else {
  9459. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9460. "Content-Length)";
  9461. }
  9462. } else {
  9463. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9464. }
  9465. }
  9466. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9467. // Test request without Content-Length header exceeding 10MB limit
  9468. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9469. "Host: " +
  9470. std::string(HOST) + ":" +
  9471. std::to_string(PORT) +
  9472. "\r\n"
  9473. "Connection: close\r\n"
  9474. "\r\n";
  9475. // Add 12MB payload (exceeds 10MB limit)
  9476. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9477. request_without_content_length += large_payload;
  9478. std::string response;
  9479. bool result = send_request(10, request_without_content_length, &response);
  9480. if (!result) {
  9481. // Server should close connection due to payload limit
  9482. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9483. "(connection closed)";
  9484. } else {
  9485. // Check for error response
  9486. if (response.length() <= 10) {
  9487. SUCCEED()
  9488. << "Server closed connection for 12MB request exceeding 10MB limit";
  9489. } else {
  9490. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9491. response.find("Payload Too Large") != std::string::npos ||
  9492. response.find("400") != std::string::npos);
  9493. }
  9494. }
  9495. }
  9496. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9497. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9498. // path.
  9499. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9500. Server svr;
  9501. const size_t LIMIT = 64 * 1024; // 64KB
  9502. svr.set_payload_max_length(LIMIT);
  9503. size_t total = 0;
  9504. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9505. const ContentReader &content_reader) {
  9506. content_reader([&](const char * /*data*/, size_t len) {
  9507. total += len;
  9508. return true;
  9509. });
  9510. res.status = 200;
  9511. res.set_content("stream_ok", "text/plain");
  9512. });
  9513. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9514. auto se = detail::scope_exit([&] {
  9515. svr.stop();
  9516. thread.join();
  9517. ASSERT_FALSE(svr.is_running());
  9518. });
  9519. svr.wait_until_ready();
  9520. // Prepare 256KB raw data and gzip-compress it
  9521. std::string raw(256 * 1024, 'A');
  9522. std::string gz;
  9523. {
  9524. z_stream zs{};
  9525. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9526. Z_DEFAULT_STRATEGY);
  9527. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9528. zs.avail_in = static_cast<uInt>(raw.size());
  9529. char outbuf[4096];
  9530. int ret;
  9531. do {
  9532. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9533. zs.avail_out = sizeof(outbuf);
  9534. ret = deflate(&zs, Z_FINISH);
  9535. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9536. } while (ret != Z_STREAM_END);
  9537. deflateEnd(&zs);
  9538. }
  9539. Client cli(HOST, PORT);
  9540. cli.set_connection_timeout(std::chrono::seconds(5));
  9541. Headers headers = {{"Content-Encoding", "gzip"}};
  9542. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9543. "application/octet-stream");
  9544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9545. // Server must reject oversized decompressed payloads with 413.
  9546. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9547. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9548. EXPECT_LE(total, LIMIT);
  9549. }
  9550. #ifndef CPPHTTPLIB_SSL_ENABLED
  9551. // For a request with neither Content-Length nor Transfer-Encoding, the
  9552. // non-SSL raw-socket fallback in read_content_core() used to hand the
  9553. // compressed wire bytes straight to the ContentReader without ever routing
  9554. // them through the decompressor, so payload_max_length_ only bounded the
  9555. // compressed size on the wire, not the decompressed size.
  9556. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  9557. Server svr;
  9558. const size_t LIMIT = 64 * 1024; // 64KB
  9559. svr.set_payload_max_length(LIMIT);
  9560. size_t total = 0;
  9561. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9562. const ContentReader &content_reader) {
  9563. content_reader([&](const char * /*data*/, size_t len) {
  9564. total += len;
  9565. return true;
  9566. });
  9567. res.status = 200;
  9568. res.set_content("stream_ok", "text/plain");
  9569. });
  9570. auto port = svr.bind_to_any_port(HOST);
  9571. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9572. auto se = detail::scope_exit([&] {
  9573. svr.stop();
  9574. thread.join();
  9575. ASSERT_FALSE(svr.is_running());
  9576. });
  9577. svr.wait_until_ready();
  9578. // Prepare 256KB raw data and gzip-compress it, same payload as the
  9579. // StreamingGzipDecompression test above.
  9580. std::string raw(256 * 1024, 'A');
  9581. std::string gz;
  9582. {
  9583. httplib::detail::gzip_compressor compressor;
  9584. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  9585. [&](const char *chunk, size_t len) {
  9586. gz.append(chunk, len);
  9587. return true;
  9588. });
  9589. ASSERT_TRUE(result);
  9590. }
  9591. // Send the gzip body over raw TCP with neither Content-Length nor
  9592. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  9593. // kicks in.
  9594. std::string req = "POST /stream HTTP/1.1\r\n"
  9595. "Host: " +
  9596. std::string(HOST) + ":" + std::to_string(port) +
  9597. "\r\n"
  9598. "Content-Encoding: gzip\r\n"
  9599. "Connection: close\r\n"
  9600. "\r\n" +
  9601. gz;
  9602. std::string response;
  9603. ASSERT_TRUE(send_request(5, req, &response, port));
  9604. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9605. EXPECT_LE(total, LIMIT);
  9606. }
  9607. #endif
  9608. #endif
  9609. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9610. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9611. // the payload must be passed through untouched instead of being rejected.
  9612. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9613. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9614. Server svr;
  9615. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9616. res.set_content(body, "image/jpeg");
  9617. res.set_header("Content-Encoding", "UTF-8");
  9618. });
  9619. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9620. res.set_content(body, "image/jpeg");
  9621. res.set_header("Content-Encoding", "identity");
  9622. });
  9623. svr.Post("/echo", [](const Request &req, Response &res) {
  9624. res.set_content(req.body, "image/jpeg");
  9625. });
  9626. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9627. auto se = detail::scope_exit([&] {
  9628. svr.stop();
  9629. t.join();
  9630. ASSERT_FALSE(svr.is_running());
  9631. });
  9632. svr.wait_until_ready();
  9633. Client cli(HOST, PORT);
  9634. {
  9635. auto res = cli.Get("/image");
  9636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9637. EXPECT_EQ(StatusCode::OK_200, res->status);
  9638. EXPECT_EQ(body, res->body);
  9639. }
  9640. {
  9641. auto res = cli.Get("/identity");
  9642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9643. EXPECT_EQ(StatusCode::OK_200, res->status);
  9644. EXPECT_EQ(body, res->body);
  9645. }
  9646. {
  9647. // The same applies to a request body reaching the server.
  9648. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9649. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9651. EXPECT_EQ(StatusCode::OK_200, res->status);
  9652. EXPECT_EQ(body, res->body);
  9653. }
  9654. }
  9655. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9656. // gzip-encoded response even when the build has no zlib support.
  9657. static const char GZIPPED_HELLO_WORLD[] = {
  9658. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9659. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9660. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9661. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9662. // A content coding is a whole token, not something the field value merely
  9663. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  9664. // as "fibre" look like Brotli, and turned a multi-coding value like
  9665. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  9666. // it was never meant to see.
  9667. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  9668. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9669. Server svr;
  9670. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  9671. res.set_content(body, "image/jpeg");
  9672. res.set_header("Content-Encoding", "fibre");
  9673. });
  9674. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  9675. res.set_content(body, "image/jpeg");
  9676. res.set_header("Content-Encoding", "gzip, br");
  9677. });
  9678. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  9679. res.set_content(body, "image/jpeg");
  9680. res.set_header("Content-Encoding", "x-zstd-ish");
  9681. });
  9682. auto port = svr.bind_to_any_port(HOST);
  9683. thread t = thread([&]() { svr.listen_after_bind(); });
  9684. auto se = detail::scope_exit([&] {
  9685. svr.stop();
  9686. t.join();
  9687. ASSERT_FALSE(svr.is_running());
  9688. });
  9689. svr.wait_until_ready();
  9690. Client cli(HOST, port);
  9691. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  9692. auto res = cli.Get(path);
  9693. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9694. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9695. // Not a coding we recognize, so the payload comes back untouched
  9696. EXPECT_EQ(body, res->body) << path;
  9697. }
  9698. }
  9699. // A content coding cpp-httplib recognizes but was not built with must be
  9700. // reported as such. Handing the still-compressed payload back to the caller
  9701. // would silently corrupt it.
  9702. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9703. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9704. Server svr;
  9705. // "image/jpeg" keeps the server from applying a content coding of its own,
  9706. // so the hand-crafted Content-Encoding below survives.
  9707. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9708. res.set_content(gzipped, "image/jpeg");
  9709. res.set_header("Content-Encoding", "gzip");
  9710. });
  9711. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9712. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9713. res.set_content(gzipped, "image/jpeg");
  9714. res.set_header("Content-Encoding", "GZIP");
  9715. });
  9716. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9717. auto se = detail::scope_exit([&] {
  9718. svr.stop();
  9719. t.join();
  9720. ASSERT_FALSE(svr.is_running());
  9721. });
  9722. svr.wait_until_ready();
  9723. Client cli(HOST, PORT);
  9724. {
  9725. auto res = cli.Get("/gzipped");
  9726. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9728. EXPECT_EQ("Hello World!", res->body);
  9729. #else
  9730. ASSERT_FALSE(res);
  9731. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9732. #endif
  9733. }
  9734. {
  9735. // open_stream() must behave the same way.
  9736. auto handle = cli.open_stream("GET", "/gzipped");
  9737. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9738. ASSERT_TRUE(handle.is_valid());
  9739. std::string received;
  9740. char buf[256];
  9741. ssize_t n;
  9742. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9743. received.append(buf, static_cast<size_t>(n));
  9744. }
  9745. EXPECT_EQ("Hello World!", received);
  9746. #else
  9747. EXPECT_FALSE(handle.is_valid());
  9748. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9749. #endif
  9750. }
  9751. {
  9752. // A differently-cased coding must not be mistaken for an unknown one, or
  9753. // the body would be handed back still compressed.
  9754. auto res = cli.Get("/gzipped-uppercase");
  9755. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9757. EXPECT_EQ("Hello World!", res->body);
  9758. #else
  9759. ASSERT_FALSE(res);
  9760. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9761. #endif
  9762. }
  9763. }
  9764. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  9765. // the same message as the comma-joined one, so both have to be read the same
  9766. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  9767. // single gzip coding, and a body the sender says was encoded twice was handed
  9768. // back after one pass, still compressed but presented as decoded.
  9769. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  9770. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9771. Server svr;
  9772. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  9773. res.set_content(body, "image/jpeg");
  9774. res.headers.emplace("Content-Encoding", "gzip");
  9775. res.headers.emplace("Content-Encoding", "gzip");
  9776. });
  9777. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  9778. res.set_content(body, "image/jpeg");
  9779. res.set_header("Content-Encoding", "gzip, gzip");
  9780. });
  9781. auto port = svr.bind_to_any_port(HOST);
  9782. thread t = thread([&]() { svr.listen_after_bind(); });
  9783. auto se = detail::scope_exit([&] {
  9784. svr.stop();
  9785. t.join();
  9786. ASSERT_FALSE(svr.is_running());
  9787. });
  9788. svr.wait_until_ready();
  9789. Client cli(HOST, port);
  9790. // Two codings is not something cpp-httplib decodes, so both representations
  9791. // take the pass-through path rather than one of them being gunzipped once.
  9792. for (const char *path : {"/split", "/joined"}) {
  9793. auto res = cli.Get(path);
  9794. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9795. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9796. EXPECT_EQ(body, res->body) << path;
  9797. }
  9798. }
  9799. // Regression test for DoS vulnerability: a malicious server sending a response
  9800. // without Content-Length header must not cause unbounded memory consumption on
  9801. // the client side. The client should stop reading after a reasonable limit,
  9802. // similar to the server-side set_payload_max_length protection.
  9803. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9804. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9805. #ifndef _WIN32
  9806. signal(SIGPIPE, SIG_IGN);
  9807. #endif
  9808. auto server_thread = std::thread([] {
  9809. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9810. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9811. default_socket_options(srv);
  9812. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9813. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9814. sockaddr_in addr{};
  9815. addr.sin_family = AF_INET;
  9816. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9817. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9818. int opt = 1;
  9819. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9820. #ifdef _WIN32
  9821. reinterpret_cast<const char *>(&opt),
  9822. #else
  9823. &opt,
  9824. #endif
  9825. sizeof(opt));
  9826. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9827. ::listen(srv, 1);
  9828. sockaddr_in cli_addr{};
  9829. socklen_t cli_len = sizeof(cli_addr);
  9830. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9831. if (cli != INVALID_SOCKET) {
  9832. char buf[4096];
  9833. ::recv(cli, buf, sizeof(buf), 0);
  9834. // Malicious response: no Content-Length, no chunked encoding
  9835. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9836. "Connection: close\r\n"
  9837. "\r\n";
  9838. ::send(cli,
  9839. #ifdef _WIN32
  9840. static_cast<const char *>(response_header.c_str()),
  9841. static_cast<int>(response_header.size()),
  9842. #else
  9843. response_header.c_str(), response_header.size(),
  9844. #endif
  9845. 0);
  9846. // Send 10MB of data
  9847. std::string chunk(64 * 1024, 'A');
  9848. size_t total_sent = 0;
  9849. while (total_sent < MALICIOUS_DATA_SIZE) {
  9850. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9851. auto sent = ::send(cli,
  9852. #ifdef _WIN32
  9853. static_cast<const char *>(chunk.c_str()),
  9854. static_cast<int>(to_send),
  9855. #else
  9856. chunk.c_str(), to_send,
  9857. #endif
  9858. 0);
  9859. if (sent <= 0) break;
  9860. total_sent += static_cast<size_t>(sent);
  9861. }
  9862. detail::close_socket(cli);
  9863. }
  9864. detail::close_socket(srv);
  9865. });
  9866. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9867. size_t total_read = 0;
  9868. {
  9869. Client cli("127.0.0.1", PORT + 2);
  9870. cli.set_read_timeout(5, 0);
  9871. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9872. auto stream = cli.open_stream("GET", "/malicious");
  9873. ASSERT_TRUE(stream.is_valid());
  9874. char buffer[64 * 1024];
  9875. ssize_t n;
  9876. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9877. total_read += static_cast<size_t>(n);
  9878. }
  9879. } // StreamHandle and Client destroyed here, closing the socket
  9880. server_thread.join();
  9881. // With set_payload_max_length, the client must stop reading before consuming
  9882. // all 10MB. The read loop should be cut off at or near the configured limit.
  9883. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9884. << "Client read " << total_read << " bytes, exceeding the configured "
  9885. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9886. }
  9887. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9888. // the entire response body without truncation.
  9889. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9890. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9891. #ifndef _WIN32
  9892. signal(SIGPIPE, SIG_IGN);
  9893. #endif
  9894. auto server_thread = std::thread([] {
  9895. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9896. default_socket_options(srv);
  9897. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9898. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9899. sockaddr_in addr{};
  9900. addr.sin_family = AF_INET;
  9901. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9902. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9903. int opt = 1;
  9904. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9905. #ifdef _WIN32
  9906. reinterpret_cast<const char *>(&opt),
  9907. #else
  9908. &opt,
  9909. #endif
  9910. sizeof(opt));
  9911. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9912. ::listen(srv, 1);
  9913. sockaddr_in cli_addr{};
  9914. socklen_t cli_len = sizeof(cli_addr);
  9915. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9916. if (cli != INVALID_SOCKET) {
  9917. char buf[4096];
  9918. ::recv(cli, buf, sizeof(buf), 0);
  9919. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9920. "Connection: close\r\n"
  9921. "\r\n";
  9922. ::send(cli,
  9923. #ifdef _WIN32
  9924. static_cast<const char *>(response_header.c_str()),
  9925. static_cast<int>(response_header.size()),
  9926. #else
  9927. response_header.c_str(), response_header.size(),
  9928. #endif
  9929. 0);
  9930. std::string chunk(64 * 1024, 'A');
  9931. size_t total_sent = 0;
  9932. while (total_sent < DATA_SIZE) {
  9933. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9934. auto sent = ::send(cli,
  9935. #ifdef _WIN32
  9936. static_cast<const char *>(chunk.c_str()),
  9937. static_cast<int>(to_send),
  9938. #else
  9939. chunk.c_str(), to_send,
  9940. #endif
  9941. 0);
  9942. if (sent <= 0) break;
  9943. total_sent += static_cast<size_t>(sent);
  9944. }
  9945. #ifdef _WIN32
  9946. ::shutdown(cli, SD_SEND);
  9947. #else
  9948. ::shutdown(cli, SHUT_WR);
  9949. #endif
  9950. // Drain until the client closes its end, ensuring all data is delivered
  9951. char drain[1024];
  9952. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9953. detail::close_socket(cli);
  9954. }
  9955. detail::close_socket(srv);
  9956. });
  9957. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9958. size_t total_read = 0;
  9959. {
  9960. Client cli("127.0.0.1", PORT + 2);
  9961. cli.set_read_timeout(5, 0);
  9962. cli.set_payload_max_length(0); // 0 means no limit
  9963. auto stream = cli.open_stream("GET", "/data");
  9964. ASSERT_TRUE(stream.is_valid());
  9965. char buffer[64 * 1024];
  9966. ssize_t n;
  9967. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9968. total_read += static_cast<size_t>(n);
  9969. }
  9970. }
  9971. server_thread.join();
  9972. EXPECT_EQ(total_read, DATA_SIZE)
  9973. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9974. << " bytes without truncation, but only read " << total_read << " bytes.";
  9975. }
  9976. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9977. // enormous Content-Length must not cause the client to pre-allocate a huge
  9978. // response body buffer. The reservation is capped at payload_max_length_, and
  9979. // the read itself fails when the body exceeds the limit.
  9980. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9981. #ifndef _WIN32
  9982. signal(SIGPIPE, SIG_IGN);
  9983. #endif
  9984. auto server_thread = std::thread([] {
  9985. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9986. default_socket_options(srv);
  9987. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9988. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9989. sockaddr_in addr{};
  9990. addr.sin_family = AF_INET;
  9991. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9992. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9993. int opt = 1;
  9994. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9995. #ifdef _WIN32
  9996. reinterpret_cast<const char *>(&opt),
  9997. #else
  9998. &opt,
  9999. #endif
  10000. sizeof(opt));
  10001. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10002. ::listen(srv, 1);
  10003. sockaddr_in cli_addr{};
  10004. socklen_t cli_len = sizeof(cli_addr);
  10005. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10006. if (cli != INVALID_SOCKET) {
  10007. char buf[4096];
  10008. ::recv(cli, buf, sizeof(buf), 0);
  10009. // Malicious response: claim a 20GB body but send only a tiny payload.
  10010. std::string response = "HTTP/1.1 200 OK\r\n"
  10011. "Content-Length: 20000000000\r\n"
  10012. "\r\n"
  10013. "abc";
  10014. ::send(cli,
  10015. #ifdef _WIN32
  10016. static_cast<const char *>(response.c_str()),
  10017. static_cast<int>(response.size()),
  10018. #else
  10019. response.c_str(), response.size(),
  10020. #endif
  10021. 0);
  10022. detail::close_socket(cli);
  10023. }
  10024. detail::close_socket(srv);
  10025. });
  10026. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10027. {
  10028. Client cli("127.0.0.1", PORT + 2);
  10029. cli.set_read_timeout(5, 0);
  10030. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  10031. // result in a 20GB pre-allocation. The Get() call is expected to fail
  10032. // (server claims more bytes than payload_max_length permits), but it must
  10033. // not exhaust memory before getting there.
  10034. auto res = cli.Get("/malicious");
  10035. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  10036. }
  10037. server_thread.join();
  10038. }
  10039. // Verify that content_receiver bypasses the default payload_max_length,
  10040. // allowing streaming downloads larger than 100MB without requiring an explicit
  10041. // set_payload_max_length call.
  10042. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  10043. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10044. #ifndef _WIN32
  10045. signal(SIGPIPE, SIG_IGN);
  10046. #endif
  10047. auto server_thread = std::thread([] {
  10048. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10049. default_socket_options(srv);
  10050. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10051. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10052. sockaddr_in addr{};
  10053. addr.sin_family = AF_INET;
  10054. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10055. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10056. int opt = 1;
  10057. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10058. #ifdef _WIN32
  10059. reinterpret_cast<const char *>(&opt),
  10060. #else
  10061. &opt,
  10062. #endif
  10063. sizeof(opt));
  10064. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10065. ::listen(srv, 1);
  10066. sockaddr_in cli_addr{};
  10067. socklen_t cli_len = sizeof(cli_addr);
  10068. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10069. if (cli != INVALID_SOCKET) {
  10070. char buf[4096];
  10071. ::recv(cli, buf, sizeof(buf), 0);
  10072. // Response with Content-Length larger than default 100MB limit
  10073. auto content_length = std::to_string(DATA_SIZE);
  10074. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10075. "Content-Length: " +
  10076. content_length +
  10077. "\r\n"
  10078. "Connection: close\r\n"
  10079. "\r\n";
  10080. ::send(cli,
  10081. #ifdef _WIN32
  10082. static_cast<const char *>(response_header.c_str()),
  10083. static_cast<int>(response_header.size()),
  10084. #else
  10085. response_header.c_str(), response_header.size(),
  10086. #endif
  10087. 0);
  10088. std::string chunk(64 * 1024, 'A');
  10089. size_t total_sent = 0;
  10090. while (total_sent < DATA_SIZE) {
  10091. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10092. auto sent = ::send(cli,
  10093. #ifdef _WIN32
  10094. static_cast<const char *>(chunk.c_str()),
  10095. static_cast<int>(to_send),
  10096. #else
  10097. chunk.c_str(), to_send,
  10098. #endif
  10099. 0);
  10100. if (sent <= 0) break;
  10101. total_sent += static_cast<size_t>(sent);
  10102. }
  10103. detail::close_socket(cli);
  10104. }
  10105. detail::close_socket(srv);
  10106. });
  10107. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10108. size_t total_received = 0;
  10109. {
  10110. Client cli("127.0.0.1", PORT + 2);
  10111. cli.set_read_timeout(10, 0);
  10112. // Do NOT call set_payload_max_length — use the default 100MB limit
  10113. auto res =
  10114. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10115. total_received += data_length;
  10116. return true;
  10117. });
  10118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10119. EXPECT_EQ(StatusCode::OK_200, res->status);
  10120. }
  10121. server_thread.join();
  10122. EXPECT_EQ(total_received, DATA_SIZE)
  10123. << "With content_receiver, the client should read all " << DATA_SIZE
  10124. << " bytes despite the default 100MB payload_max_length, but only read "
  10125. << total_received << " bytes.";
  10126. }
  10127. // Verify that an explicit set_payload_max_length smaller than the response is
  10128. // enforced even when a content_receiver is used.
  10129. TEST(ClientVulnerabilityTest,
  10130. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  10131. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10132. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  10133. #ifndef _WIN32
  10134. signal(SIGPIPE, SIG_IGN);
  10135. #endif
  10136. auto server_thread = std::thread([] {
  10137. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10138. default_socket_options(srv);
  10139. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10140. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10141. sockaddr_in addr{};
  10142. addr.sin_family = AF_INET;
  10143. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10144. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10145. int opt = 1;
  10146. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10147. #ifdef _WIN32
  10148. reinterpret_cast<const char *>(&opt),
  10149. #else
  10150. &opt,
  10151. #endif
  10152. sizeof(opt));
  10153. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10154. ::listen(srv, 1);
  10155. sockaddr_in cli_addr{};
  10156. socklen_t cli_len = sizeof(cli_addr);
  10157. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10158. if (cli != INVALID_SOCKET) {
  10159. char buf[4096];
  10160. ::recv(cli, buf, sizeof(buf), 0);
  10161. auto content_length = std::to_string(DATA_SIZE);
  10162. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10163. "Content-Length: " +
  10164. content_length +
  10165. "\r\n"
  10166. "Connection: close\r\n"
  10167. "\r\n";
  10168. ::send(cli,
  10169. #ifdef _WIN32
  10170. static_cast<const char *>(response_header.c_str()),
  10171. static_cast<int>(response_header.size()),
  10172. #else
  10173. response_header.c_str(), response_header.size(),
  10174. #endif
  10175. 0);
  10176. std::string chunk(64 * 1024, 'A');
  10177. size_t total_sent = 0;
  10178. while (total_sent < DATA_SIZE) {
  10179. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10180. auto sent = ::send(cli,
  10181. #ifdef _WIN32
  10182. static_cast<const char *>(chunk.c_str()),
  10183. static_cast<int>(to_send),
  10184. #else
  10185. chunk.c_str(), to_send,
  10186. #endif
  10187. 0);
  10188. if (sent <= 0) break;
  10189. total_sent += static_cast<size_t>(sent);
  10190. }
  10191. detail::close_socket(cli);
  10192. }
  10193. detail::close_socket(srv);
  10194. });
  10195. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10196. size_t total_received = 0;
  10197. {
  10198. Client cli("127.0.0.1", PORT + 2);
  10199. cli.set_read_timeout(10, 0);
  10200. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  10201. auto res =
  10202. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10203. total_received += data_length;
  10204. return true;
  10205. });
  10206. // Should fail because 200MB exceeds the explicit 150MB limit
  10207. EXPECT_FALSE(res);
  10208. }
  10209. server_thread.join();
  10210. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  10211. << "Client with content_receiver should respect the explicit "
  10212. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  10213. << total_received << " bytes.";
  10214. }
  10215. // Verify that an explicit set_payload_max_length larger than the response
  10216. // allows the content_receiver to read all data successfully.
  10217. TEST(ClientVulnerabilityTest,
  10218. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  10219. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10220. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  10221. #ifndef _WIN32
  10222. signal(SIGPIPE, SIG_IGN);
  10223. #endif
  10224. auto server_thread = std::thread([] {
  10225. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10226. default_socket_options(srv);
  10227. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10228. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10229. sockaddr_in addr{};
  10230. addr.sin_family = AF_INET;
  10231. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10232. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10233. int opt = 1;
  10234. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10235. #ifdef _WIN32
  10236. reinterpret_cast<const char *>(&opt),
  10237. #else
  10238. &opt,
  10239. #endif
  10240. sizeof(opt));
  10241. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10242. ::listen(srv, 1);
  10243. sockaddr_in cli_addr{};
  10244. socklen_t cli_len = sizeof(cli_addr);
  10245. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10246. if (cli != INVALID_SOCKET) {
  10247. char buf[4096];
  10248. ::recv(cli, buf, sizeof(buf), 0);
  10249. auto content_length = std::to_string(DATA_SIZE);
  10250. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10251. "Content-Length: " +
  10252. content_length +
  10253. "\r\n"
  10254. "Connection: close\r\n"
  10255. "\r\n";
  10256. ::send(cli,
  10257. #ifdef _WIN32
  10258. static_cast<const char *>(response_header.c_str()),
  10259. static_cast<int>(response_header.size()),
  10260. #else
  10261. response_header.c_str(), response_header.size(),
  10262. #endif
  10263. 0);
  10264. std::string chunk(64 * 1024, 'A');
  10265. size_t total_sent = 0;
  10266. while (total_sent < DATA_SIZE) {
  10267. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10268. auto sent = ::send(cli,
  10269. #ifdef _WIN32
  10270. static_cast<const char *>(chunk.c_str()),
  10271. static_cast<int>(to_send),
  10272. #else
  10273. chunk.c_str(), to_send,
  10274. #endif
  10275. 0);
  10276. if (sent <= 0) break;
  10277. total_sent += static_cast<size_t>(sent);
  10278. }
  10279. #ifdef _WIN32
  10280. ::shutdown(cli, SD_SEND);
  10281. #else
  10282. ::shutdown(cli, SHUT_WR);
  10283. #endif
  10284. char drain[1024];
  10285. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10286. detail::close_socket(cli);
  10287. }
  10288. detail::close_socket(srv);
  10289. });
  10290. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10291. size_t total_received = 0;
  10292. {
  10293. Client cli("127.0.0.1", PORT + 2);
  10294. cli.set_read_timeout(10, 0);
  10295. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  10296. auto res =
  10297. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10298. total_received += data_length;
  10299. return true;
  10300. });
  10301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10302. EXPECT_EQ(StatusCode::OK_200, res->status);
  10303. }
  10304. server_thread.join();
  10305. EXPECT_EQ(total_received, DATA_SIZE)
  10306. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  10307. << " bytes (larger than " << DATA_SIZE
  10308. << " bytes response), content_receiver should read all data, but only "
  10309. "read "
  10310. << total_received << " bytes.";
  10311. }
  10312. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  10313. // Regression test for "zip bomb" attack on the client side: a malicious server
  10314. // sends a small gzip-compressed response that decompresses to a huge payload.
  10315. // The client must enforce payload_max_length on the decompressed size.
  10316. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  10317. constexpr size_t DECOMPRESSED_SIZE =
  10318. 10 * 1024 * 1024; // 10MB after decompression
  10319. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10320. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  10321. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  10322. std::string compressed;
  10323. {
  10324. httplib::detail::gzip_compressor compressor;
  10325. bool ok =
  10326. compressor.compress(uncompressed.data(), uncompressed.size(),
  10327. /*last=*/true, [&](const char *buf, size_t len) {
  10328. compressed.append(buf, len);
  10329. return true;
  10330. });
  10331. ASSERT_TRUE(ok);
  10332. }
  10333. // Sanity: compressed data should be much smaller than the decompressed size
  10334. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  10335. #ifndef _WIN32
  10336. signal(SIGPIPE, SIG_IGN);
  10337. #endif
  10338. // Set up the listening socket in the main thread so the server is guaranteed
  10339. // to be ready before the client connects (eliminates race condition).
  10340. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10341. default_socket_options(srv);
  10342. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10343. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10344. sockaddr_in addr{};
  10345. addr.sin_family = AF_INET;
  10346. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  10347. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10348. int opt = 1;
  10349. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10350. #ifdef _WIN32
  10351. reinterpret_cast<const char *>(&opt),
  10352. #else
  10353. &opt,
  10354. #endif
  10355. sizeof(opt));
  10356. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  10357. ASSERT_EQ(0, ::listen(srv, 1));
  10358. auto server_thread = std::thread([&compressed, srv] {
  10359. sockaddr_in cli_addr{};
  10360. socklen_t cli_len = sizeof(cli_addr);
  10361. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10362. if (cli != INVALID_SOCKET) {
  10363. // Read the full HTTP request (until \r\n\r\n)
  10364. char buf[4096];
  10365. size_t total = 0;
  10366. while (total < sizeof(buf)) {
  10367. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  10368. if (n <= 0) break;
  10369. total += static_cast<size_t>(n);
  10370. // Check for end of headers
  10371. if (total >= 4) {
  10372. std::string req(buf, total);
  10373. if (req.find("\r\n\r\n") != std::string::npos) break;
  10374. }
  10375. }
  10376. // Malicious response: gzip-compressed body, no Content-Length
  10377. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10378. "Content-Encoding: gzip\r\n"
  10379. "Connection: close\r\n"
  10380. "\r\n";
  10381. ::send(cli,
  10382. #ifdef _WIN32
  10383. static_cast<const char *>(response_header.c_str()),
  10384. static_cast<int>(response_header.size()),
  10385. #else
  10386. response_header.c_str(), response_header.size(),
  10387. #endif
  10388. 0);
  10389. // Send the compressed payload (small on the wire, huge when decompressed)
  10390. size_t total_sent = 0;
  10391. while (total_sent < compressed.size()) {
  10392. auto to_send = std::min(compressed.size() - total_sent,
  10393. static_cast<size_t>(64 * 1024));
  10394. auto sent =
  10395. ::send(cli,
  10396. #ifdef _WIN32
  10397. static_cast<const char *>(compressed.c_str() + total_sent),
  10398. static_cast<int>(to_send),
  10399. #else
  10400. compressed.c_str() + total_sent, to_send,
  10401. #endif
  10402. 0);
  10403. if (sent <= 0) break;
  10404. total_sent += static_cast<size_t>(sent);
  10405. }
  10406. detail::close_socket(cli);
  10407. }
  10408. });
  10409. auto se = detail::scope_exit([&] {
  10410. detail::close_socket(srv);
  10411. server_thread.join();
  10412. });
  10413. size_t total_decompressed = 0;
  10414. {
  10415. Client cli("127.0.0.1", PORT + 3);
  10416. cli.set_read_timeout(5, 0);
  10417. cli.set_decompress(true);
  10418. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10419. auto stream = cli.open_stream("GET", "/zipbomb");
  10420. ASSERT_TRUE(stream.is_valid());
  10421. char buffer[64 * 1024];
  10422. ssize_t n;
  10423. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10424. total_decompressed += static_cast<size_t>(n);
  10425. }
  10426. }
  10427. // The decompressed size must be capped by payload_max_length. Without
  10428. // protection, the client would decompress the full 10MB from a tiny
  10429. // compressed payload, enabling a zip bomb DoS attack.
  10430. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  10431. << "Client decompressed " << total_decompressed
  10432. << " bytes from a gzip response. The decompressed size should be "
  10433. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  10434. }
  10435. #endif
  10436. TEST(HostAndPortPropertiesTest, NoSSL) {
  10437. httplib::Client cli("www.google.com", 1234);
  10438. ASSERT_EQ("www.google.com", cli.host());
  10439. ASSERT_EQ(1234, cli.port());
  10440. }
  10441. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10442. httplib::Client cli("www.google.com:1234");
  10443. ASSERT_EQ("www.google.com", cli.host());
  10444. ASSERT_EQ(1234, cli.port());
  10445. }
  10446. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10447. // Port number that overflows int — should not crash, client becomes invalid
  10448. httplib::Client cli("http://www.google.com:99999999999999999999");
  10449. ASSERT_FALSE(cli.is_valid());
  10450. }
  10451. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10452. // Port 99999 exceeds valid range (1-65535) — should not crash
  10453. httplib::Client cli("http://www.google.com:99999");
  10454. ASSERT_FALSE(cli.is_valid());
  10455. }
  10456. #ifdef CPPHTTPLIB_SSL_ENABLED
  10457. TEST(HostAndPortPropertiesTest, SSL) {
  10458. httplib::SSLClient cli("www.google.com");
  10459. ASSERT_EQ("www.google.com", cli.host());
  10460. ASSERT_EQ(443, cli.port());
  10461. }
  10462. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10463. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10464. std::string cert;
  10465. read_file(CA_CERT_FILE, cert);
  10466. httplib::SSLClient httplib_client("www.google.com");
  10467. // Load CA store first time
  10468. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10469. // Load CA store second time (update)
  10470. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10471. // Verify client is still valid and can make connections
  10472. httplib_client.enable_server_certificate_verification(true);
  10473. auto res = httplib_client.Get("/");
  10474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10475. // Google may return 200 or 301 depending on various factors
  10476. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10477. res->status == StatusCode::MovedPermanently_301);
  10478. }
  10479. TEST(SSLClientTest, ServerNameIndication_Online) {
  10480. auto host = "httpbingo.org";
  10481. auto path = std::string{"/get"};
  10482. SSLClient cli(host, 443);
  10483. auto res = cli.Get(path);
  10484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10485. ASSERT_EQ(StatusCode::OK_200, res->status);
  10486. }
  10487. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10488. // Use a site that will cause SSL verification failure due to self-signed cert
  10489. SSLClient cli("self-signed.badssl.com", 443);
  10490. cli.enable_server_certificate_verification(true);
  10491. auto res = cli.Get("/");
  10492. ASSERT_TRUE(!res);
  10493. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10494. // Verify backend error is captured for SSLServerVerification
  10495. // This occurs when certificate verification fails
  10496. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10497. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10498. EXPECT_NE(0UL, res.ssl_backend_error());
  10499. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10500. // For OpenSSL, ssl_error is 0 for verification errors
  10501. EXPECT_EQ(0, res.ssl_error());
  10502. #if !defined(_WIN32) || \
  10503. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10504. // On non-Windows or when Windows Schannel is disabled, the error comes
  10505. // from OpenSSL's verification
  10506. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10507. res.ssl_backend_error());
  10508. #endif
  10509. #endif
  10510. }
  10511. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10512. // Use a site where hostname doesn't match the certificate
  10513. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10514. SSLClient cli("wrong.host.badssl.com", 443);
  10515. cli.enable_server_certificate_verification(true);
  10516. cli.enable_server_hostname_verification(true);
  10517. auto res = cli.Get("/");
  10518. ASSERT_TRUE(!res);
  10519. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10520. // Verify backend error is captured for hostname verification failure
  10521. EXPECT_NE(0UL, res.ssl_backend_error());
  10522. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10523. // For OpenSSL, ssl_error is 0 for verification errors
  10524. EXPECT_EQ(0, res.ssl_error());
  10525. #if !defined(_WIN32) || \
  10526. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10527. // On non-Windows or when Windows Schannel is disabled, the error comes
  10528. // from OpenSSL's hostname verification
  10529. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10530. res.ssl_backend_error());
  10531. #endif
  10532. #endif
  10533. }
  10534. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10535. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10536. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10537. SSLClient cli("www.google.com", 443);
  10538. cli.enable_server_certificate_verification(true);
  10539. auto res = cli.Get("/");
  10540. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10541. }
  10542. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10543. SSLClient cli("www.google.com", 443);
  10544. cli.enable_server_certificate_verification(true);
  10545. cli.enable_windows_certificate_verification(false);
  10546. auto res = cli.Get("/");
  10547. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10548. }
  10549. #endif
  10550. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10551. Client cli("https://google.com");
  10552. auto res = cli.Get("/");
  10553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10554. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10555. }
  10556. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10557. SSLClient cli("google.com");
  10558. cli.set_ca_cert_path(CA_CERT_FILE);
  10559. auto res = cli.Get("/");
  10560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10561. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10562. }
  10563. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10564. SSLClient cli("google.com");
  10565. cli.enable_server_certificate_verification(true);
  10566. cli.set_ca_cert_path("hello");
  10567. auto res = cli.Get("/");
  10568. ASSERT_TRUE(!res);
  10569. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10570. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10571. // should be set
  10572. EXPECT_EQ(0, res.ssl_error());
  10573. // Verify backend error is captured for SSLLoadingCerts
  10574. // This error occurs when loading CA certificates fails
  10575. EXPECT_NE(0UL, res.ssl_backend_error());
  10576. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10577. // OpenSSL specific error codes:
  10578. // > openssl errstr 0x80000002
  10579. // error:80000002:system library::No such file or directory
  10580. // > openssl errstr 0xA000126
  10581. // error:0A000126:SSL routines::unexpected eof while reading
  10582. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10583. res.ssl_backend_error() == 0xA000126);
  10584. #endif
  10585. }
  10586. TEST(SSLClientTest, ServerCertificateVerification4) {
  10587. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10588. ASSERT_TRUE(svr.is_valid());
  10589. svr.Get("/test", [&](const Request &, Response &res) {
  10590. res.set_content("test", "text/plain");
  10591. svr.stop();
  10592. ASSERT_TRUE(true);
  10593. });
  10594. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10595. auto se = detail::scope_exit([&] {
  10596. t.join();
  10597. ASSERT_FALSE(svr.is_running());
  10598. });
  10599. svr.wait_until_ready();
  10600. SSLClient cli("127.0.0.1", PORT);
  10601. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10602. cli.enable_server_certificate_verification(true);
  10603. cli.set_connection_timeout(30);
  10604. auto res = cli.Get("/test");
  10605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10606. ASSERT_EQ(StatusCode::OK_200, res->status);
  10607. }
  10608. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10609. std::string cert;
  10610. read_file(CA_CERT_FILE, cert);
  10611. SSLClient cli("google.com");
  10612. cli.load_ca_cert_store(cert.data(), cert.size());
  10613. const auto res = cli.Get("/");
  10614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10615. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10616. }
  10617. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10618. // clang-format off
  10619. static constexpr char cert[] =
  10620. "GlobalSign Root CA\n"
  10621. "==================\n"
  10622. "-----BEGIN CERTIFICATE-----\n"
  10623. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10624. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10625. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10626. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10627. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10628. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10629. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10630. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10631. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10632. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10633. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10634. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10635. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10636. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10637. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10638. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10639. "-----END CERTIFICATE-----\n";
  10640. // clang-format on
  10641. SSLClient cli("google.com");
  10642. cli.load_ca_cert_store(cert, sizeof(cert));
  10643. const auto res = cli.Get("/");
  10644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10645. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10646. }
  10647. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10648. SSLClient cli("www.youtube.com");
  10649. cli.set_ca_cert_path(CA_CERT_FILE);
  10650. cli.enable_server_certificate_verification(true);
  10651. cli.set_follow_location(true);
  10652. auto res = cli.Get("/");
  10653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10654. ASSERT_EQ(StatusCode::OK_200, res->status);
  10655. }
  10656. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10657. SSLClient cli("wWw.YouTube.Com");
  10658. cli.set_ca_cert_path(CA_CERT_FILE);
  10659. cli.enable_server_certificate_verification(true);
  10660. cli.enable_server_hostname_verification(true);
  10661. cli.set_follow_location(true);
  10662. auto res = cli.Get("/");
  10663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10664. ASSERT_EQ(StatusCode::OK_200, res->status);
  10665. }
  10666. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10667. SSLClient cli("gOoGlE.COm");
  10668. cli.enable_server_certificate_verification(true);
  10669. cli.enable_server_hostname_verification(true);
  10670. cli.set_follow_location(true);
  10671. auto res = cli.Get("/");
  10672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10673. ASSERT_EQ(StatusCode::OK_200, res->status);
  10674. }
  10675. TEST(SSLClientTest, Issue2004_Online) {
  10676. Client client("https://google.com");
  10677. client.set_follow_location(true);
  10678. auto res = client.Get("/");
  10679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10680. ASSERT_EQ(StatusCode::OK_200, res->status);
  10681. auto body = res->body;
  10682. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10683. }
  10684. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10685. // Create SSLClient with invalid cert/key to make is_valid() return false
  10686. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10687. "nonexistent_key.pem");
  10688. // is_valid() should be false due to cert loading failure
  10689. ASSERT_FALSE(cli.is_valid());
  10690. auto res = cli.Get("/");
  10691. ASSERT_FALSE(res);
  10692. EXPECT_EQ(Error::SSLConnection, res.error());
  10693. }
  10694. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10695. // Test for Issue #2251: SSL error not properly reported when client cert
  10696. // and key paths are swapped or mismatched
  10697. // This simulates the scenario where user accidentally swaps the cert and key
  10698. // files
  10699. // Using client cert file as private key and vice versa (completely wrong)
  10700. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10701. // Should fail validation due to cert/key mismatch
  10702. ASSERT_FALSE(cli.is_valid());
  10703. // Attempt to make a request should fail with proper error
  10704. auto res = cli.Get("/");
  10705. ASSERT_FALSE(res);
  10706. EXPECT_EQ(Error::SSLConnection, res.error());
  10707. // SSL error should be recorded in the Result object (this is the key fix for
  10708. // Issue #2251)
  10709. auto backend_error = res.ssl_backend_error();
  10710. EXPECT_NE(0u, backend_error);
  10711. }
  10712. // Tests cert/key mismatch detection at the TLS context level
  10713. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10714. // Test that using mismatched cert/key causes connection failure.
  10715. // We verify this at the SSLClient level rather than through internal
  10716. // TLS API functions.
  10717. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10718. cli.enable_server_certificate_verification(false);
  10719. cli.set_connection_timeout(2);
  10720. // The mismatch should cause a connection or handshake error
  10721. auto res = cli.Get("/test");
  10722. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10723. // Either way, the request should fail
  10724. EXPECT_FALSE(res);
  10725. }
  10726. #endif
  10727. #if 0
  10728. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10729. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10730. ASSERT_TRUE(cli != nullptr);
  10731. cli->set_address_family(AF_INET6);
  10732. cli->set_interface("en0");
  10733. auto res = cli->Get("/get");
  10734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10735. ASSERT_EQ(StatusCode::OK_200, res->status);
  10736. }
  10737. #endif
  10738. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10739. #ifdef CPPHTTPLIB_SSL_ENABLED
  10740. void ClientCertPresent(
  10741. const std::string &client_cert_file,
  10742. const std::string &client_private_key_file,
  10743. const std::string &client_encrypted_private_key_pass = std::string()) {
  10744. using namespace httplib::tls;
  10745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10746. CLIENT_CA_CERT_DIR);
  10747. ASSERT_TRUE(svr.is_valid());
  10748. svr.Get("/test", [&](const Request &req, Response &res) {
  10749. res.set_content("test", "text/plain");
  10750. auto cert = req.peer_cert();
  10751. ASSERT_TRUE(static_cast<bool>(cert));
  10752. std::string common_name = cert.subject_cn();
  10753. EXPECT_EQ("Common Name", common_name);
  10754. });
  10755. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10756. auto se = detail::scope_exit([&] {
  10757. svr.stop();
  10758. t.join();
  10759. ASSERT_FALSE(svr.is_running());
  10760. });
  10761. svr.wait_until_ready();
  10762. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10763. client_encrypted_private_key_pass);
  10764. cli.enable_server_certificate_verification(false);
  10765. cli.set_connection_timeout(30);
  10766. auto res = cli.Get("/test");
  10767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10768. ASSERT_EQ(StatusCode::OK_200, res->status);
  10769. }
  10770. TEST(SSLClientServerTest, ClientCertPresent) {
  10771. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10772. }
  10773. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10774. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10775. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10776. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10777. }
  10778. // PEM memory-based constructor tests (works with all TLS backends)
  10779. void PemMemoryClientCertPresent(
  10780. const std::string &client_cert_file,
  10781. const std::string &client_private_key_file,
  10782. const std::string &client_encrypted_private_key_pass = std::string()) {
  10783. // Read PEM files into memory
  10784. std::string server_cert_pem, server_key_pem;
  10785. std::string client_ca_pem;
  10786. std::string client_cert_pem, client_key_pem;
  10787. read_file(SERVER_CERT_FILE, server_cert_pem);
  10788. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10789. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10790. read_file(client_cert_file, client_cert_pem);
  10791. read_file(client_private_key_file, client_key_pem);
  10792. // Create server with PEM memory
  10793. SSLServer::PemMemory server_pem = {
  10794. server_cert_pem.c_str(),
  10795. server_cert_pem.size(),
  10796. server_key_pem.c_str(),
  10797. server_key_pem.size(),
  10798. client_ca_pem.c_str(),
  10799. client_ca_pem.size(),
  10800. nullptr // no password for server key
  10801. };
  10802. SSLServer svr(server_pem);
  10803. ASSERT_TRUE(svr.is_valid());
  10804. svr.Get("/test", [&](const Request &, Response &res) {
  10805. res.set_content("test", "text/plain");
  10806. });
  10807. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10808. auto se = detail::scope_exit([&] {
  10809. svr.stop();
  10810. t.join();
  10811. ASSERT_FALSE(svr.is_running());
  10812. });
  10813. svr.wait_until_ready();
  10814. // Create client with PEM memory
  10815. const char *password = client_encrypted_private_key_pass.empty()
  10816. ? nullptr
  10817. : client_encrypted_private_key_pass.c_str();
  10818. SSLClient::PemMemory client_pem = {
  10819. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10820. client_key_pem.size(), password};
  10821. SSLClient cli(HOST, PORT, client_pem);
  10822. cli.enable_server_certificate_verification(false);
  10823. cli.set_connection_timeout(30);
  10824. auto res = cli.Get("/test");
  10825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10826. ASSERT_EQ(StatusCode::OK_200, res->status);
  10827. }
  10828. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10829. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10830. }
  10831. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10832. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10833. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10834. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10835. }
  10836. TEST(SSLClientServerTest, ClientCertMissing) {
  10837. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10838. CLIENT_CA_CERT_DIR);
  10839. ASSERT_TRUE(svr.is_valid());
  10840. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10841. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10842. auto se = detail::scope_exit([&] {
  10843. svr.stop();
  10844. t.join();
  10845. ASSERT_FALSE(svr.is_running());
  10846. });
  10847. svr.wait_until_ready();
  10848. SSLClient cli(HOST, PORT);
  10849. cli.set_connection_timeout(30);
  10850. auto res = cli.Get("/test");
  10851. ASSERT_TRUE(!res);
  10852. // When client cert is missing and server requires it, connection fails
  10853. // Error type depends on backend implementation
  10854. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10855. res.error() == Error::SSLConnection);
  10856. // Verify backend error is captured
  10857. // Note: This test may have different error codes depending on the exact
  10858. // verification failure
  10859. EXPECT_NE(0UL, res.ssl_backend_error());
  10860. }
  10861. TEST(SSLClientServerTest, TrustDirOptional) {
  10862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10863. ASSERT_TRUE(svr.is_valid());
  10864. svr.Get("/test", [&](const Request &, Response &res) {
  10865. res.set_content("test", "text/plain");
  10866. });
  10867. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10868. auto se = detail::scope_exit([&] {
  10869. svr.stop();
  10870. t.join();
  10871. ASSERT_FALSE(svr.is_running());
  10872. });
  10873. svr.wait_until_ready();
  10874. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10875. cli.enable_server_certificate_verification(false);
  10876. cli.set_connection_timeout(30);
  10877. auto res = cli.Get("/test");
  10878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10879. ASSERT_EQ(StatusCode::OK_200, res->status);
  10880. }
  10881. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10882. class NoListenSSLServer : public SSLServer {
  10883. public:
  10884. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10885. const char *client_ca_cert_file_path,
  10886. const char *client_ca_cert_dir_path = nullptr)
  10887. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10888. client_ca_cert_dir_path),
  10889. stop_(false) {}
  10890. std::atomic_bool stop_;
  10891. private:
  10892. bool process_and_close_socket(socket_t /*sock*/) override {
  10893. // Don't create SSL context
  10894. while (!stop_.load()) {
  10895. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10896. }
  10897. return true;
  10898. }
  10899. };
  10900. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10901. CLIENT_CA_CERT_FILE);
  10902. ASSERT_TRUE(svr.is_valid());
  10903. svr.Get("/test", [&](const Request &, Response &res) {
  10904. res.set_content("test", "text/plain");
  10905. });
  10906. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10907. auto se = detail::scope_exit([&] {
  10908. svr.stop_ = true;
  10909. svr.stop();
  10910. t.join();
  10911. ASSERT_FALSE(svr.is_running());
  10912. });
  10913. svr.wait_until_ready();
  10914. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10915. cli.enable_server_certificate_verification(false);
  10916. cli.set_connection_timeout(1);
  10917. auto res = cli.Get("/test");
  10918. ASSERT_TRUE(!res);
  10919. EXPECT_EQ(Error::SSLConnection, res.error());
  10920. // Timeout results in WantRead error code (maps to backend-specific value)
  10921. EXPECT_NE(0, res.ssl_error());
  10922. }
  10923. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10924. // Test SSLServer with client certificate verification using the standard
  10925. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10926. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10927. CLIENT_CA_CERT_DIR);
  10928. ASSERT_TRUE(svr.is_valid());
  10929. svr.Get("/test", [&](const Request &req, Response &res) {
  10930. res.set_content("test", "text/plain");
  10931. auto cert = req.peer_cert();
  10932. ASSERT_TRUE(static_cast<bool>(cert));
  10933. auto common_name = cert.subject_cn();
  10934. EXPECT_EQ("Common Name", common_name);
  10935. });
  10936. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10937. auto se = detail::scope_exit([&] {
  10938. svr.stop();
  10939. t.join();
  10940. ASSERT_FALSE(svr.is_running());
  10941. });
  10942. svr.wait_until_ready();
  10943. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10944. cli.enable_server_certificate_verification(false);
  10945. cli.set_connection_timeout(30);
  10946. auto res = cli.Get("/test");
  10947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10948. ASSERT_EQ(StatusCode::OK_200, res->status);
  10949. }
  10950. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10951. // Verifies that wildcard matching and exact matching work consistently
  10952. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10953. using namespace httplib::tls;
  10954. // We need a running server to test against
  10955. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10956. ASSERT_TRUE(svr.is_valid());
  10957. svr.Get("/test", [](const Request &, Response &res) {
  10958. res.set_content("ok", "text/plain");
  10959. });
  10960. thread t([&]() { svr.listen(HOST, PORT); });
  10961. auto se = detail::scope_exit([&] {
  10962. svr.stop();
  10963. t.join();
  10964. });
  10965. svr.wait_until_ready();
  10966. bool verify_callback_called = false;
  10967. bool verify_result_wrong = false;
  10968. SSLClient cli(HOST, PORT);
  10969. cli.enable_server_certificate_verification(true);
  10970. cli.set_ca_cert_path(CA_CERT_FILE);
  10971. cli.set_connection_timeout(5);
  10972. // Note: Test certificate has CN="Common Name", not "localhost"
  10973. bool verify_result_cn = false;
  10974. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10975. verify_callback_called = true;
  10976. if (!ctx.cert) return false;
  10977. // Test 1: "Common Name" should match (our test server cert CN)
  10978. verify_result_cn = ctx.check_hostname("Common Name");
  10979. // Test 2: wrong hostname should not match
  10980. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10981. return true; // Accept for the purpose of this test
  10982. });
  10983. auto res = cli.Get("/test");
  10984. // The request may succeed or fail depending on cert configuration
  10985. // but the callback should have been called
  10986. ASSERT_TRUE(verify_callback_called)
  10987. << "Verify callback should have been called";
  10988. // CN="Common Name" should match our test certificate
  10989. //
  10990. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10991. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10992. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10993. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10994. // <openssl/base.h>, which is included transitively when
  10995. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10996. #if defined(OPENSSL_IS_BORINGSSL)
  10997. EXPECT_FALSE(verify_result_cn)
  10998. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10999. #else
  11000. EXPECT_TRUE(verify_result_cn)
  11001. << "verify_hostname should match 'Common Name' (certificate CN)";
  11002. #endif
  11003. // Wrong hostname should not match
  11004. EXPECT_FALSE(verify_result_wrong)
  11005. << "verify_hostname should not match 'wronghost.example.com'";
  11006. }
  11007. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  11008. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  11009. // X509_check_ip behavior and must hold for every backend.
  11010. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  11011. using namespace httplib::tls;
  11012. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  11013. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  11014. ASSERT_TRUE(svr.is_valid());
  11015. svr.Get("/test", [](const Request &, Response &res) {
  11016. res.set_content("ok", "text/plain");
  11017. });
  11018. thread t([&]() { svr.listen(HOST, PORT); });
  11019. auto se = detail::scope_exit([&] {
  11020. svr.stop();
  11021. t.join();
  11022. });
  11023. svr.wait_until_ready();
  11024. bool verify_callback_called = false;
  11025. bool ip_matched_via_cn = true;
  11026. SSLClient cli(HOST, PORT);
  11027. cli.enable_server_certificate_verification(true);
  11028. cli.set_ca_cert_path(CA_CERT_FILE);
  11029. cli.set_connection_timeout(5);
  11030. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11031. verify_callback_called = true;
  11032. if (!ctx.cert) return false;
  11033. // The IP appears only in the CN, so it must NOT be accepted.
  11034. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  11035. return true; // Accept for the purpose of this test
  11036. });
  11037. cli.Get("/test");
  11038. ASSERT_TRUE(verify_callback_called)
  11039. << "Verify callback should have been called";
  11040. EXPECT_FALSE(ip_matched_via_cn)
  11041. << "An IP host must not be authenticated via the certificate CN";
  11042. }
  11043. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  11044. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  11045. using namespace httplib::tls;
  11046. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  11047. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  11048. ASSERT_TRUE(svr.is_valid());
  11049. svr.Get("/test", [](const Request &, Response &res) {
  11050. res.set_content("ok", "text/plain");
  11051. });
  11052. thread t([&]() { svr.listen(HOST, PORT); });
  11053. auto se = detail::scope_exit([&] {
  11054. svr.stop();
  11055. t.join();
  11056. });
  11057. svr.wait_until_ready();
  11058. bool verify_callback_called = false;
  11059. bool san_matched = false;
  11060. bool wrong_ipv6_matched = true;
  11061. bool cn_ipv6_matched = true;
  11062. SSLClient cli(HOST, PORT);
  11063. cli.enable_server_certificate_verification(true);
  11064. cli.set_ca_cert_path(CA_CERT_FILE);
  11065. cli.set_connection_timeout(5);
  11066. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11067. verify_callback_called = true;
  11068. if (!ctx.cert) return false;
  11069. // Matches the IPv6 iPAddress SAN.
  11070. san_matched = ctx.check_hostname("2001:db8::1");
  11071. // A different IPv6 address must not match.
  11072. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  11073. // "::1" lives only in the CN, so it must not be accepted.
  11074. cn_ipv6_matched = ctx.check_hostname("::1");
  11075. return true; // Accept for the purpose of this test
  11076. });
  11077. cli.Get("/test");
  11078. ASSERT_TRUE(verify_callback_called)
  11079. << "Verify callback should have been called";
  11080. EXPECT_TRUE(san_matched)
  11081. << "verify_hostname should match an IPv6 iPAddress SAN";
  11082. EXPECT_FALSE(wrong_ipv6_matched)
  11083. << "verify_hostname should not match a non-matching IPv6 address";
  11084. EXPECT_FALSE(cn_ipv6_matched)
  11085. << "An IPv6 host must not be authenticated via the certificate CN";
  11086. }
  11087. #endif
  11088. // mbedTLS-specific callback constructor test
  11089. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  11090. #ifdef CPPHTTPLIB_SSL_ENABLED
  11091. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  11092. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11093. ASSERT_TRUE(svr.is_valid());
  11094. // Set up a handler to verify client certificate is present
  11095. bool client_cert_verified = false;
  11096. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11097. // Verify that client certificate was provided
  11098. client_cert_verified = true;
  11099. res.set_content("success", "text/plain");
  11100. });
  11101. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11102. auto se = detail::scope_exit([&] {
  11103. svr.stop();
  11104. t.join();
  11105. ASSERT_FALSE(svr.is_running());
  11106. });
  11107. svr.wait_until_ready();
  11108. // Client with certificate
  11109. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11110. cli.enable_server_certificate_verification(false);
  11111. cli.set_connection_timeout(30);
  11112. auto res = cli.Get("/test");
  11113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11114. ASSERT_EQ(StatusCode::OK_200, res->status);
  11115. ASSERT_TRUE(client_cert_verified);
  11116. EXPECT_EQ("success", res->body);
  11117. }
  11118. #endif
  11119. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  11120. // backends
  11121. #ifdef CPPHTTPLIB_SSL_ENABLED
  11122. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  11123. using namespace httplib::tls;
  11124. // Test that when client CA cert file is provided,
  11125. // the server properly requests and validates client certificates
  11126. // Create a server with client authentication
  11127. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11128. ASSERT_TRUE(svr.is_valid());
  11129. bool handler_called = false;
  11130. svr.Get("/test", [&](const Request &req, Response &res) {
  11131. handler_called = true;
  11132. // Verify that a client certificate was provided
  11133. auto cert = req.peer_cert();
  11134. ASSERT_TRUE(static_cast<bool>(cert));
  11135. // Get the issuer name
  11136. std::string issuer_str = cert.issuer_name();
  11137. ASSERT_FALSE(issuer_str.empty());
  11138. // The client certificate should be issued by our test CA
  11139. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  11140. res.set_content("authenticated", "text/plain");
  11141. });
  11142. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11143. auto se = detail::scope_exit([&] {
  11144. svr.stop();
  11145. t.join();
  11146. ASSERT_FALSE(svr.is_running());
  11147. });
  11148. svr.wait_until_ready();
  11149. // Connect with a client certificate issued by the CA
  11150. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11151. cli.enable_server_certificate_verification(false);
  11152. cli.set_connection_timeout(30);
  11153. auto res = cli.Get("/test");
  11154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11155. ASSERT_EQ(StatusCode::OK_200, res->status);
  11156. ASSERT_TRUE(handler_called);
  11157. EXPECT_EQ("authenticated", res->body);
  11158. }
  11159. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  11160. using namespace httplib::tls;
  11161. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11162. ASSERT_TRUE(svr.is_valid());
  11163. svr.Get("/test", [](const Request &, Response &res) {
  11164. res.set_content("ok", "text/plain");
  11165. });
  11166. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11167. auto se = detail::scope_exit([&] {
  11168. svr.stop();
  11169. t.join();
  11170. });
  11171. svr.wait_until_ready();
  11172. SSLClient cli(HOST, PORT);
  11173. cli.enable_server_certificate_verification(false);
  11174. cli.set_connection_timeout(30);
  11175. bool cert_checked = false;
  11176. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11177. if (ctx.cert) {
  11178. auto sans = ctx.sans();
  11179. // Test certificate may or may not have SANs - just verify the API
  11180. // works If SANs exist, verify the types are valid
  11181. for (const auto &san : sans) {
  11182. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  11183. san.type == SanType::EMAIL || san.type == SanType::URI ||
  11184. san.type == SanType::OTHER);
  11185. EXPECT_FALSE(san.value.empty());
  11186. }
  11187. cert_checked = true;
  11188. }
  11189. return true;
  11190. });
  11191. auto res = cli.Get("/test");
  11192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11193. EXPECT_TRUE(cert_checked);
  11194. }
  11195. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  11196. using namespace httplib::tls;
  11197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11198. ASSERT_TRUE(svr.is_valid());
  11199. svr.Get("/test", [](const Request &, Response &res) {
  11200. res.set_content("ok", "text/plain");
  11201. });
  11202. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11203. auto se = detail::scope_exit([&] {
  11204. svr.stop();
  11205. t.join();
  11206. });
  11207. svr.wait_until_ready();
  11208. SSLClient cli(HOST, PORT);
  11209. cli.enable_server_certificate_verification(false);
  11210. cli.set_connection_timeout(30);
  11211. bool validity_checked = false;
  11212. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11213. if (ctx.cert) {
  11214. time_t not_before = 0, not_after = 0;
  11215. bool result = ctx.validity(not_before, not_after);
  11216. EXPECT_TRUE(result);
  11217. // Verify that not_before < now < not_after for a valid cert
  11218. time_t now = time(nullptr);
  11219. EXPECT_LT(not_before, now);
  11220. EXPECT_GT(not_after, now);
  11221. validity_checked = true;
  11222. }
  11223. return true;
  11224. });
  11225. auto res = cli.Get("/test");
  11226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11227. EXPECT_TRUE(validity_checked);
  11228. }
  11229. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  11230. using namespace httplib::tls;
  11231. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11232. ASSERT_TRUE(svr.is_valid());
  11233. svr.Get("/test", [](const Request &, Response &res) {
  11234. res.set_content("ok", "text/plain");
  11235. });
  11236. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11237. auto se = detail::scope_exit([&] {
  11238. svr.stop();
  11239. t.join();
  11240. });
  11241. svr.wait_until_ready();
  11242. SSLClient cli(HOST, PORT);
  11243. cli.enable_server_certificate_verification(false);
  11244. cli.set_connection_timeout(30);
  11245. bool serial_checked = false;
  11246. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11247. if (ctx.cert) {
  11248. std::string serial = ctx.serial();
  11249. EXPECT_FALSE(serial.empty());
  11250. // Serial should be a hex string
  11251. for (char c : serial) {
  11252. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  11253. (c >= 'a' && c <= 'f'));
  11254. }
  11255. serial_checked = true;
  11256. }
  11257. return true;
  11258. });
  11259. auto res = cli.Get("/test");
  11260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11261. EXPECT_TRUE(serial_checked);
  11262. }
  11263. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  11264. // Test 1: Valid CA file - no error should be recorded
  11265. {
  11266. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11267. CLIENT_CA_CERT_FILE);
  11268. ASSERT_TRUE(svr.is_valid());
  11269. // With valid setup, last_ssl_error should be 0
  11270. EXPECT_EQ(0, svr.ssl_last_error());
  11271. }
  11272. // Test 2: Invalid CA file content
  11273. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  11274. {
  11275. // Create a temporary file with completely invalid content
  11276. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  11277. {
  11278. std::ofstream ofs(temp_invalid_ca);
  11279. ofs << "This is not a certificate file at all\n";
  11280. ofs << "Just plain text content\n";
  11281. }
  11282. // Create server with invalid CA file
  11283. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  11284. // Clean up temporary file
  11285. std::remove(temp_invalid_ca);
  11286. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  11287. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  11288. // Note: SSL_CTX_load_verify_locations typically fails first,
  11289. // but our error handling code path is still exercised
  11290. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  11291. }
  11292. }
  11293. TEST(VerifyCallbackTest, VerifyContextFields) {
  11294. using namespace httplib::tls;
  11295. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11296. ASSERT_TRUE(svr.is_valid());
  11297. svr.Get("/test", [](const Request &, Response &res) {
  11298. res.set_content("ok", "text/plain");
  11299. });
  11300. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11301. auto se = detail::scope_exit([&] {
  11302. svr.stop();
  11303. t.join();
  11304. });
  11305. svr.wait_until_ready();
  11306. SSLClient cli(HOST, PORT);
  11307. cli.enable_server_certificate_verification(false);
  11308. cli.set_connection_timeout(30);
  11309. int callback_count = 0;
  11310. bool saw_leaf_cert = false;
  11311. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11312. if (ctx.cert) {
  11313. callback_count++;
  11314. // We should see at least one certificate (the leaf)
  11315. std::string cn = ctx.subject_cn();
  11316. if (!cn.empty()) { saw_leaf_cert = true; }
  11317. // Verify context fields are populated
  11318. EXPECT_NE(ctx.session, nullptr);
  11319. EXPECT_GE(ctx.depth, 0);
  11320. }
  11321. return true;
  11322. });
  11323. auto res = cli.Get("/test");
  11324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11325. EXPECT_GT(callback_count, 0);
  11326. EXPECT_TRUE(saw_leaf_cert);
  11327. }
  11328. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  11329. using httplib::tls::TlsError;
  11330. // Test that verify_error_to_string returns empty for success
  11331. std::string success_str = TlsError::verify_error_to_string(0);
  11332. EXPECT_TRUE(success_str.empty());
  11333. // Test that verify_error_to_string returns non-empty for error codes
  11334. // Using a common error code (certificate expired)
  11335. std::string error_str =
  11336. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  11337. EXPECT_FALSE(error_str.empty());
  11338. }
  11339. TEST(SessionVerifierTest, CertificateAccepted) {
  11340. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11341. ASSERT_TRUE(svr.is_valid());
  11342. svr.Get("/test", [](const Request &, Response &res) {
  11343. res.set_content("ok", "text/plain");
  11344. });
  11345. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11346. auto se = detail::scope_exit([&] {
  11347. svr.stop();
  11348. t.join();
  11349. });
  11350. svr.wait_until_ready();
  11351. SSLClient cli(HOST, PORT);
  11352. cli.enable_server_certificate_verification(false);
  11353. cli.set_connection_timeout(30);
  11354. bool callback_called = false;
  11355. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11356. EXPECT_NE(session, nullptr);
  11357. callback_called = true;
  11358. return SSLVerifierResponse::CertificateAccepted;
  11359. });
  11360. auto res = cli.Get("/test");
  11361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11362. EXPECT_EQ(200, res->status);
  11363. EXPECT_TRUE(callback_called);
  11364. }
  11365. TEST(SessionVerifierTest, CertificateRejected) {
  11366. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11367. ASSERT_TRUE(svr.is_valid());
  11368. svr.Get("/test", [](const Request &, Response &res) {
  11369. res.set_content("ok", "text/plain");
  11370. });
  11371. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11372. auto se = detail::scope_exit([&] {
  11373. svr.stop();
  11374. t.join();
  11375. });
  11376. svr.wait_until_ready();
  11377. SSLClient cli(HOST, PORT);
  11378. cli.enable_server_certificate_verification(false);
  11379. cli.set_connection_timeout(30);
  11380. bool callback_called = false;
  11381. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11382. EXPECT_NE(session, nullptr);
  11383. callback_called = true;
  11384. return SSLVerifierResponse::CertificateRejected;
  11385. });
  11386. auto res = cli.Get("/test");
  11387. EXPECT_FALSE(res);
  11388. EXPECT_TRUE(callback_called);
  11389. }
  11390. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  11391. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11392. ASSERT_TRUE(svr.is_valid());
  11393. svr.Get("/test", [](const Request &, Response &res) {
  11394. res.set_content("ok", "text/plain");
  11395. });
  11396. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11397. auto se = detail::scope_exit([&] {
  11398. svr.stop();
  11399. t.join();
  11400. });
  11401. svr.wait_until_ready();
  11402. // NoDecisionMade with verification disabled should succeed (no default check)
  11403. SSLClient cli(HOST, PORT);
  11404. cli.enable_server_certificate_verification(false);
  11405. cli.set_connection_timeout(30);
  11406. bool callback_called = false;
  11407. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11408. EXPECT_NE(session, nullptr);
  11409. callback_called = true;
  11410. return SSLVerifierResponse::NoDecisionMade;
  11411. });
  11412. auto res = cli.Get("/test");
  11413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11414. EXPECT_EQ(200, res->status);
  11415. EXPECT_TRUE(callback_called);
  11416. }
  11417. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  11418. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11419. ASSERT_TRUE(svr.is_valid());
  11420. svr.Get("/test", [](const Request &, Response &res) {
  11421. res.set_content("ok", "text/plain");
  11422. });
  11423. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11424. auto se = detail::scope_exit([&] {
  11425. svr.stop();
  11426. t.join();
  11427. });
  11428. svr.wait_until_ready();
  11429. // NoDecisionMade with verification enabled should fail (self-signed cert).
  11430. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  11431. // so we only check that the request fails, not whether the callback was
  11432. // called.
  11433. SSLClient cli(HOST, PORT);
  11434. cli.enable_server_certificate_verification(true);
  11435. cli.set_connection_timeout(30);
  11436. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11437. EXPECT_NE(session, nullptr);
  11438. return SSLVerifierResponse::NoDecisionMade;
  11439. });
  11440. auto res = cli.Get("/test");
  11441. EXPECT_FALSE(res);
  11442. }
  11443. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11444. // Test SSL server using PemMemory constructor with client CA certificates
  11445. // Read PEM files
  11446. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11447. read_file(SERVER_CERT_FILE, server_cert_pem);
  11448. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11449. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11450. // Create SSLServer with PemMemory constructor including client CA
  11451. SSLServer::PemMemory server_pem = {
  11452. server_cert_pem.c_str(),
  11453. server_cert_pem.size(),
  11454. server_key_pem.c_str(),
  11455. server_key_pem.size(),
  11456. client_ca_pem.c_str(),
  11457. client_ca_pem.size(),
  11458. nullptr // no password for server key
  11459. };
  11460. SSLServer svr(server_pem);
  11461. ASSERT_TRUE(svr.is_valid());
  11462. // No SSL error should be recorded for valid setup
  11463. EXPECT_EQ(0, svr.ssl_last_error());
  11464. // Set up server endpoints
  11465. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11466. res.set_content("ok", "text/plain");
  11467. });
  11468. // Start server in a thread
  11469. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11470. svr.wait_until_ready();
  11471. // Connect with client certificate (using constructor with paths)
  11472. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11473. cli.enable_server_certificate_verification(false);
  11474. auto res = cli.Get("/test-pem-ca");
  11475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11476. EXPECT_EQ(200, res->status);
  11477. EXPECT_EQ("ok", res->body);
  11478. svr.stop();
  11479. server_thread.join();
  11480. }
  11481. #endif
  11482. #ifdef _WIN32
  11483. TEST(CleanupTest, WSACleanup) {
  11484. int ret = WSACleanup();
  11485. ASSERT_EQ(0, ret);
  11486. }
  11487. #endif
  11488. #ifndef CPPHTTPLIB_SSL_ENABLED
  11489. TEST(NoSSLSupport, SimpleInterface) {
  11490. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11491. }
  11492. #endif
  11493. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11494. TEST(InvalidScheme, SimpleInterface) {
  11495. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11496. }
  11497. #endif
  11498. TEST(NoScheme, SimpleInterface) {
  11499. Client cli("yahoo.com:80");
  11500. ASSERT_TRUE(cli.is_valid());
  11501. }
  11502. TEST(SendAPI, SimpleInterface_Online) {
  11503. Client cli("http://yahoo.com");
  11504. Request req;
  11505. req.method = "GET";
  11506. req.path = "/";
  11507. auto res = cli.send(req);
  11508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11509. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11510. }
  11511. TEST(SendAPI, WithParamsInRequest) {
  11512. Server svr;
  11513. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11514. EXPECT_TRUE(req.has_param("test"));
  11515. EXPECT_EQ("test_value", req.get_param_value("test"));
  11516. });
  11517. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11518. auto se = detail::scope_exit([&] {
  11519. svr.stop();
  11520. t.join();
  11521. ASSERT_FALSE(svr.is_running());
  11522. });
  11523. svr.wait_until_ready();
  11524. Client cli(HOST, PORT);
  11525. {
  11526. Request req;
  11527. req.method = "GET";
  11528. req.path = "/";
  11529. req.params.emplace("test", "test_value");
  11530. auto res = cli.send(req);
  11531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11532. }
  11533. {
  11534. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11536. }
  11537. }
  11538. TEST(ClientImplMethods, GetSocketTest) {
  11539. httplib::Server svr;
  11540. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11541. res.status = StatusCode::OK_200;
  11542. });
  11543. auto port = svr.bind_to_any_port("127.0.0.1");
  11544. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11545. auto se = detail::scope_exit([&] {
  11546. svr.stop();
  11547. thread.join();
  11548. ASSERT_FALSE(svr.is_running());
  11549. });
  11550. svr.wait_until_ready();
  11551. {
  11552. httplib::Client cli("127.0.0.1", port);
  11553. cli.set_keep_alive(true);
  11554. // Use the behavior of cpp-httplib of opening the connection
  11555. // only when the first request happens. If that changes,
  11556. // this test would be obsolete.
  11557. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11558. // This also implicitly tests the server. But other tests would fail much
  11559. // earlier than this one to be considered.
  11560. auto res = cli.Get("/");
  11561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11562. EXPECT_EQ(StatusCode::OK_200, res->status);
  11563. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11564. }
  11565. }
  11566. #ifdef CPPHTTPLIB_SSL_ENABLED
  11567. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11568. Client cli("http://yahoo.com");
  11569. auto res = cli.Get("/");
  11570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11571. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11572. cli.set_follow_location(true);
  11573. res = cli.Get("/");
  11574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11575. EXPECT_EQ(StatusCode::OK_200, res->status);
  11576. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11577. }
  11578. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11579. Client cli("https://yahoo.com");
  11580. auto res = cli.Get("/");
  11581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11582. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11583. cli.set_follow_location(true);
  11584. res = cli.Get("/");
  11585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11586. EXPECT_EQ(StatusCode::OK_200, res->status);
  11587. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11588. }
  11589. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11590. Client cli("https://yahoo.com");
  11591. auto res = cli.Get("/");
  11592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11593. ASSERT_FALSE(!res);
  11594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11595. ASSERT_FALSE(res == nullptr);
  11596. ASSERT_TRUE(res != nullptr);
  11597. EXPECT_EQ(Error::Success, res.error());
  11598. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11599. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11600. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11601. cli.set_follow_location(true);
  11602. res = cli.Get("/");
  11603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11604. EXPECT_EQ(Error::Success, res.error());
  11605. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11606. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11607. EXPECT_EQ(StatusCode::OK_200, res->status);
  11608. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11609. }
  11610. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11611. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11612. Client cli("https://cdnjs.cloudflare.com");
  11613. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11614. Headers{{"Accept-Encoding", "br"}});
  11615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11616. EXPECT_EQ(StatusCode::OK_200, res->status);
  11617. EXPECT_EQ(287630U, res->body.size());
  11618. EXPECT_EQ("application/javascript; charset=utf-8",
  11619. res->get_header_value("Content-Type"));
  11620. }
  11621. #endif
  11622. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11623. #undef REDIR_HOST // Silence compiler warning
  11624. #define REDIR_HOST "https://httpbingo.org"
  11625. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11626. Client cli(REDIR_HOST);
  11627. cli.set_follow_location(true);
  11628. auto res =
  11629. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11631. EXPECT_EQ(StatusCode::OK_200, res->status);
  11632. }
  11633. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11634. Client cli(REDIR_HOST);
  11635. cli.set_follow_location(true);
  11636. Params params;
  11637. params.emplace("url", "http://example.com");
  11638. params.emplace("status_code", "302");
  11639. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11641. EXPECT_EQ(StatusCode::OK_200, res->status);
  11642. }
  11643. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11644. Client cli(REDIR_HOST);
  11645. cli.set_follow_location(true);
  11646. Params params;
  11647. params.emplace("url", "http://example.com");
  11648. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11650. EXPECT_EQ(StatusCode::OK_200, res->status);
  11651. }
  11652. TEST(HttpToHttpsRedirectTest, CertFile) {
  11653. auto ssl_port = PORT + 1;
  11654. Server svr;
  11655. ASSERT_TRUE(svr.is_valid());
  11656. svr.Get("/index", [&](const Request &, Response &res) {
  11657. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11658. "/index");
  11659. svr.stop();
  11660. });
  11661. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11662. ASSERT_TRUE(ssl_svr.is_valid());
  11663. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11664. res.set_content("test", "text/plain");
  11665. ssl_svr.stop();
  11666. });
  11667. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11668. thread t2 =
  11669. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11670. auto se = detail::scope_exit([&] {
  11671. t2.join();
  11672. t.join();
  11673. ASSERT_FALSE(svr.is_running());
  11674. });
  11675. svr.wait_until_ready();
  11676. ssl_svr.wait_until_ready();
  11677. Client cli("127.0.0.1", PORT);
  11678. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11679. cli.enable_server_certificate_verification(true);
  11680. cli.set_follow_location(true);
  11681. cli.set_connection_timeout(30);
  11682. auto res = cli.Get("/index");
  11683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11684. ASSERT_EQ(StatusCode::OK_200, res->status);
  11685. }
  11686. TEST(SSLClientRedirectTest, CertFile) {
  11687. auto ssl_port = PORT + 1;
  11688. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11689. ASSERT_TRUE(ssl_svr1.is_valid());
  11690. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11691. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11692. "/index");
  11693. ssl_svr1.stop();
  11694. });
  11695. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11696. ASSERT_TRUE(ssl_svr2.is_valid());
  11697. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11698. res.set_content("test", "text/plain");
  11699. ssl_svr2.stop();
  11700. });
  11701. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11702. thread t2 =
  11703. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11704. auto se = detail::scope_exit([&] {
  11705. t2.join();
  11706. t.join();
  11707. ASSERT_FALSE(ssl_svr1.is_running());
  11708. });
  11709. ssl_svr1.wait_until_ready();
  11710. ssl_svr2.wait_until_ready();
  11711. SSLClient cli("127.0.0.1", PORT);
  11712. std::string cert;
  11713. read_file(SERVER_CERT2_FILE, cert);
  11714. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11715. cli.enable_server_certificate_verification(true);
  11716. cli.set_follow_location(true);
  11717. cli.set_connection_timeout(30);
  11718. auto res = cli.Get("/index");
  11719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11720. ASSERT_EQ(StatusCode::OK_200, res->status);
  11721. }
  11722. #endif
  11723. #ifdef CPPHTTPLIB_SSL_ENABLED
  11724. // Test that set_ca_cert_store() skips system certs (consistent with
  11725. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11726. // should be trusted - system certs should NOT be loaded.
  11727. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11728. // Load a specific cert that is NOT a system CA cert
  11729. std::string cert;
  11730. read_file(SERVER_CERT2_FILE, cert);
  11731. SSLClient cli("google.com");
  11732. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11733. cli.enable_server_certificate_verification(true);
  11734. // This should FAIL because:
  11735. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11736. // 2. System certs should NOT be loaded when custom store is set
  11737. // If system certs WERE loaded, this would succeed
  11738. auto res = cli.Get("/");
  11739. ASSERT_FALSE(res);
  11740. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11741. }
  11742. // Same as above, but through the native store handle path. Regression test:
  11743. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11744. // merged system certs into the user-provided store.
  11745. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11746. std::string cert;
  11747. read_file(SERVER_CERT2_FILE, cert);
  11748. SSLClient cli("google.com");
  11749. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11750. cli.enable_server_certificate_verification(true);
  11751. auto res = cli.Get("/");
  11752. ASSERT_FALSE(res);
  11753. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11754. }
  11755. // A custom store set via the native handle must still verify a server whose
  11756. // cert it does contain.
  11757. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11758. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11759. ASSERT_TRUE(svr.is_valid());
  11760. svr.Get("/test", [&](const Request &, Response &res) {
  11761. res.set_content("test", "text/plain");
  11762. });
  11763. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11764. auto se = detail::scope_exit([&] {
  11765. svr.stop();
  11766. t.join();
  11767. ASSERT_FALSE(svr.is_running());
  11768. });
  11769. svr.wait_until_ready();
  11770. SSLClient cli("127.0.0.1", PORT);
  11771. std::string cert;
  11772. read_file(SERVER_CERT2_FILE, cert);
  11773. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11774. cli.enable_server_certificate_verification(true);
  11775. cli.set_connection_timeout(30);
  11776. auto res = cli.Get("/test");
  11777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11778. ASSERT_EQ(StatusCode::OK_200, res->status);
  11779. }
  11780. // CA certs loaded through the universal Client must be transferred to the
  11781. // client created internally for following an HTTPS redirect. Regression test:
  11782. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11783. // the CA data for redirect transfer.
  11784. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11785. auto ssl_port = PORT + 1;
  11786. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11787. ASSERT_TRUE(ssl_svr1.is_valid());
  11788. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11789. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11790. "/index");
  11791. });
  11792. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11793. ASSERT_TRUE(ssl_svr2.is_valid());
  11794. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11795. res.set_content("test", "text/plain");
  11796. });
  11797. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11798. thread t2 =
  11799. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11800. auto se = detail::scope_exit([&] {
  11801. ssl_svr2.stop();
  11802. ssl_svr1.stop();
  11803. t2.join();
  11804. t.join();
  11805. ASSERT_FALSE(ssl_svr1.is_running());
  11806. });
  11807. ssl_svr1.wait_until_ready();
  11808. ssl_svr2.wait_until_ready();
  11809. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11810. std::string cert;
  11811. read_file(SERVER_CERT2_FILE, cert);
  11812. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11813. cli.enable_server_certificate_verification(true);
  11814. cli.set_follow_location(true);
  11815. cli.set_connection_timeout(30);
  11816. auto res = cli.Get("/index");
  11817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11818. ASSERT_EQ(StatusCode::OK_200, res->status);
  11819. }
  11820. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11821. // so a host signed by a system CA verifies even though a custom CA is set
  11822. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11823. std::string cert;
  11824. read_file(SERVER_CERT2_FILE, cert);
  11825. SSLClient cli("google.com");
  11826. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11827. cli.enable_system_ca(true);
  11828. cli.enable_server_certificate_verification(true);
  11829. auto res = cli.Get("/");
  11830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11831. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11832. }
  11833. // The custom CA remains effective when combined with the system CA
  11834. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11835. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11836. ASSERT_TRUE(svr.is_valid());
  11837. svr.Get("/test", [&](const Request &, Response &res) {
  11838. res.set_content("test", "text/plain");
  11839. });
  11840. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11841. auto se = detail::scope_exit([&] {
  11842. svr.stop();
  11843. t.join();
  11844. ASSERT_FALSE(svr.is_running());
  11845. });
  11846. svr.wait_until_ready();
  11847. SSLClient cli("127.0.0.1", PORT);
  11848. std::string cert;
  11849. read_file(SERVER_CERT2_FILE, cert);
  11850. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11851. cli.enable_system_ca(true);
  11852. cli.enable_server_certificate_verification(true);
  11853. cli.set_connection_timeout(30);
  11854. auto res = cli.Get("/test");
  11855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11856. ASSERT_EQ(StatusCode::OK_200, res->status);
  11857. }
  11858. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11859. // skip chain verification entirely (only the certificate identity was
  11860. // checked), so a server presenting an untrusted certificate with a matching
  11861. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11862. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11863. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11864. ASSERT_TRUE(svr.is_valid());
  11865. svr.Get("/test", [&](const Request &, Response &res) {
  11866. res.set_content("test", "text/plain");
  11867. });
  11868. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11869. auto se = detail::scope_exit([&] {
  11870. svr.stop();
  11871. t.join();
  11872. ASSERT_FALSE(svr.is_running());
  11873. });
  11874. svr.wait_until_ready();
  11875. SSLClient cli("127.0.0.1", PORT);
  11876. std::string cert;
  11877. // A trusted CA that did not sign the server certificate. The server cert
  11878. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11879. // this connection.
  11880. read_file(CLIENT_CA_CERT_FILE, cert);
  11881. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11882. cli.enable_server_certificate_verification(true);
  11883. cli.set_connection_timeout(30);
  11884. auto res = cli.Get("/test");
  11885. ASSERT_FALSE(res);
  11886. }
  11887. // enable_system_ca(false) prevents system CA loading entirely
  11888. TEST(SSLClientTest, DisableSystemCa_Online) {
  11889. SSLClient cli("google.com");
  11890. cli.enable_system_ca(false);
  11891. cli.enable_server_certificate_verification(true);
  11892. auto res = cli.Get("/");
  11893. ASSERT_FALSE(res);
  11894. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11895. // itself when the CA chain is empty
  11896. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11897. res.error() == Error::SSLConnection);
  11898. }
  11899. // The universal Client forwards enable_system_ca()
  11900. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11901. std::string cert;
  11902. read_file(SERVER_CERT2_FILE, cert);
  11903. Client cli("https://google.com");
  11904. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11905. cli.enable_system_ca(true);
  11906. cli.enable_server_certificate_verification(true);
  11907. auto res = cli.Get("/");
  11908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11909. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11910. }
  11911. // The system CA policy must carry over to the client created internally for
  11912. // following a cross-host HTTPS redirect
  11913. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11914. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11915. ASSERT_TRUE(svr.is_valid());
  11916. svr.Get("/index", [&](const Request &, Response &res) {
  11917. res.set_redirect("https://www.google.com/");
  11918. });
  11919. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11920. auto se = detail::scope_exit([&] {
  11921. svr.stop();
  11922. t.join();
  11923. ASSERT_FALSE(svr.is_running());
  11924. });
  11925. svr.wait_until_ready();
  11926. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11927. std::string cert;
  11928. read_file(SERVER_CERT2_FILE, cert);
  11929. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11930. cli.enable_system_ca(true);
  11931. cli.enable_server_certificate_verification(true);
  11932. cli.set_follow_location(true);
  11933. cli.set_connection_timeout(30);
  11934. // Receiving any response proves the redirect client completed the TLS
  11935. // handshake with a system-CA-signed host
  11936. auto res = cli.Get("/index");
  11937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11938. }
  11939. TEST(MultipartFormDataTest, LargeData) {
  11940. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11941. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11942. const ContentReader &content_reader) {
  11943. if (req.is_multipart_form_data()) {
  11944. std::vector<FormData> items;
  11945. content_reader(
  11946. [&](const FormData &file) {
  11947. items.push_back(file);
  11948. return true;
  11949. },
  11950. [&](const char *data, size_t data_length) {
  11951. items.back().content.append(data, data_length);
  11952. return true;
  11953. });
  11954. EXPECT_TRUE(std::string(items[0].name) == "document");
  11955. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11956. EXPECT_TRUE(items[0].filename == "2MB_data");
  11957. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11958. EXPECT_TRUE(items[1].name == "hello");
  11959. EXPECT_TRUE(items[1].content == "world");
  11960. EXPECT_TRUE(items[1].filename == "");
  11961. EXPECT_TRUE(items[1].content_type == "");
  11962. } else {
  11963. std::string body;
  11964. content_reader([&](const char *data, size_t data_length) {
  11965. body.append(data, data_length);
  11966. return true;
  11967. });
  11968. }
  11969. });
  11970. auto port = svr.bind_to_any_port(HOST);
  11971. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11972. auto se = detail::scope_exit([&] {
  11973. svr.stop();
  11974. t.join();
  11975. ASSERT_FALSE(svr.is_running());
  11976. });
  11977. svr.wait_until_ready();
  11978. {
  11979. std::string data(1024 * 1024 * 2, '.');
  11980. std::stringstream buffer;
  11981. buffer << data;
  11982. SSLClient cli(HOST, port);
  11983. cli.enable_server_certificate_verification(false);
  11984. UploadFormDataItems items{
  11985. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11986. {"hello", "world", "", ""},
  11987. };
  11988. auto res = cli.Post("/post", items);
  11989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11990. ASSERT_EQ(StatusCode::OK_200, res->status);
  11991. }
  11992. }
  11993. TEST(MultipartFormDataTest, DataProviderItems) {
  11994. std::random_device seed_gen;
  11995. std::mt19937 random(seed_gen());
  11996. std::string rand1;
  11997. rand1.resize(1000);
  11998. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11999. std::string rand2;
  12000. rand2.resize(3000);
  12001. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  12002. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12003. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  12004. const ContentReader &content_reader) {
  12005. ASSERT_FALSE(req.is_multipart_form_data());
  12006. std::string body;
  12007. content_reader([&](const char *data, size_t data_length) {
  12008. body.append(data, data_length);
  12009. return true;
  12010. });
  12011. EXPECT_EQ(body, "");
  12012. });
  12013. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  12014. const ContentReader &content_reader) {
  12015. ASSERT_TRUE(req.is_multipart_form_data());
  12016. std::vector<FormData> items;
  12017. content_reader(
  12018. [&](const FormData &file) {
  12019. items.push_back(file);
  12020. return true;
  12021. },
  12022. [&](const char *data, size_t data_length) {
  12023. items.back().content.append(data, data_length);
  12024. return true;
  12025. });
  12026. ASSERT_TRUE(items.size() == 2);
  12027. EXPECT_EQ(std::string(items[0].name), "name1");
  12028. EXPECT_EQ(items[0].content, "Testing123");
  12029. EXPECT_EQ(items[0].filename, "filename1");
  12030. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12031. EXPECT_EQ(items[1].name, "name2");
  12032. EXPECT_EQ(items[1].content, "Testing456");
  12033. EXPECT_EQ(items[1].filename, "");
  12034. EXPECT_EQ(items[1].content_type, "");
  12035. });
  12036. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  12037. const ContentReader &content_reader) {
  12038. ASSERT_TRUE(req.is_multipart_form_data());
  12039. std::vector<FormData> items;
  12040. content_reader(
  12041. [&](const FormData &file) {
  12042. items.push_back(file);
  12043. return true;
  12044. },
  12045. [&](const char *data, size_t data_length) {
  12046. items.back().content.append(data, data_length);
  12047. return true;
  12048. });
  12049. ASSERT_TRUE(items.size() == 2);
  12050. EXPECT_EQ(items[0].name, "name3");
  12051. EXPECT_EQ(items[0].content, rand1);
  12052. EXPECT_EQ(items[0].filename, "filename3");
  12053. EXPECT_EQ(items[0].content_type, "");
  12054. EXPECT_EQ(items[1].name, "name4");
  12055. EXPECT_EQ(items[1].content, rand2);
  12056. EXPECT_EQ(items[1].filename, "filename4");
  12057. EXPECT_EQ(items[1].content_type, "");
  12058. });
  12059. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  12060. const ContentReader &content_reader) {
  12061. ASSERT_TRUE(req.is_multipart_form_data());
  12062. std::vector<FormData> items;
  12063. content_reader(
  12064. [&](const FormData &file) {
  12065. items.push_back(file);
  12066. return true;
  12067. },
  12068. [&](const char *data, size_t data_length) {
  12069. items.back().content.append(data, data_length);
  12070. return true;
  12071. });
  12072. ASSERT_TRUE(items.size() == 4);
  12073. EXPECT_EQ(std::string(items[0].name), "name1");
  12074. EXPECT_EQ(items[0].content, "Testing123");
  12075. EXPECT_EQ(items[0].filename, "filename1");
  12076. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12077. EXPECT_EQ(items[1].name, "name2");
  12078. EXPECT_EQ(items[1].content, "Testing456");
  12079. EXPECT_EQ(items[1].filename, "");
  12080. EXPECT_EQ(items[1].content_type, "");
  12081. EXPECT_EQ(items[2].name, "name3");
  12082. EXPECT_EQ(items[2].content, rand1);
  12083. EXPECT_EQ(items[2].filename, "filename3");
  12084. EXPECT_EQ(items[2].content_type, "");
  12085. EXPECT_EQ(items[3].name, "name4");
  12086. EXPECT_EQ(items[3].content, rand2);
  12087. EXPECT_EQ(items[3].filename, "filename4");
  12088. EXPECT_EQ(items[3].content_type, "");
  12089. });
  12090. auto port = svr.bind_to_any_port("localhost");
  12091. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12092. auto se = detail::scope_exit([&] {
  12093. svr.stop();
  12094. t.join();
  12095. ASSERT_FALSE(svr.is_running());
  12096. });
  12097. svr.wait_until_ready();
  12098. {
  12099. SSLClient cli("localhost", port);
  12100. cli.enable_server_certificate_verification(false);
  12101. UploadFormDataItems items{
  12102. {"name1", "Testing123", "filename1", "application/octet-stream"},
  12103. {"name2", "Testing456", "", ""}, // not a file
  12104. };
  12105. {
  12106. auto res = cli.Post("/post-none", {}, {}, {});
  12107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12108. ASSERT_EQ(StatusCode::OK_200, res->status);
  12109. }
  12110. FormDataProviderItems providers;
  12111. {
  12112. auto res =
  12113. cli.Post("/post-items", {}, items, providers); // empty providers
  12114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12115. ASSERT_EQ(StatusCode::OK_200, res->status);
  12116. }
  12117. providers.push_back({"name3",
  12118. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12119. // test the offset is given correctly at each step
  12120. if (!offset)
  12121. sink.os.write(rand1.data(), 30);
  12122. else if (offset == 30)
  12123. sink.os.write(rand1.data() + 30, 300);
  12124. else if (offset == 330)
  12125. sink.os.write(rand1.data() + 330, 670);
  12126. else if (offset == rand1.size())
  12127. sink.done();
  12128. return true;
  12129. },
  12130. "filename3",
  12131. {}});
  12132. providers.push_back({"name4",
  12133. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12134. // test the offset is given correctly at each step
  12135. if (!offset)
  12136. sink.os.write(rand2.data(), 2000);
  12137. else if (offset == 2000)
  12138. sink.os.write(rand2.data() + 2000, 1);
  12139. else if (offset == 2001)
  12140. sink.os.write(rand2.data() + 2001, 999);
  12141. else if (offset == rand2.size())
  12142. sink.done();
  12143. return true;
  12144. },
  12145. "filename4",
  12146. {}});
  12147. {
  12148. auto res = cli.Post("/post-providers", {}, {}, providers);
  12149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12150. ASSERT_EQ(StatusCode::OK_200, res->status);
  12151. }
  12152. {
  12153. auto res = cli.Post("/post-both", {}, items, providers);
  12154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12155. ASSERT_EQ(StatusCode::OK_200, res->status);
  12156. }
  12157. }
  12158. }
  12159. TEST(MultipartFormDataTest, BadHeader) {
  12160. Server svr;
  12161. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12162. res.set_content("ok", "text/plain");
  12163. });
  12164. thread t = thread([&] { svr.listen(HOST, PORT); });
  12165. auto se = detail::scope_exit([&] {
  12166. svr.stop();
  12167. t.join();
  12168. ASSERT_FALSE(svr.is_running());
  12169. });
  12170. svr.wait_until_ready();
  12171. const std::string body =
  12172. "This is the preamble. It is to be ignored, though it\r\n"
  12173. "is a handy place for composition agents to include an\r\n"
  12174. "explanatory note to non-MIME conformant readers.\r\n"
  12175. "\r\n"
  12176. "\r\n"
  12177. "--simple boundary\r\n"
  12178. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12179. ": BAD...\r\n"
  12180. "\r\n"
  12181. "value1\r\n"
  12182. "--simple boundary\r\n"
  12183. "Content-Disposition: form-data; name=\"field2\"; "
  12184. "filename=\"example.txt\"\r\n"
  12185. "\r\n"
  12186. "value2\r\n"
  12187. "--simple boundary--\r\n"
  12188. "This is the epilogue. It is also to be ignored.\r\n";
  12189. std::string content_type =
  12190. R"(multipart/form-data; boundary="simple boundary")";
  12191. Client cli(HOST, PORT);
  12192. auto res = cli.Post("/post", body, content_type.c_str());
  12193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12194. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12195. }
  12196. TEST(MultipartFormDataTest, WithPreamble) {
  12197. Server svr;
  12198. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12199. res.set_content("ok", "text/plain");
  12200. });
  12201. thread t = thread([&] { svr.listen(HOST, PORT); });
  12202. auto se = detail::scope_exit([&] {
  12203. svr.stop();
  12204. t.join();
  12205. ASSERT_FALSE(svr.is_running());
  12206. });
  12207. svr.wait_until_ready();
  12208. const std::string body =
  12209. "This is the preamble. It is to be ignored, though it\r\n"
  12210. "is a handy place for composition agents to include an\r\n"
  12211. "explanatory note to non-MIME conformant readers.\r\n"
  12212. "\r\n"
  12213. "\r\n"
  12214. "--simple boundary\r\n"
  12215. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12216. "\r\n"
  12217. "value1\r\n"
  12218. "--simple boundary\r\n"
  12219. "Content-Disposition: form-data; name=\"field2\"; "
  12220. "filename=\"example.txt\"\r\n"
  12221. "\r\n"
  12222. "value2\r\n"
  12223. "--simple boundary--\r\n"
  12224. "This is the epilogue. It is also to be ignored.\r\n";
  12225. std::string content_type =
  12226. R"(multipart/form-data; boundary="simple boundary")";
  12227. Client cli(HOST, PORT);
  12228. auto res = cli.Post("/post", body, content_type.c_str());
  12229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12230. EXPECT_EQ(StatusCode::OK_200, res->status);
  12231. }
  12232. TEST(MultipartFormDataTest, PostCustomBoundary) {
  12233. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12234. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  12235. const ContentReader &content_reader) {
  12236. if (req.is_multipart_form_data()) {
  12237. std::vector<FormData> items;
  12238. content_reader(
  12239. [&](const FormData &file) {
  12240. items.push_back(file);
  12241. return true;
  12242. },
  12243. [&](const char *data, size_t data_length) {
  12244. items.back().content.append(data, data_length);
  12245. return true;
  12246. });
  12247. EXPECT_TRUE(std::string(items[0].name) == "document");
  12248. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12249. EXPECT_TRUE(items[0].filename == "2MB_data");
  12250. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12251. EXPECT_TRUE(items[1].name == "hello");
  12252. EXPECT_TRUE(items[1].content == "world");
  12253. EXPECT_TRUE(items[1].filename == "");
  12254. EXPECT_TRUE(items[1].content_type == "");
  12255. } else {
  12256. std::string body;
  12257. content_reader([&](const char *data, size_t data_length) {
  12258. body.append(data, data_length);
  12259. return true;
  12260. });
  12261. }
  12262. });
  12263. auto port = svr.bind_to_any_port("localhost");
  12264. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12265. auto se = detail::scope_exit([&] {
  12266. svr.stop();
  12267. t.join();
  12268. ASSERT_FALSE(svr.is_running());
  12269. });
  12270. svr.wait_until_ready();
  12271. {
  12272. std::string data(1024 * 1024 * 2, '.');
  12273. std::stringstream buffer;
  12274. buffer << data;
  12275. SSLClient cli("localhost", port);
  12276. cli.enable_server_certificate_verification(false);
  12277. UploadFormDataItems items{
  12278. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12279. {"hello", "world", "", ""},
  12280. };
  12281. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  12282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12283. ASSERT_EQ(StatusCode::OK_200, res->status);
  12284. }
  12285. }
  12286. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  12287. std::string data(1024 * 1024 * 2, '&');
  12288. std::stringstream buffer;
  12289. buffer << data;
  12290. Client cli("https://localhost:8080");
  12291. UploadFormDataItems items{
  12292. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12293. {"hello", "world", "", ""},
  12294. };
  12295. for (const char &c : " \t\r\n") {
  12296. auto res =
  12297. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  12298. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12299. ASSERT_FALSE(res);
  12300. }
  12301. }
  12302. TEST(MultipartFormDataTest, PutFormData) {
  12303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12304. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  12305. const ContentReader &content_reader) {
  12306. if (req.is_multipart_form_data()) {
  12307. std::vector<FormData> items;
  12308. content_reader(
  12309. [&](const FormData &file) {
  12310. items.push_back(file);
  12311. return true;
  12312. },
  12313. [&](const char *data, size_t data_length) {
  12314. items.back().content.append(data, data_length);
  12315. return true;
  12316. });
  12317. EXPECT_TRUE(std::string(items[0].name) == "document");
  12318. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12319. EXPECT_TRUE(items[0].filename == "2MB_data");
  12320. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12321. EXPECT_TRUE(items[1].name == "hello");
  12322. EXPECT_TRUE(items[1].content == "world");
  12323. EXPECT_TRUE(items[1].filename == "");
  12324. EXPECT_TRUE(items[1].content_type == "");
  12325. } else {
  12326. std::string body;
  12327. content_reader([&](const char *data, size_t data_length) {
  12328. body.append(data, data_length);
  12329. return true;
  12330. });
  12331. }
  12332. });
  12333. auto port = svr.bind_to_any_port("localhost");
  12334. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12335. auto se = detail::scope_exit([&] {
  12336. svr.stop();
  12337. t.join();
  12338. ASSERT_FALSE(svr.is_running());
  12339. });
  12340. svr.wait_until_ready();
  12341. {
  12342. std::string data(1024 * 1024 * 2, '&');
  12343. std::stringstream buffer;
  12344. buffer << data;
  12345. SSLClient cli("localhost", port);
  12346. cli.enable_server_certificate_verification(false);
  12347. UploadFormDataItems items{
  12348. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12349. {"hello", "world", "", ""},
  12350. };
  12351. auto res = cli.Put("/put", items);
  12352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12353. ASSERT_EQ(StatusCode::OK_200, res->status);
  12354. }
  12355. }
  12356. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  12357. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12358. svr.Put("/put_customboundary",
  12359. [&](const Request &req, const Response & /*res*/,
  12360. const ContentReader &content_reader) {
  12361. if (req.is_multipart_form_data()) {
  12362. std::vector<FormData> items;
  12363. content_reader(
  12364. [&](const FormData &file) {
  12365. items.push_back(file);
  12366. return true;
  12367. },
  12368. [&](const char *data, size_t data_length) {
  12369. items.back().content.append(data, data_length);
  12370. return true;
  12371. });
  12372. EXPECT_TRUE(std::string(items[0].name) == "document");
  12373. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12374. EXPECT_TRUE(items[0].filename == "2MB_data");
  12375. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12376. EXPECT_TRUE(items[1].name == "hello");
  12377. EXPECT_TRUE(items[1].content == "world");
  12378. EXPECT_TRUE(items[1].filename == "");
  12379. EXPECT_TRUE(items[1].content_type == "");
  12380. } else {
  12381. std::string body;
  12382. content_reader([&](const char *data, size_t data_length) {
  12383. body.append(data, data_length);
  12384. return true;
  12385. });
  12386. }
  12387. });
  12388. auto port = svr.bind_to_any_port("localhost");
  12389. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12390. auto se = detail::scope_exit([&] {
  12391. svr.stop();
  12392. t.join();
  12393. ASSERT_FALSE(svr.is_running());
  12394. });
  12395. svr.wait_until_ready();
  12396. {
  12397. std::string data(1024 * 1024 * 2, '&');
  12398. std::stringstream buffer;
  12399. buffer << data;
  12400. SSLClient cli("localhost", port);
  12401. cli.enable_server_certificate_verification(false);
  12402. UploadFormDataItems items{
  12403. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12404. {"hello", "world", "", ""},
  12405. };
  12406. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  12407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12408. ASSERT_EQ(StatusCode::OK_200, res->status);
  12409. }
  12410. }
  12411. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  12412. std::string data(1024 * 1024 * 2, '&');
  12413. std::stringstream buffer;
  12414. buffer << data;
  12415. Client cli("https://localhost:8080");
  12416. cli.enable_server_certificate_verification(false);
  12417. UploadFormDataItems items{
  12418. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12419. {"hello", "world", "", ""},
  12420. };
  12421. for (const char &c : " \t\r\n") {
  12422. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  12423. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12424. ASSERT_FALSE(res);
  12425. }
  12426. }
  12427. TEST(MultipartFormDataTest, AlternateFilename) {
  12428. auto handled = false;
  12429. Server svr;
  12430. svr.Post("/test", [&](const Request &req, Response &res) {
  12431. ASSERT_EQ(2u, req.form.files.size());
  12432. ASSERT_EQ(1u, req.form.fields.size());
  12433. // Test files
  12434. const auto &file1 = req.form.get_file("file1");
  12435. ASSERT_EQ("file1", file1.name);
  12436. ASSERT_EQ("A.txt", file1.filename);
  12437. ASSERT_EQ("text/plain", file1.content_type);
  12438. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  12439. const auto &file2 = req.form.get_file("file2");
  12440. ASSERT_EQ("file2", file2.name);
  12441. ASSERT_EQ("a.html", file2.filename);
  12442. ASSERT_EQ("text/html", file2.content_type);
  12443. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12444. file2.content);
  12445. // Test text field
  12446. const auto &text = req.form.get_field("text");
  12447. ASSERT_EQ("text default", text);
  12448. res.set_content("ok", "text/plain");
  12449. handled = true;
  12450. });
  12451. thread t = thread([&] { svr.listen(HOST, PORT); });
  12452. auto se = detail::scope_exit([&] {
  12453. svr.stop();
  12454. t.join();
  12455. ASSERT_FALSE(svr.is_running());
  12456. ASSERT_TRUE(handled);
  12457. });
  12458. svr.wait_until_ready();
  12459. auto req = "POST /test HTTP/1.1\r\n"
  12460. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12461. "Content-Length: 399\r\n"
  12462. "\r\n"
  12463. "----------\r\n"
  12464. "Content-Disposition: form-data; name=\"text\"\r\n"
  12465. "\r\n"
  12466. "text default\r\n"
  12467. "----------\r\n"
  12468. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12469. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12470. "Content-Type: text/plain\r\n"
  12471. "\r\n"
  12472. "Content of a.txt.\r\n"
  12473. "\r\n"
  12474. "----------\r\n"
  12475. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12476. "\"a.html\"\r\n"
  12477. "Content-Type: text/html\r\n"
  12478. "\r\n"
  12479. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12480. "\r\n"
  12481. "------------\r\n";
  12482. ASSERT_TRUE(send_request(1, req));
  12483. }
  12484. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12485. auto handled = false;
  12486. Server svr;
  12487. svr.Post("/test", [&](const Request &req, Response &res) {
  12488. // Case-insensitive "utf-8''" prefix with a long value
  12489. const auto &file = req.form.get_file("file1");
  12490. ASSERT_EQ("file1", file.name);
  12491. // 8000 chars exercises both the Content-Disposition parser and the
  12492. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12493. // Prior to the fix, std::regex_match on this header would cause O(N)
  12494. // stack recursion in libstdc++, leading to SIGSEGV.
  12495. std::string expected_filename(8000, 'A');
  12496. ASSERT_EQ(expected_filename, file.filename);
  12497. res.set_content("ok", "text/plain");
  12498. handled = true;
  12499. });
  12500. thread t = thread([&] { svr.listen(HOST, PORT); });
  12501. auto se = detail::scope_exit([&] {
  12502. svr.stop();
  12503. t.join();
  12504. ASSERT_FALSE(svr.is_running());
  12505. ASSERT_TRUE(handled);
  12506. });
  12507. svr.wait_until_ready();
  12508. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12509. // Regression test for GHSA-qq6v-r583-3h69
  12510. std::string long_filename(8000, 'A');
  12511. std::string body = "----------\r\n"
  12512. "Content-Disposition: form-data; name=\"file1\"; "
  12513. "filename*=\"Utf-8''" +
  12514. long_filename +
  12515. "\"\r\n"
  12516. "\r\n"
  12517. "hello\r\n"
  12518. "------------\r\n";
  12519. auto req = "POST /test HTTP/1.1\r\n"
  12520. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12521. "Content-Length: " +
  12522. std::to_string(body.size()) + "\r\n\r\n" + body;
  12523. ASSERT_TRUE(send_request(1, req));
  12524. }
  12525. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12526. auto handled = false;
  12527. Server svr;
  12528. svr.Post("/test", [&](const Request &req, Response &) {
  12529. ASSERT_EQ(2u, req.form.fields.size());
  12530. const auto &text1 = req.form.get_field("text1");
  12531. ASSERT_EQ("text1", text1);
  12532. const auto &text2 = req.form.get_field("text2");
  12533. ASSERT_EQ("text2", text2);
  12534. handled = true;
  12535. });
  12536. thread t = thread([&] { svr.listen(HOST, PORT); });
  12537. auto se = detail::scope_exit([&] {
  12538. svr.stop();
  12539. t.join();
  12540. ASSERT_FALSE(svr.is_running());
  12541. ASSERT_TRUE(handled);
  12542. });
  12543. svr.wait_until_ready();
  12544. auto req = "POST /test HTTP/1.1\r\n"
  12545. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12546. "Content-Length: 146\r\n"
  12547. "\r\n----------\r\n"
  12548. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12549. "\r\n"
  12550. "text1"
  12551. "\r\n----------\r\n"
  12552. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12553. "\r\n"
  12554. "text2"
  12555. "\r\n------------";
  12556. std::string response;
  12557. ASSERT_TRUE(send_request(1, req, &response));
  12558. ASSERT_EQ("200", response.substr(9, 3));
  12559. }
  12560. TEST(MultipartFormDataTest, ContentLength) {
  12561. auto handled = false;
  12562. Server svr;
  12563. svr.Post("/test", [&](const Request &req, Response &) {
  12564. ASSERT_EQ(2u, req.form.fields.size());
  12565. const auto &text1 = req.form.get_field("text1");
  12566. ASSERT_EQ("text1", text1);
  12567. const auto &text2 = req.form.get_field("text2");
  12568. ASSERT_EQ("text2", text2);
  12569. handled = true;
  12570. });
  12571. thread t = thread([&] { svr.listen(HOST, PORT); });
  12572. auto se = detail::scope_exit([&] {
  12573. svr.stop();
  12574. t.join();
  12575. ASSERT_FALSE(svr.is_running());
  12576. ASSERT_TRUE(handled);
  12577. });
  12578. svr.wait_until_ready();
  12579. auto req = "POST /test HTTP/1.1\r\n"
  12580. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12581. "Content-Length: 167\r\n"
  12582. "\r\n----------\r\n"
  12583. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12584. "Content-Length: 5\r\n"
  12585. "\r\n"
  12586. "text1"
  12587. "\r\n----------\r\n"
  12588. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12589. "\r\n"
  12590. "text2"
  12591. "\r\n------------\r\n";
  12592. std::string response;
  12593. ASSERT_TRUE(send_request(1, req, &response));
  12594. ASSERT_EQ("200", response.substr(9, 3));
  12595. }
  12596. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12597. auto handled = false;
  12598. Server svr;
  12599. svr.Post("/test", [&](const Request &req, Response &) {
  12600. ASSERT_EQ(2u, req.form.fields.size());
  12601. const auto &text1 = req.form.get_field("text1");
  12602. ASSERT_EQ("text1", text1);
  12603. // TODO: Add header access for text fields if needed
  12604. const auto &text2 = req.form.get_field("text2");
  12605. ASSERT_EQ("text2", text2);
  12606. // TODO: Header access for text fields needs to be implemented
  12607. // auto &headers = it->second.headers;
  12608. // ASSERT_EQ(3U, headers.size());
  12609. // auto custom_header = headers.find("x-whatever");
  12610. // ASSERT_TRUE(custom_header != headers.end());
  12611. // ASSERT_NE("customvalue", custom_header->second);
  12612. // ASSERT_EQ("CustomValue", custom_header->second);
  12613. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12614. handled = true;
  12615. });
  12616. thread t = thread([&] { svr.listen(HOST, PORT); });
  12617. auto se = detail::scope_exit([&] {
  12618. svr.stop();
  12619. t.join();
  12620. ASSERT_FALSE(svr.is_running());
  12621. ASSERT_TRUE(handled);
  12622. });
  12623. svr.wait_until_ready();
  12624. auto req = "POST /test HTTP/1.1\r\n"
  12625. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12626. "Content-Length: 232\r\n"
  12627. "\r\n----------\r\n"
  12628. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12629. "Content-Length: 5\r\n"
  12630. "X-Test: 1\r\n"
  12631. "\r\n"
  12632. "text1"
  12633. "\r\n----------\r\n"
  12634. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12635. "Content-Type: text/plain\r\n"
  12636. "X-Whatever: CustomValue\r\n"
  12637. "\r\n"
  12638. "text2"
  12639. "\r\n------------\r\n"
  12640. "That should be disregarded. Not even read";
  12641. std::string response;
  12642. ASSERT_TRUE(send_request(1, req, &response));
  12643. ASSERT_EQ("200", response.substr(9, 3));
  12644. }
  12645. TEST(MultipartFormDataTest, LargeHeader) {
  12646. auto handled = false;
  12647. Server svr;
  12648. svr.Post("/test", [&](const Request &req, Response &) {
  12649. ASSERT_EQ(1u, req.form.fields.size());
  12650. const auto &text = req.form.get_field("name1");
  12651. ASSERT_EQ("text1", text);
  12652. handled = true;
  12653. });
  12654. thread t = thread([&] { svr.listen(HOST, PORT); });
  12655. auto se = detail::scope_exit([&] {
  12656. svr.stop();
  12657. t.join();
  12658. ASSERT_FALSE(svr.is_running());
  12659. ASSERT_TRUE(handled);
  12660. });
  12661. svr.wait_until_ready();
  12662. auto boundary = std::string("cpp-httplib-multipart-data");
  12663. std::string content = "--" + boundary +
  12664. "\r\n"
  12665. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12666. "\r\n"
  12667. "text1\r\n"
  12668. "--" +
  12669. boundary + "--\r\n";
  12670. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12671. "Content-Type: multipart/form-data;boundary=" +
  12672. boundary +
  12673. "\r\n"
  12674. "Content-Length: " +
  12675. std::to_string(content.size()) +
  12676. "\r\n"
  12677. "Dummy-Header: ";
  12678. std::string header_suffix = "\r\n"
  12679. "\r\n";
  12680. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12681. size_t header_dummy_size =
  12682. read_buff_size -
  12683. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12684. auto header_dummy = std::string(header_dummy_size, '@');
  12685. auto req = header_prefix + header_dummy + header_suffix + content;
  12686. std::string response;
  12687. ASSERT_TRUE(send_request(1, req, &response));
  12688. ASSERT_EQ("200", response.substr(9, 3));
  12689. }
  12690. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12691. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12692. // (not chunked Transfer-Encoding) after the streaming refactor.
  12693. auto handled = false;
  12694. Server svr;
  12695. svr.Post("/upload", [&](const Request &req, Response &res) {
  12696. auto cl_it = req.headers.find("Content-Length");
  12697. EXPECT_TRUE(cl_it != req.headers.end());
  12698. auto te_it = req.headers.find("Transfer-Encoding");
  12699. EXPECT_TRUE(te_it == req.headers.end());
  12700. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12701. res.set_content("ok", "text/plain");
  12702. handled = true;
  12703. });
  12704. auto port = svr.bind_to_any_port(HOST);
  12705. auto t = thread([&] { svr.listen_after_bind(); });
  12706. auto se = detail::scope_exit([&] {
  12707. svr.stop();
  12708. t.join();
  12709. ASSERT_FALSE(svr.is_running());
  12710. ASSERT_TRUE(handled);
  12711. });
  12712. svr.wait_until_ready();
  12713. UploadFormDataItems items = {
  12714. {"field1", "hello", "", "text/plain"},
  12715. {"file1", "world", "test.txt", "application/octet-stream"},
  12716. };
  12717. Client cli(HOST, port);
  12718. auto res = cli.Post("/upload", {}, items);
  12719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12720. EXPECT_EQ(StatusCode::OK_200, res->status);
  12721. }
  12722. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12723. // Verify that make_multipart_content_provider coalesces many small segments
  12724. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12725. constexpr size_t kItemCount = 1000;
  12726. UploadFormDataItems items;
  12727. items.reserve(kItemCount);
  12728. for (size_t i = 0; i < kItemCount; i++) {
  12729. items.push_back(
  12730. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12731. }
  12732. const std::string boundary = "----test-boundary";
  12733. auto content_length = detail::get_multipart_content_length(items, boundary);
  12734. auto provider = detail::make_multipart_content_provider(items, boundary);
  12735. // Drive the provider the same way write_content_with_progress does
  12736. size_t write_count = 0;
  12737. size_t total_bytes = 0;
  12738. DataSink sink;
  12739. size_t offset = 0;
  12740. sink.write = [&](const char *d, size_t l) -> bool {
  12741. (void)d;
  12742. write_count++;
  12743. total_bytes += l;
  12744. offset += l;
  12745. return true;
  12746. };
  12747. sink.is_writable = []() -> bool { return true; };
  12748. while (offset < content_length) {
  12749. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12750. }
  12751. EXPECT_EQ(content_length, total_bytes);
  12752. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12753. // With buffering into 64KB blocks, write_count should be much smaller.
  12754. auto segment_count = 3 * kItemCount + 1;
  12755. EXPECT_LT(write_count, segment_count / 10);
  12756. }
  12757. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12758. // Integration test: send many UploadFormDataItems and verify the server
  12759. // receives all of them correctly (#2410).
  12760. constexpr size_t kItemCount = 500;
  12761. auto handled = false;
  12762. Server svr;
  12763. svr.Post("/upload", [&](const Request &req, Response &res) {
  12764. EXPECT_EQ(kItemCount, req.form.fields.size());
  12765. for (size_t i = 0; i < kItemCount; i++) {
  12766. auto key = "field" + std::to_string(i);
  12767. auto val = "value" + std::to_string(i);
  12768. auto it = req.form.fields.find(key);
  12769. if (it != req.form.fields.end()) {
  12770. EXPECT_EQ(val, it->second.content);
  12771. } else {
  12772. ADD_FAILURE() << "Missing field: " << key;
  12773. }
  12774. }
  12775. res.set_content("ok", "text/plain");
  12776. handled = true;
  12777. });
  12778. auto port = svr.bind_to_any_port(HOST);
  12779. auto t = thread([&] { svr.listen_after_bind(); });
  12780. auto se = detail::scope_exit([&] {
  12781. svr.stop();
  12782. t.join();
  12783. ASSERT_FALSE(svr.is_running());
  12784. ASSERT_TRUE(handled);
  12785. });
  12786. svr.wait_until_ready();
  12787. UploadFormDataItems items;
  12788. items.reserve(kItemCount);
  12789. for (size_t i = 0; i < kItemCount; i++) {
  12790. items.push_back(
  12791. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12792. }
  12793. Client cli(HOST, port);
  12794. auto res = cli.Post("/upload", items);
  12795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12796. EXPECT_EQ(StatusCode::OK_200, res->status);
  12797. }
  12798. TEST(MultipartFormDataTest, MakeFileProvider) {
  12799. // Verify make_file_provider sends a file's contents correctly.
  12800. const std::string file_content(4096, 'Z');
  12801. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12802. {
  12803. std::ofstream ofs(tmp_path, std::ios::binary);
  12804. ofs.write(file_content.data(),
  12805. static_cast<std::streamsize>(file_content.size()));
  12806. }
  12807. auto handled = false;
  12808. Server svr;
  12809. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12810. const ContentReader &content_reader) {
  12811. ASSERT_TRUE(req.is_multipart_form_data());
  12812. std::vector<FormData> items;
  12813. content_reader(
  12814. [&](const FormData &file) {
  12815. items.push_back(file);
  12816. return true;
  12817. },
  12818. [&](const char *data, size_t data_length) {
  12819. items.back().content.append(data, data_length);
  12820. return true;
  12821. });
  12822. ASSERT_EQ(1u, items.size());
  12823. EXPECT_EQ("myfile", items[0].name);
  12824. EXPECT_EQ("data.bin", items[0].filename);
  12825. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12826. EXPECT_EQ(file_content, items[0].content);
  12827. handled = true;
  12828. });
  12829. auto port = svr.bind_to_any_port(HOST);
  12830. auto t = thread([&] { svr.listen_after_bind(); });
  12831. auto se = detail::scope_exit([&] {
  12832. svr.stop();
  12833. t.join();
  12834. ASSERT_FALSE(svr.is_running());
  12835. ASSERT_TRUE(handled);
  12836. std::remove(tmp_path.c_str());
  12837. });
  12838. svr.wait_until_ready();
  12839. FormDataProviderItems providers;
  12840. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12841. "application/octet-stream"));
  12842. Client cli(HOST, port);
  12843. auto res = cli.Post("/upload", {}, {}, providers);
  12844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12845. EXPECT_EQ(StatusCode::OK_200, res->status);
  12846. }
  12847. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12848. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12849. // (100) headers is rejected with a 400 Bad Request response.
  12850. Server svr;
  12851. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12852. res.set_content("ok", "text/plain");
  12853. });
  12854. thread t = thread([&] { svr.listen(HOST, PORT); });
  12855. auto se = detail::scope_exit([&] {
  12856. svr.stop();
  12857. t.join();
  12858. ASSERT_FALSE(svr.is_running());
  12859. });
  12860. svr.wait_until_ready();
  12861. // Build a multipart part with 101 custom headers (exceeding
  12862. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12863. std::stringstream body;
  12864. body << "--simpleboundary\r\n"
  12865. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12866. for (int i = 0; i < 101; i++) {
  12867. body << "X-Custom-Header-" << i << ": value\r\n";
  12868. }
  12869. body << "\r\n"
  12870. << "value1\r\n"
  12871. << "--simpleboundary--\r\n";
  12872. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12873. Client cli(HOST, PORT);
  12874. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12876. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12877. }
  12878. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  12879. // A body that never contains the declared boundary must not be accumulated
  12880. // while the parser waits for it. Buffering it would also make every read
  12881. // rescan everything seen so far, which is quadratic in the body size.
  12882. Server svr;
  12883. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  12884. res.set_content("ok", "text/plain");
  12885. });
  12886. auto port = svr.bind_to_any_port(HOST);
  12887. thread t = thread([&] { svr.listen_after_bind(); });
  12888. auto se = detail::scope_exit([&] {
  12889. svr.stop();
  12890. t.join();
  12891. ASSERT_FALSE(svr.is_running());
  12892. });
  12893. svr.wait_until_ready();
  12894. Client cli(HOST, port);
  12895. cli.set_read_timeout(60, 0);
  12896. cli.set_write_timeout(60, 0);
  12897. // '-' is the worst case: it matches the first character of the boundary, so
  12898. // every position has to be checked against it.
  12899. auto post_dashes = [&](size_t size) {
  12900. const std::string body(size, '-');
  12901. auto start = std::chrono::steady_clock::now();
  12902. auto res =
  12903. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  12904. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  12905. std::chrono::steady_clock::now() - start)
  12906. .count();
  12907. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  12908. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  12909. return ms;
  12910. };
  12911. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  12912. // Windows.
  12913. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  12914. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  12915. // Comparing the two sizes rather than checking an absolute duration keeps
  12916. // this meaningful across build types and CI load, both of which move the
  12917. // absolute numbers by more than an order of magnitude. Four times the bytes
  12918. // costs about four times the time when parsing is linear, and about sixteen
  12919. // times when the body is buffered and rescanned.
  12920. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  12921. EXPECT_LT(ms_16mb, ms_4mb * 10)
  12922. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  12923. << "ms, which suggests the body is being buffered and rescanned";
  12924. }
  12925. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  12926. // A boundary can only be followed by CRLF or by "--", so anything else is
  12927. // malformed no matter what comes next. The parser must say so right away
  12928. // instead of buffering the rest of the declared body.
  12929. Server svr;
  12930. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  12931. res.set_content("ok", "text/plain");
  12932. });
  12933. auto port = svr.bind_to_any_port(HOST);
  12934. thread t = thread([&] { svr.listen_after_bind(); });
  12935. auto se = detail::scope_exit([&] {
  12936. svr.stop();
  12937. t.join();
  12938. ASSERT_FALSE(svr.is_running());
  12939. });
  12940. svr.wait_until_ready();
  12941. // Announce a 1 MB body but send only the malformed prefix. A parser that
  12942. // buffers instead of failing would still be waiting for the remaining bytes.
  12943. const std::string body = "--zzzz\r\n"
  12944. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12945. "\r\n"
  12946. "text1"
  12947. "\r\n--zzzzXX";
  12948. const std::string req = "POST /post HTTP/1.1\r\n"
  12949. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  12950. "Content-Length: 1048576\r\n"
  12951. "\r\n" +
  12952. body;
  12953. std::string response;
  12954. ASSERT_TRUE(send_request(3, req, &response, port));
  12955. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  12956. EXPECT_EQ("400", response.substr(9, 3));
  12957. }
  12958. // Posts a multipart body split into two writes, so that the server sees the
  12959. // split at whatever offset the caller chose, and expects the single "text1"
  12960. // field to come through.
  12961. static void expect_split_multipart_ok(const std::string &body1,
  12962. const std::string &body2) {
  12963. auto handled = false;
  12964. Server svr;
  12965. svr.Post("/post", [&](const Request &req, Response &) {
  12966. EXPECT_EQ(1u, req.form.fields.size());
  12967. EXPECT_EQ("text1", req.form.get_field("text1"));
  12968. handled = true;
  12969. });
  12970. auto port = svr.bind_to_any_port(HOST);
  12971. thread t = thread([&] { svr.listen_after_bind(); });
  12972. auto se = detail::scope_exit([&] {
  12973. svr.stop();
  12974. t.join();
  12975. ASSERT_FALSE(svr.is_running());
  12976. ASSERT_TRUE(handled);
  12977. });
  12978. svr.wait_until_ready();
  12979. // "Connection: close" makes the server close once it has answered, so the
  12980. // response drain ends immediately instead of idling until the read timeout.
  12981. const std::string head =
  12982. "POST /post HTTP/1.1\r\n"
  12983. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  12984. "Connection: close\r\n"
  12985. "Content-Length: " +
  12986. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  12987. std::string response;
  12988. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  12989. ASSERT_GE(response.size(), 12u) << "no response";
  12990. EXPECT_EQ("200", response.substr(9, 3));
  12991. }
  12992. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  12993. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  12994. // ignored, including when it does not arrive in the same read as the
  12995. // close-delimiter itself.
  12996. expect_split_multipart_ok("--zzzz\r\n"
  12997. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12998. "\r\n"
  12999. "text1"
  13000. "\r\n--zzzz--",
  13001. "\r\nthis epilogue must be ignored\r\n");
  13002. }
  13003. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  13004. // The initial boundary may be preceded by a preamble of any length and may
  13005. // straddle a read boundary. Discarding data while waiting for it must not
  13006. // throw away a partial boundary sitting at the end of the buffer.
  13007. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  13008. "zz\r\n"
  13009. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13010. "\r\n"
  13011. "text1"
  13012. "\r\n--zzzz--\r\n");
  13013. }
  13014. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  13015. // The received boundary was only checked for being non-empty, so it could be
  13016. // as long as a header is allowed to be. The parser scans the body for
  13017. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  13018. // costs a nearly full comparison at nearly every position, making the
  13019. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  13020. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  13021. Server svr;
  13022. svr.Post("/post", [](const Request &req, Response &res) {
  13023. EXPECT_EQ(1u, req.form.fields.size());
  13024. EXPECT_EQ("text1", req.form.get_field("text1"));
  13025. res.set_content("ok", "text/plain");
  13026. });
  13027. auto port = svr.bind_to_any_port(HOST);
  13028. thread t = thread([&] { svr.listen_after_bind(); });
  13029. auto se = detail::scope_exit([&] {
  13030. svr.stop();
  13031. t.join();
  13032. ASSERT_FALSE(svr.is_running());
  13033. });
  13034. svr.wait_until_ready();
  13035. Client cli(HOST, port);
  13036. auto post_with_boundary_of_length = [&](size_t len) {
  13037. const std::string boundary(len, 'a');
  13038. const std::string body =
  13039. "--" + boundary +
  13040. "\r\n"
  13041. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13042. "\r\n"
  13043. "text1"
  13044. "\r\n--" +
  13045. boundary + "--\r\n";
  13046. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  13047. };
  13048. auto res = post_with_boundary_of_length(70);
  13049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13050. EXPECT_EQ(StatusCode::OK_200, res->status);
  13051. res = post_with_boundary_of_length(71);
  13052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13053. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13054. }
  13055. TEST(MakeFileBodyTest, Basic) {
  13056. const std::string file_content(4096, 'Z');
  13057. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  13058. {
  13059. std::ofstream ofs(tmp_path, std::ios::binary);
  13060. ofs.write(file_content.data(),
  13061. static_cast<std::streamsize>(file_content.size()));
  13062. }
  13063. auto handled = false;
  13064. Server svr;
  13065. svr.Post("/upload", [&](const Request &req, Response &res) {
  13066. EXPECT_EQ(file_content, req.body);
  13067. handled = true;
  13068. res.status = StatusCode::OK_200;
  13069. });
  13070. auto port = svr.bind_to_any_port(HOST);
  13071. auto t = thread([&] { svr.listen_after_bind(); });
  13072. auto se = detail::scope_exit([&] {
  13073. svr.stop();
  13074. t.join();
  13075. ASSERT_FALSE(svr.is_running());
  13076. ASSERT_TRUE(handled);
  13077. std::remove(tmp_path.c_str());
  13078. });
  13079. svr.wait_until_ready();
  13080. auto fb = make_file_body(tmp_path);
  13081. ASSERT_GT(fb.first, 0u);
  13082. Client cli(HOST, port);
  13083. auto res =
  13084. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  13085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13086. EXPECT_EQ(StatusCode::OK_200, res->status);
  13087. }
  13088. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  13089. static constexpr unsigned int number_of_tasks{1000000};
  13090. std::atomic_uint count{0};
  13091. std::unique_ptr<TaskQueue> task_queue{
  13092. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  13093. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13094. auto queued = task_queue->enqueue(
  13095. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  13096. EXPECT_TRUE(queued);
  13097. }
  13098. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13099. task_queue->shutdown();
  13100. #else
  13101. EXPECT_NO_THROW(task_queue->shutdown());
  13102. #endif
  13103. EXPECT_EQ(number_of_tasks, count.load());
  13104. }
  13105. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  13106. static constexpr unsigned int number_of_tasks{1000000};
  13107. static constexpr unsigned int qlimit{2};
  13108. unsigned int queued_count{0};
  13109. std::atomic_uint count{0};
  13110. std::unique_ptr<TaskQueue> task_queue{
  13111. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  13112. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13113. if (task_queue->enqueue(
  13114. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  13115. queued_count++;
  13116. }
  13117. }
  13118. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13119. task_queue->shutdown();
  13120. #else
  13121. EXPECT_NO_THROW(task_queue->shutdown());
  13122. #endif
  13123. EXPECT_EQ(queued_count, count.load());
  13124. EXPECT_TRUE(queued_count <= number_of_tasks);
  13125. EXPECT_TRUE(queued_count >= qlimit);
  13126. }
  13127. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  13128. // Use a short idle timeout so a dynamic thread spawns, times out and
  13129. // exits during the test, and the pool keeps working afterwards.
  13130. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  13131. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  13132. /*idle_timeout_sec=*/1}};
  13133. std::atomic_uint count{0};
  13134. std::condition_variable cv;
  13135. std::mutex mtx;
  13136. bool release = false;
  13137. // Block the base thread so the second task spawns a dynamic thread.
  13138. EXPECT_TRUE(task_queue->enqueue([&] {
  13139. std::unique_lock<std::mutex> lock(mtx);
  13140. while (!release) {
  13141. cv.wait(lock);
  13142. }
  13143. count++;
  13144. }));
  13145. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13146. // Let the dynamic thread finish its task and exceed the idle timeout.
  13147. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  13148. {
  13149. std::unique_lock<std::mutex> lock(mtx);
  13150. release = true;
  13151. }
  13152. cv.notify_all();
  13153. // The pool must still accept and run tasks after the dynamic thread exited.
  13154. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13155. task_queue->shutdown();
  13156. EXPECT_EQ(3u, count.load());
  13157. }
  13158. TEST(TaskQueueTest, MaxQueuedRequests) {
  13159. static constexpr unsigned int qlimit{3};
  13160. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  13161. std::condition_variable sem_cv;
  13162. std::mutex sem_mtx;
  13163. int credits = 0;
  13164. bool queued;
  13165. /* Fill up the queue with tasks that will block until we give them credits to
  13166. * complete. */
  13167. for (unsigned int n = 0; n <= qlimit;) {
  13168. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  13169. std::unique_lock<std::mutex> lock(sem_mtx);
  13170. while (credits <= 0) {
  13171. sem_cv.wait(lock);
  13172. }
  13173. /* Consume the credit and signal the test code if they are all gone. */
  13174. if (--credits == 0) { sem_cv.notify_one(); }
  13175. });
  13176. if (n < qlimit) {
  13177. /* The first qlimit enqueues must succeed. */
  13178. EXPECT_TRUE(queued);
  13179. } else {
  13180. /* The last one will succeed only when the worker thread
  13181. * starts and dequeues the first blocking task. Although
  13182. * not necessary for the correctness of this test, we sleep for
  13183. * a short while to avoid busy waiting. */
  13184. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13185. }
  13186. if (queued) { n++; }
  13187. }
  13188. /* Further enqueues must fail since the queue is full. */
  13189. for (auto i = 0; i < 4; i++) {
  13190. queued = task_queue->enqueue([] {});
  13191. EXPECT_FALSE(queued);
  13192. }
  13193. /* Give the credits to allow the previous tasks to complete. */
  13194. {
  13195. std::unique_lock<std::mutex> lock(sem_mtx);
  13196. credits += qlimit + 1;
  13197. }
  13198. sem_cv.notify_all();
  13199. /* Wait for all the credits to be consumed. */
  13200. {
  13201. std::unique_lock<std::mutex> lock(sem_mtx);
  13202. while (credits > 0) {
  13203. sem_cv.wait(lock);
  13204. }
  13205. }
  13206. /* Check that we are able again to enqueue at least qlimit tasks. */
  13207. for (unsigned int i = 0; i < qlimit; i++) {
  13208. queued = task_queue->enqueue([] {});
  13209. EXPECT_TRUE(queued);
  13210. }
  13211. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13212. task_queue->shutdown();
  13213. #else
  13214. EXPECT_NO_THROW(task_queue->shutdown());
  13215. #endif
  13216. }
  13217. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  13218. Server svr;
  13219. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13220. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  13221. });
  13222. svr.Get("/hello", [](const Request &req, Response &res) {
  13223. res.set_content(req.get_param_value("key"), "text/plain");
  13224. });
  13225. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13226. auto se = detail::scope_exit([&] {
  13227. svr.stop();
  13228. thread.join();
  13229. ASSERT_FALSE(svr.is_running());
  13230. });
  13231. svr.wait_until_ready();
  13232. {
  13233. Client cli(HOST, PORT);
  13234. cli.set_follow_location(true);
  13235. auto res = cli.Get("/");
  13236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13237. EXPECT_EQ(StatusCode::OK_200, res->status);
  13238. EXPECT_EQ("val&key2=val2", res->body);
  13239. }
  13240. }
  13241. #endif
  13242. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  13243. Server svr;
  13244. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13245. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  13246. });
  13247. svr.Get("/hello", [](const Request &req, Response &res) {
  13248. res.set_content(req.get_param_value("key"), "text/plain");
  13249. });
  13250. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13251. auto se = detail::scope_exit([&] {
  13252. svr.stop();
  13253. thread.join();
  13254. ASSERT_FALSE(svr.is_running());
  13255. });
  13256. svr.wait_until_ready();
  13257. {
  13258. Client cli(HOST, PORT);
  13259. cli.set_follow_location(true);
  13260. auto res = cli.Get("/");
  13261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13262. EXPECT_EQ(StatusCode::OK_200, res->status);
  13263. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  13264. }
  13265. }
  13266. TEST(RedirectTest, RedirectWithPlusInPath) {
  13267. Server svr;
  13268. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13269. res.set_redirect("/a+b");
  13270. });
  13271. // Route pattern uses regex; escape + as \\+
  13272. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  13273. res.set_content(req.path, "text/plain");
  13274. });
  13275. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13276. auto se = detail::scope_exit([&] {
  13277. svr.stop();
  13278. thread.join();
  13279. ASSERT_FALSE(svr.is_running());
  13280. });
  13281. svr.wait_until_ready();
  13282. {
  13283. Client cli(HOST, PORT);
  13284. cli.set_follow_location(true);
  13285. auto res = cli.Get("/");
  13286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13287. EXPECT_EQ(StatusCode::OK_200, res->status);
  13288. EXPECT_EQ("/a+b", res->body);
  13289. }
  13290. }
  13291. #ifdef CPPHTTPLIB_SSL_ENABLED
  13292. TEST(RedirectTest, Issue2185_Online) {
  13293. SSLClient client("github.com");
  13294. client.set_follow_location(true);
  13295. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  13296. "Coollab-Windows.zip");
  13297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13298. EXPECT_EQ(StatusCode::OK_200, res->status);
  13299. EXPECT_EQ(9920427U, res->body.size());
  13300. }
  13301. #endif
  13302. TEST(VulnerabilityTest, CRLFInjection) {
  13303. Server svr;
  13304. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  13305. res.set_content("Hello 1", "text/plain");
  13306. });
  13307. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  13308. res.set_content("Hello 2", "text/plain");
  13309. });
  13310. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  13311. res.set_content("Hello 3", "text/plain");
  13312. });
  13313. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  13314. res.set_content("Hello 4", "text/plain");
  13315. });
  13316. svr.set_logger([](const Request &req, const Response & /*res*/) {
  13317. for (const auto &x : req.headers) {
  13318. auto key = x.first;
  13319. EXPECT_STRNE("evil", key.c_str());
  13320. }
  13321. });
  13322. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13323. auto se = detail::scope_exit([&] {
  13324. svr.stop();
  13325. thread.join();
  13326. ASSERT_FALSE(svr.is_running());
  13327. });
  13328. svr.wait_until_ready();
  13329. {
  13330. Client cli(HOST, PORT);
  13331. cli.Post("/test1", "A=B",
  13332. "application/x-www-form-urlencoded\r\nevil: hello1");
  13333. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  13334. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  13335. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  13336. }
  13337. }
  13338. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  13339. auto server_thread = std::thread([] {
  13340. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13341. default_socket_options(srv);
  13342. sockaddr_in addr{};
  13343. addr.sin_family = AF_INET;
  13344. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  13345. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13346. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13347. ::listen(srv, 1);
  13348. sockaddr_in cli_addr{};
  13349. socklen_t cli_len = sizeof(cli_addr);
  13350. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13351. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  13352. std::string buf_all;
  13353. char buf[2048];
  13354. ssize_t n;
  13355. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  13356. buf_all.append(buf, static_cast<size_t>(n));
  13357. size_t pos;
  13358. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  13359. auto request_block = buf_all.substr(0, pos + 4); // include separator
  13360. auto e = request_block.find("\r\n");
  13361. if (e != std::string::npos) {
  13362. auto request_line = request_block.substr(0, e);
  13363. std::string msg =
  13364. "CRLF injection detected in request line: '" + request_line + "'";
  13365. EXPECT_FALSE(true) << msg;
  13366. }
  13367. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  13368. ::send(cli,
  13369. #ifdef _WIN32
  13370. static_cast<const char *>(resp.c_str()),
  13371. static_cast<int>(resp.size()),
  13372. #else
  13373. resp.c_str(), resp.size(),
  13374. #endif
  13375. 0);
  13376. buf_all.erase(0, pos + 4);
  13377. }
  13378. }
  13379. detail::close_socket(cli);
  13380. detail::close_socket(srv);
  13381. });
  13382. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13383. auto cli = Client("127.0.0.1", PORT + 1);
  13384. auto headers = Headers{
  13385. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  13386. {"Connection", "keep-alive"}};
  13387. auto res = cli.Get("/hi", headers);
  13388. EXPECT_FALSE(res);
  13389. EXPECT_EQ(Error::InvalidHeaders, res.error());
  13390. server_thread.join();
  13391. }
  13392. TEST(PathParamsTest, StaticMatch) {
  13393. const auto pattern = "/users/all";
  13394. detail::PathParamsMatcher matcher(pattern);
  13395. Request request;
  13396. request.path = "/users/all";
  13397. ASSERT_TRUE(matcher.match(request));
  13398. std::unordered_map<std::string, std::string> expected_params = {};
  13399. EXPECT_EQ(request.path_params, expected_params);
  13400. }
  13401. TEST(PathParamsTest, StaticMismatch) {
  13402. const auto pattern = "/users/all";
  13403. detail::PathParamsMatcher matcher(pattern);
  13404. Request request;
  13405. request.path = "/users/1";
  13406. ASSERT_FALSE(matcher.match(request));
  13407. }
  13408. TEST(PathParamsTest, SingleParamInTheMiddle) {
  13409. const auto pattern = "/users/:id/subscriptions";
  13410. detail::PathParamsMatcher matcher(pattern);
  13411. Request request;
  13412. request.path = "/users/42/subscriptions";
  13413. ASSERT_TRUE(matcher.match(request));
  13414. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13415. EXPECT_EQ(request.path_params, expected_params);
  13416. }
  13417. TEST(PathParamsTest, SingleParamInTheEnd) {
  13418. const auto pattern = "/users/:id";
  13419. detail::PathParamsMatcher matcher(pattern);
  13420. Request request;
  13421. request.path = "/users/24";
  13422. ASSERT_TRUE(matcher.match(request));
  13423. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  13424. EXPECT_EQ(request.path_params, expected_params);
  13425. }
  13426. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  13427. const auto pattern = "/users/:id/";
  13428. detail::PathParamsMatcher matcher(pattern);
  13429. Request request;
  13430. request.path = "/users/42/";
  13431. ASSERT_TRUE(matcher.match(request));
  13432. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13433. EXPECT_EQ(request.path_params, expected_params);
  13434. }
  13435. TEST(PathParamsTest, EmptyParam) {
  13436. const auto pattern = "/users/:id/";
  13437. detail::PathParamsMatcher matcher(pattern);
  13438. Request request;
  13439. request.path = "/users//";
  13440. ASSERT_TRUE(matcher.match(request));
  13441. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  13442. EXPECT_EQ(request.path_params, expected_params);
  13443. }
  13444. TEST(PathParamsTest, FragmentMismatch) {
  13445. const auto pattern = "/users/:id/";
  13446. detail::PathParamsMatcher matcher(pattern);
  13447. Request request;
  13448. request.path = "/admins/24/";
  13449. ASSERT_FALSE(matcher.match(request));
  13450. }
  13451. TEST(PathParamsTest, ExtraFragments) {
  13452. const auto pattern = "/users/:id";
  13453. detail::PathParamsMatcher matcher(pattern);
  13454. Request request;
  13455. request.path = "/users/42/subscriptions";
  13456. ASSERT_FALSE(matcher.match(request));
  13457. }
  13458. TEST(PathParamsTest, MissingTrailingParam) {
  13459. const auto pattern = "/users/:id";
  13460. detail::PathParamsMatcher matcher(pattern);
  13461. Request request;
  13462. request.path = "/users";
  13463. ASSERT_FALSE(matcher.match(request));
  13464. }
  13465. TEST(PathParamsTest, MissingParamInTheMiddle) {
  13466. const auto pattern = "/users/:id/subscriptions";
  13467. detail::PathParamsMatcher matcher(pattern);
  13468. Request request;
  13469. request.path = "/users/subscriptions";
  13470. ASSERT_FALSE(matcher.match(request));
  13471. }
  13472. TEST(PathParamsTest, MultipleParams) {
  13473. const auto pattern = "/users/:userid/subscriptions/:subid";
  13474. detail::PathParamsMatcher matcher(pattern);
  13475. Request request;
  13476. request.path = "/users/42/subscriptions/2";
  13477. ASSERT_TRUE(matcher.match(request));
  13478. std::unordered_map<std::string, std::string> expected_params = {
  13479. {"userid", "42"}, {"subid", "2"}};
  13480. EXPECT_EQ(request.path_params, expected_params);
  13481. }
  13482. TEST(PathParamsTest, SequenceOfParams) {
  13483. const auto pattern = "/values/:x/:y/:z";
  13484. detail::PathParamsMatcher matcher(pattern);
  13485. Request request;
  13486. request.path = "/values/1/2/3";
  13487. ASSERT_TRUE(matcher.match(request));
  13488. std::unordered_map<std::string, std::string> expected_params = {
  13489. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  13490. EXPECT_EQ(request.path_params, expected_params);
  13491. }
  13492. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  13493. const auto pattern = "/prefix:suffix";
  13494. detail::PathParamsMatcher matcher(pattern);
  13495. Request request;
  13496. request.path = "/prefix:suffix";
  13497. ASSERT_TRUE(matcher.match(request));
  13498. const std::unordered_map<std::string, std::string> expected_params = {};
  13499. EXPECT_EQ(request.path_params, expected_params);
  13500. }
  13501. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  13502. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  13503. // calling thread's stack on a long enough path for a quantified pattern;
  13504. // RegexMatcher must refuse to run regex matching on paths beyond
  13505. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  13506. detail::RegexMatcher matcher("/files/(.*)");
  13507. Request within_limit;
  13508. within_limit.path = "/files/" + std::string(10, 'A');
  13509. EXPECT_TRUE(matcher.match(within_limit));
  13510. Request over_limit;
  13511. over_limit.path =
  13512. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  13513. EXPECT_FALSE(matcher.match(over_limit));
  13514. }
  13515. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  13516. Server svr;
  13517. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  13518. res.set_content("ok", "text/plain");
  13519. });
  13520. auto port = svr.bind_to_any_port(HOST);
  13521. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13522. auto se = detail::scope_exit([&] {
  13523. svr.stop();
  13524. thread.join();
  13525. ASSERT_FALSE(svr.is_running());
  13526. });
  13527. svr.wait_until_ready();
  13528. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  13529. // request URI limit; this used to be able to crash the process.
  13530. std::string path =
  13531. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  13532. std::string req = "GET " + path +
  13533. " HTTP/1.1\r\n"
  13534. "Host: " +
  13535. std::string(HOST) + ":" + std::to_string(port) +
  13536. "\r\n"
  13537. "Connection: close\r\n"
  13538. "\r\n";
  13539. std::string response;
  13540. ASSERT_TRUE(send_request(5, req, &response, port));
  13541. EXPECT_NE(std::string::npos, response.find("404"));
  13542. }
  13543. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  13544. Server svr;
  13545. auto handler = [](const Request & /*req*/, Response &res) {
  13546. res.set_content("hit", "text/plain");
  13547. };
  13548. // No regex metacharacter, so this one is compared literally
  13549. svr.Get("/literal/route", handler);
  13550. // '.' is a regex metacharacter, so this one must keep regex semantics
  13551. svr.Get("/a.c", handler);
  13552. auto port = svr.bind_to_any_port(HOST);
  13553. std::thread t([&]() { svr.listen_after_bind(); });
  13554. auto se = detail::scope_exit([&] {
  13555. svr.stop();
  13556. t.join();
  13557. ASSERT_FALSE(svr.is_running());
  13558. });
  13559. svr.wait_until_ready();
  13560. Client cli(HOST, port);
  13561. struct {
  13562. const char *path;
  13563. int status;
  13564. } cases[] = {
  13565. {"/literal/route", StatusCode::OK_200},
  13566. {"/literal/routes", StatusCode::NotFound_404},
  13567. {"/literal/rout", StatusCode::NotFound_404},
  13568. {"/abc", StatusCode::OK_200},
  13569. {"/a.c", StatusCode::OK_200},
  13570. };
  13571. for (const auto &x : cases) {
  13572. auto res = cli.Get(x.path);
  13573. ASSERT_TRUE(res) << x.path;
  13574. EXPECT_EQ(x.status, res->status) << x.path;
  13575. }
  13576. }
  13577. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  13578. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  13579. // from exhausting the stack, so it must only constrain routes that actually
  13580. // run a regular expression. A literal route is matched by comparison and
  13581. // stays usable at any length.
  13582. Server svr;
  13583. const std::string pattern =
  13584. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  13585. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  13586. res.set_content("hit", "text/plain");
  13587. });
  13588. auto port = svr.bind_to_any_port(HOST);
  13589. std::thread t([&]() { svr.listen_after_bind(); });
  13590. auto se = detail::scope_exit([&] {
  13591. svr.stop();
  13592. t.join();
  13593. ASSERT_FALSE(svr.is_running());
  13594. });
  13595. svr.wait_until_ready();
  13596. Client cli(HOST, port);
  13597. auto res = cli.Get(pattern);
  13598. ASSERT_TRUE(res);
  13599. EXPECT_EQ(StatusCode::OK_200, res->status);
  13600. }
  13601. TEST(ParseUrlTest, VariousPatterns) {
  13602. {
  13603. detail::UrlComponents uc;
  13604. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  13605. EXPECT_EQ("http", uc.scheme);
  13606. EXPECT_EQ("example.com", uc.host);
  13607. EXPECT_EQ("8080", uc.port);
  13608. EXPECT_EQ("/path", uc.path);
  13609. EXPECT_EQ("?q=1", uc.query);
  13610. }
  13611. {
  13612. detail::UrlComponents uc;
  13613. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  13614. EXPECT_EQ("https", uc.scheme);
  13615. EXPECT_EQ("example.com", uc.host);
  13616. EXPECT_TRUE(uc.port.empty());
  13617. EXPECT_EQ("/path", uc.path);
  13618. }
  13619. {
  13620. detail::UrlComponents uc;
  13621. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  13622. EXPECT_EQ("::1", uc.host);
  13623. EXPECT_EQ("8080", uc.port);
  13624. EXPECT_EQ("/path", uc.path);
  13625. }
  13626. {
  13627. detail::UrlComponents uc;
  13628. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  13629. }
  13630. {
  13631. // Bytes after the IPv6 literal must be a delimiter, not folded into
  13632. // the path while the connection still targets the bracketed host.
  13633. detail::UrlComponents uc;
  13634. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  13635. }
  13636. {
  13637. detail::UrlComponents uc;
  13638. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  13639. }
  13640. {
  13641. detail::UrlComponents uc;
  13642. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  13643. EXPECT_EQ("::1", uc.host);
  13644. EXPECT_TRUE(uc.port.empty());
  13645. EXPECT_EQ("/path", uc.path);
  13646. }
  13647. {
  13648. detail::UrlComponents uc;
  13649. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  13650. EXPECT_TRUE(uc.scheme.empty());
  13651. EXPECT_EQ("example.com", uc.host);
  13652. EXPECT_EQ("/path", uc.path);
  13653. EXPECT_EQ("?q=1", uc.query);
  13654. }
  13655. {
  13656. detail::UrlComponents uc;
  13657. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  13658. EXPECT_TRUE(uc.host.empty());
  13659. EXPECT_EQ("/path", uc.path);
  13660. EXPECT_EQ("?q=1", uc.query);
  13661. }
  13662. {
  13663. detail::UrlComponents uc;
  13664. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  13665. EXPECT_EQ("example.com", uc.host);
  13666. EXPECT_EQ("8080", uc.port);
  13667. }
  13668. {
  13669. // Unix socket path — must not be parsed as host
  13670. detail::UrlComponents uc;
  13671. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  13672. EXPECT_TRUE(uc.host.empty());
  13673. }
  13674. {
  13675. detail::UrlComponents uc;
  13676. ASSERT_TRUE(detail::parse_url("", uc));
  13677. EXPECT_TRUE(uc.host.empty());
  13678. EXPECT_TRUE(uc.path.empty());
  13679. }
  13680. {
  13681. detail::UrlComponents uc;
  13682. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  13683. }
  13684. {
  13685. detail::UrlComponents uc;
  13686. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  13687. }
  13688. {
  13689. // Accepted by parse_url; callers restrict to http/https
  13690. detail::UrlComponents uc;
  13691. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  13692. EXPECT_EQ("ftp", uc.scheme);
  13693. }
  13694. {
  13695. detail::UrlComponents uc;
  13696. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  13697. }
  13698. {
  13699. detail::UrlComponents uc;
  13700. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  13701. }
  13702. }
  13703. TEST(ParseUrlTest, FragmentHandling) {
  13704. {
  13705. detail::UrlComponents uc;
  13706. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  13707. EXPECT_EQ("/path", uc.path);
  13708. EXPECT_TRUE(uc.query.empty());
  13709. }
  13710. {
  13711. detail::UrlComponents uc;
  13712. ASSERT_TRUE(detail::parse_url("#frag", uc));
  13713. EXPECT_TRUE(uc.path.empty());
  13714. EXPECT_TRUE(uc.query.empty());
  13715. }
  13716. }
  13717. TEST(ParseUrlTest, UserinfoHandling) {
  13718. // Userinfo with @ but no colon — host includes @
  13719. detail::UrlComponents uc;
  13720. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  13721. EXPECT_EQ("user@host.com", uc.host);
  13722. EXPECT_EQ("/path", uc.path);
  13723. }
  13724. TEST(ParseUrlTest, IPv6EdgeCases) {
  13725. {
  13726. detail::UrlComponents uc;
  13727. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  13728. EXPECT_TRUE(uc.scheme.empty());
  13729. EXPECT_EQ("::1", uc.host);
  13730. EXPECT_EQ("8080", uc.port);
  13731. }
  13732. {
  13733. // Zone ID '%25' is not in [a-fA-F0-9:]
  13734. detail::UrlComponents uc;
  13735. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  13736. }
  13737. }
  13738. TEST(ParseUrlTest, SchemeEdgeCases) {
  13739. {
  13740. detail::UrlComponents uc;
  13741. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  13742. }
  13743. {
  13744. detail::UrlComponents uc;
  13745. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  13746. }
  13747. {
  13748. detail::UrlComponents uc;
  13749. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  13750. }
  13751. }
  13752. TEST(ParseUrlTest, PortEdgeCases) {
  13753. {
  13754. detail::UrlComponents uc;
  13755. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  13756. EXPECT_TRUE(uc.port.empty());
  13757. EXPECT_EQ("/path", uc.path);
  13758. }
  13759. {
  13760. // parse_url accepts any port string; validation is done by parse_port
  13761. detail::UrlComponents uc;
  13762. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  13763. EXPECT_EQ("abc", uc.port);
  13764. }
  13765. }
  13766. TEST(ParseUrlTest, WebSocketPatterns) {
  13767. {
  13768. detail::UrlComponents uc;
  13769. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  13770. EXPECT_EQ("ws", uc.scheme);
  13771. EXPECT_EQ("echo.example.com", uc.host);
  13772. EXPECT_EQ("8080", uc.port);
  13773. EXPECT_EQ("/ws", uc.path);
  13774. }
  13775. {
  13776. detail::UrlComponents uc;
  13777. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  13778. EXPECT_EQ("wss", uc.scheme);
  13779. EXPECT_EQ("echo.example.com", uc.host);
  13780. EXPECT_TRUE(uc.port.empty());
  13781. EXPECT_EQ("/ws", uc.path);
  13782. }
  13783. }
  13784. TEST(ParseUrlTest, QueryOnly) {
  13785. detail::UrlComponents uc;
  13786. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  13787. EXPECT_TRUE(uc.host.empty());
  13788. EXPECT_TRUE(uc.path.empty());
  13789. EXPECT_EQ("?q=1&r=2", uc.query);
  13790. }
  13791. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13792. detail::UrlComponents uc;
  13793. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13794. EXPECT_TRUE(uc.scheme.empty());
  13795. EXPECT_EQ("example.com", uc.host);
  13796. EXPECT_EQ("443", uc.port);
  13797. EXPECT_EQ("/path", uc.path);
  13798. }
  13799. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13800. // If ipv6 regex working, regex match codepath is taken.
  13801. // else port will default to 80 in Client impl
  13802. int clientImplMagicPort = 80;
  13803. int port = 4321;
  13804. // above ports must be different to avoid false negative
  13805. EXPECT_NE(clientImplMagicPort, port);
  13806. std::string ipV6TestURL = "http://[ff06::c3]";
  13807. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13808. CLIENT_PRIVATE_KEY_FILE);
  13809. EXPECT_EQ(cli.port(), port);
  13810. }
  13811. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13812. auto file_path = "./www/dir/index.html";
  13813. auto dir_path = "./www/dir";
  13814. detail::FileStat stat_file(file_path);
  13815. EXPECT_TRUE(stat_file.is_file());
  13816. EXPECT_FALSE(stat_file.is_dir());
  13817. detail::FileStat stat_dir(dir_path);
  13818. EXPECT_FALSE(stat_dir.is_file());
  13819. EXPECT_TRUE(stat_dir.is_dir());
  13820. }
  13821. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13822. // IPv4 with default HTTP port (80)
  13823. EXPECT_EQ("example.com",
  13824. detail::make_host_and_port_string("example.com", 80, false));
  13825. // IPv4 with default HTTPS port (443)
  13826. EXPECT_EQ("example.com",
  13827. detail::make_host_and_port_string("example.com", 443, true));
  13828. // IPv4 with non-default HTTP port
  13829. EXPECT_EQ("example.com:8080",
  13830. detail::make_host_and_port_string("example.com", 8080, false));
  13831. // IPv4 with non-default HTTPS port
  13832. EXPECT_EQ("example.com:8443",
  13833. detail::make_host_and_port_string("example.com", 8443, true));
  13834. // IPv6 with default HTTP port (80)
  13835. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13836. // IPv6 with default HTTPS port (443)
  13837. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13838. // IPv6 with non-default HTTP port
  13839. EXPECT_EQ("[::1]:8080",
  13840. detail::make_host_and_port_string("::1", 8080, false));
  13841. // IPv6 with non-default HTTPS port
  13842. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13843. // IPv6 full address with default port
  13844. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13845. detail::make_host_and_port_string(
  13846. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13847. // IPv6 full address with non-default port
  13848. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13849. detail::make_host_and_port_string(
  13850. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13851. // IPv6 localhost with non-default port
  13852. EXPECT_EQ("[::1]:3000",
  13853. detail::make_host_and_port_string("::1", 3000, false));
  13854. // IPv6 with zone ID (link-local address) with default port
  13855. EXPECT_EQ("[fe80::1%eth0]",
  13856. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13857. // IPv6 with zone ID (link-local address) with non-default port
  13858. EXPECT_EQ("[fe80::1%eth0]:8080",
  13859. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13860. // Edge case: Port 443 with is_ssl=false (should add port)
  13861. EXPECT_EQ("example.com:443",
  13862. detail::make_host_and_port_string("example.com", 443, false));
  13863. // Edge case: Port 80 with is_ssl=true (should add port)
  13864. EXPECT_EQ("example.com:80",
  13865. detail::make_host_and_port_string("example.com", 80, true));
  13866. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13867. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13868. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13869. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13870. // Security fix: Already bracketed IPv6 should not get double brackets
  13871. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13872. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13873. EXPECT_EQ("[::1]:8080",
  13874. detail::make_host_and_port_string("[::1]", 8080, false));
  13875. EXPECT_EQ("[2001:db8::1]:8080",
  13876. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13877. EXPECT_EQ("[fe80::1%eth0]",
  13878. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13879. EXPECT_EQ("[fe80::1%eth0]:8080",
  13880. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13881. // Edge case: Empty host (should return as-is)
  13882. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13883. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13884. // This is a known limitation but shouldn't crash
  13885. EXPECT_EQ("[host:name]",
  13886. detail::make_host_and_port_string("host:name", 80, false));
  13887. // Port number edge cases (no validation, but should not crash)
  13888. EXPECT_EQ("example.com:0",
  13889. detail::make_host_and_port_string("example.com", 0, false));
  13890. EXPECT_EQ("example.com:-1",
  13891. detail::make_host_and_port_string("example.com", -1, false));
  13892. EXPECT_EQ("example.com:65535",
  13893. detail::make_host_and_port_string("example.com", 65535, false));
  13894. EXPECT_EQ("example.com:65536",
  13895. detail::make_host_and_port_string("example.com", 65536, false));
  13896. }
  13897. #ifdef CPPHTTPLIB_SSL_ENABLED
  13898. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13899. httplib::SSLClient cli("roblox.com", 443);
  13900. cli.set_follow_location(true);
  13901. auto res = cli.Get("/");
  13902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13903. EXPECT_EQ(StatusCode::OK_200, res->status);
  13904. }
  13905. #endif
  13906. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13907. Server svr;
  13908. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13909. EXPECT_EQ(res.status, 400);
  13910. });
  13911. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13912. auto se = detail::scope_exit([&] {
  13913. svr.stop();
  13914. thread.join();
  13915. ASSERT_FALSE(svr.is_running());
  13916. });
  13917. svr.wait_until_ready();
  13918. Client cli(HOST, PORT);
  13919. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13920. }
  13921. TEST(InvalidHeaderCharsTest, is_field_name) {
  13922. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13923. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13924. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13925. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13926. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13927. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13928. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13929. EXPECT_FALSE(detail::fields::is_field_name(""));
  13930. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13931. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13932. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13933. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13934. }
  13935. TEST(InvalidHeaderCharsTest, is_field_value) {
  13936. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13937. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13938. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13939. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13940. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13941. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13942. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13943. EXPECT_TRUE(detail::fields::is_field_value(""));
  13944. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13945. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13946. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13947. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13948. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13949. }
  13950. TEST(InvalidHeaderCharsTest, OnServer) {
  13951. Server svr;
  13952. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13953. std::string header = "Not Set";
  13954. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13955. res.set_header(header, "value");
  13956. res.set_content("Page Content Page Content", "text/plain");
  13957. });
  13958. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13959. std::string header = "Not Set";
  13960. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13961. res.set_header("X-Test", header);
  13962. res.set_content("Page Content Page Content", "text/plain");
  13963. });
  13964. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13965. auto se = detail::scope_exit([&] {
  13966. svr.stop();
  13967. thread.join();
  13968. ASSERT_FALSE(svr.is_running());
  13969. });
  13970. svr.wait_until_ready();
  13971. Client cli(HOST, PORT);
  13972. {
  13973. auto res = cli.Get(
  13974. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13976. EXPECT_EQ("Page Content Page Content", res->body);
  13977. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13978. }
  13979. {
  13980. auto res = cli.Get(
  13981. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13983. EXPECT_EQ("Page Content Page Content", res->body);
  13984. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13985. }
  13986. }
  13987. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13988. auto handled = false;
  13989. Server svr;
  13990. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13991. thread t = thread([&] { svr.listen(HOST, PORT); });
  13992. auto se = detail::scope_exit([&] {
  13993. svr.stop();
  13994. t.join();
  13995. ASSERT_FALSE(svr.is_running());
  13996. ASSERT_FALSE(handled);
  13997. });
  13998. svr.wait_until_ready();
  13999. auto req = "POST /test HTTP/1.1\r\n"
  14000. "Content-Length: x\r\n"
  14001. "\r\n";
  14002. std::string response;
  14003. ASSERT_TRUE(send_request(1, req, &response));
  14004. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14005. response.substr(0, response.find("\r\n")));
  14006. }
  14007. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  14008. // case-insensitive, and a server that receives a 100-continue expectation in
  14009. // an HTTP/1.0 request MUST ignore it.
  14010. static void probe_expect(int port, const std::string &req, bool *got_100) {
  14011. std::string response;
  14012. ASSERT_TRUE(send_request(1, req, &response, port));
  14013. *got_100 = response.find("100 Continue") != std::string::npos;
  14014. }
  14015. class ExpectTokenTest : public ::testing::Test {
  14016. protected:
  14017. void SetUp() override {
  14018. svr_.Post("/p", [](const Request &, Response &res) {
  14019. res.set_content("ok", "text/plain");
  14020. });
  14021. port_ = svr_.bind_to_any_port(HOST);
  14022. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14023. svr_.wait_until_ready();
  14024. }
  14025. void TearDown() override {
  14026. svr_.stop();
  14027. if (thread_.joinable()) { thread_.join(); }
  14028. }
  14029. std::string request(const char *version, const char *expect_value) const {
  14030. return std::string("POST /p ") + version +
  14031. "\r\n"
  14032. "Host: localhost\r\n"
  14033. "Content-Length: 2\r\n"
  14034. "Connection: close\r\n"
  14035. "Expect: " +
  14036. expect_value +
  14037. "\r\n"
  14038. "\r\n"
  14039. "hi";
  14040. }
  14041. Server svr_;
  14042. int port_ = 0;
  14043. thread thread_;
  14044. };
  14045. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  14046. bool got_100 = false;
  14047. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  14048. EXPECT_TRUE(got_100);
  14049. }
  14050. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  14051. bool got_100 = true;
  14052. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  14053. EXPECT_FALSE(got_100);
  14054. }
  14055. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  14056. bool got_100 = false;
  14057. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  14058. EXPECT_TRUE(got_100);
  14059. }
  14060. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  14061. bool got_100 = false;
  14062. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  14063. EXPECT_TRUE(got_100);
  14064. }
  14065. #ifndef _WIN32
  14066. TEST(Expect100ContinueTest, ServerClosesConnection) {
  14067. static constexpr char reject[] = "Unauthorized";
  14068. static constexpr char accept[] = "Upload accepted";
  14069. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  14070. Server svr;
  14071. svr.set_expect_100_continue_handler(
  14072. [](const Request & /*req*/, Response &res) {
  14073. res.status = StatusCode::Unauthorized_401;
  14074. res.set_content(reject, "text/plain");
  14075. return res.status;
  14076. });
  14077. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  14078. res.set_content(accept, "text/plain");
  14079. });
  14080. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14081. auto se = detail::scope_exit([&] {
  14082. svr.stop();
  14083. thread.join();
  14084. ASSERT_FALSE(svr.is_running());
  14085. });
  14086. svr.wait_until_ready();
  14087. {
  14088. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  14089. curl_easy_init(), &curl_easy_cleanup};
  14090. ASSERT_NE(curl, nullptr);
  14091. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  14092. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  14093. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  14094. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  14095. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  14096. &curl_slist_free_all};
  14097. ASSERT_NE(list, nullptr);
  14098. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  14099. struct read_data {
  14100. size_t read_size;
  14101. size_t total_size;
  14102. } data = {0, total_size};
  14103. using read_callback_t =
  14104. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14105. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  14106. void *userdata) -> size_t {
  14107. read_data *d = (read_data *)userdata;
  14108. if (!userdata || d->read_size >= d->total_size) { return 0; }
  14109. std::fill_n(ptr, size * nmemb, 'A');
  14110. d->read_size += size * nmemb;
  14111. return size * nmemb;
  14112. };
  14113. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  14114. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  14115. std::vector<char> buffer;
  14116. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  14117. using write_callback_t =
  14118. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14119. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  14120. void *userdata) -> size_t {
  14121. std::vector<char> *buf = (std::vector<char> *)userdata;
  14122. buf->reserve(buf->size() + size * nmemb + 1);
  14123. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  14124. return size * nmemb;
  14125. };
  14126. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  14127. {
  14128. const auto res = curl_easy_perform(curl.get());
  14129. ASSERT_EQ(res, CURLE_OK);
  14130. }
  14131. {
  14132. auto response_code = long{};
  14133. const auto res =
  14134. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  14135. ASSERT_EQ(res, CURLE_OK);
  14136. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  14137. }
  14138. {
  14139. auto dl = curl_off_t{};
  14140. const auto res =
  14141. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  14142. ASSERT_EQ(res, CURLE_OK);
  14143. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  14144. }
  14145. {
  14146. buffer.push_back('\0');
  14147. ASSERT_STRCASEEQ(buffer.data(), reject);
  14148. }
  14149. }
  14150. }
  14151. #endif
  14152. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  14153. // Regression test for #2458.
  14154. //
  14155. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  14156. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  14157. // ticket can make the client socket spuriously readable during the
  14158. // 100-continue wait. If the readiness is mistaken for an incoming response,
  14159. // the client withholds the body and then blocks reading a response that never
  14160. // comes, failing with `Failed to read connection`.
  14161. //
  14162. // A correct client (like curl) sends the body once no `100 Continue` arrives
  14163. // within the timeout. This raw OpenSSL server deliberately never sends
  14164. // `100 Continue`; the client must still deliver the body and receive 200.
  14165. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  14166. signal(SIGPIPE, SIG_IGN);
  14167. const auto port = PORT + 4;
  14168. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14169. ASSERT_NE(srv, INVALID_SOCKET);
  14170. int opt = 1;
  14171. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  14172. sockaddr_in addr{};
  14173. addr.sin_family = AF_INET;
  14174. addr.sin_port = htons(static_cast<uint16_t>(port));
  14175. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14176. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14177. ASSERT_EQ(0, ::listen(srv, 1));
  14178. std::atomic<size_t> server_body_bytes{0};
  14179. auto server_thread = std::thread([&] {
  14180. sockaddr_in cli_addr{};
  14181. socklen_t cli_len = sizeof(cli_addr);
  14182. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14183. if (cli == INVALID_SOCKET) { return; }
  14184. // Bound the lifetime of the server side so a buggy client (which never
  14185. // sends the body) cannot make this thread block forever on join.
  14186. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  14187. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14188. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  14189. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  14190. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  14191. SSL *ssl = SSL_new(ctx);
  14192. SSL_set_fd(ssl, static_cast<int>(cli));
  14193. if (SSL_accept(ssl) > 0) {
  14194. // Read the request headers. Reading here also flushes the TLS 1.3
  14195. // session tickets to the client. Deliberately do NOT send
  14196. // `100 Continue`.
  14197. std::string buf;
  14198. char tmp[1024];
  14199. while (buf.find("\r\n\r\n") == std::string::npos) {
  14200. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14201. if (n <= 0) { break; }
  14202. buf.append(tmp, static_cast<size_t>(n));
  14203. }
  14204. // A correct client sends the body now; count what arrives.
  14205. auto pos = buf.find("\r\n\r\n");
  14206. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  14207. while (body < 4096) {
  14208. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14209. if (n <= 0) { break; }
  14210. body += static_cast<size_t>(n);
  14211. }
  14212. server_body_bytes = body;
  14213. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  14214. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  14215. SSL_shutdown(ssl);
  14216. }
  14217. SSL_free(ssl);
  14218. detail::close_socket(cli);
  14219. SSL_CTX_free(ctx);
  14220. });
  14221. auto se = detail::scope_exit([&] {
  14222. server_thread.join();
  14223. detail::close_socket(srv);
  14224. });
  14225. SSLClient cli("127.0.0.1", port);
  14226. cli.enable_server_certificate_verification(false);
  14227. cli.set_connection_timeout(5, 0);
  14228. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  14229. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  14230. std::string body(4096, 'A');
  14231. auto res = cli.Put("/api/test", body, "application/json");
  14232. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  14233. EXPECT_EQ(StatusCode::OK_200, res->status);
  14234. EXPECT_EQ(body.size(), server_body_bytes.load());
  14235. }
  14236. #endif
  14237. template <typename S, typename C>
  14238. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  14239. svr.Get("/stream", [&](const Request &, Response &res) {
  14240. auto data = new std::string("01234567890123456789");
  14241. res.set_content_provider(
  14242. data->size(), "text/plain",
  14243. [&, data](size_t offset, size_t length, DataSink &sink) {
  14244. const size_t DATA_CHUNK_SIZE = 4;
  14245. const auto &d = *data;
  14246. std::this_thread::sleep_for(std::chrono::seconds(1));
  14247. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  14248. return true;
  14249. },
  14250. [data](bool success) {
  14251. EXPECT_FALSE(success);
  14252. delete data;
  14253. });
  14254. });
  14255. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  14256. auto i = new size_t(0);
  14257. res.set_content_provider(
  14258. "text/plain",
  14259. [i](size_t, DataSink &sink) {
  14260. if (*i < 5) {
  14261. std::this_thread::sleep_for(std::chrono::seconds(1));
  14262. sink.write("abcd", 4);
  14263. (*i)++;
  14264. } else {
  14265. sink.done();
  14266. }
  14267. return true;
  14268. },
  14269. [i](bool success) {
  14270. EXPECT_FALSE(success);
  14271. delete i;
  14272. });
  14273. });
  14274. svr.Get("/chunked", [&](const Request &, Response &res) {
  14275. auto i = new size_t(0);
  14276. res.set_chunked_content_provider(
  14277. "text/plain",
  14278. [i](size_t, DataSink &sink) {
  14279. if (*i < 5) {
  14280. std::this_thread::sleep_for(std::chrono::seconds(1));
  14281. sink.os << "abcd";
  14282. (*i)++;
  14283. } else {
  14284. sink.done();
  14285. }
  14286. return true;
  14287. },
  14288. [i](bool success) {
  14289. EXPECT_FALSE(success);
  14290. delete i;
  14291. });
  14292. });
  14293. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14294. auto se = detail::scope_exit([&] {
  14295. svr.stop();
  14296. listen_thread.join();
  14297. ASSERT_FALSE(svr.is_running());
  14298. });
  14299. svr.wait_until_ready();
  14300. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  14301. {
  14302. auto start = std::chrono::steady_clock::now();
  14303. auto res = cli.Get("/stream");
  14304. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14305. std::chrono::steady_clock::now() - start)
  14306. .count();
  14307. ASSERT_FALSE(res);
  14308. EXPECT_EQ(Error::Read, res.error());
  14309. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14310. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14311. }
  14312. {
  14313. auto start = std::chrono::steady_clock::now();
  14314. auto res = cli.Get("/stream_without_length");
  14315. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14316. std::chrono::steady_clock::now() - start)
  14317. .count();
  14318. ASSERT_FALSE(res);
  14319. EXPECT_EQ(Error::Read, res.error());
  14320. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14321. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14322. }
  14323. {
  14324. auto start = std::chrono::steady_clock::now();
  14325. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  14326. EXPECT_EQ("abcd", string(data, data_length));
  14327. return true;
  14328. });
  14329. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14330. std::chrono::steady_clock::now() - start)
  14331. .count();
  14332. ASSERT_FALSE(res);
  14333. EXPECT_EQ(Error::Read, res.error());
  14334. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14335. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14336. }
  14337. }
  14338. TEST(MaxTimeoutTest, ContentStream) {
  14339. time_t timeout = 2000;
  14340. time_t threshold = 200;
  14341. Server svr;
  14342. Client cli("localhost", PORT);
  14343. max_timeout_test(svr, cli, timeout, threshold);
  14344. }
  14345. #ifdef CPPHTTPLIB_SSL_ENABLED
  14346. TEST(MaxTimeoutTest, ContentStreamSSL) {
  14347. time_t timeout = 2000;
  14348. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  14349. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14350. SSLClient cli("localhost", PORT);
  14351. cli.enable_server_certificate_verification(false);
  14352. max_timeout_test(svr, cli, timeout, threshold);
  14353. }
  14354. #endif
  14355. class EventDispatcher {
  14356. public:
  14357. EventDispatcher() {}
  14358. bool wait_event(DataSink *sink) {
  14359. unique_lock<mutex> lk(m_);
  14360. int id = id_;
  14361. // Wait with timeout to prevent hanging if client disconnects
  14362. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  14363. [&] { return cid_ == id; })) {
  14364. return false; // Timeout occurred
  14365. }
  14366. sink->write(message_.data(), message_.size());
  14367. return true;
  14368. }
  14369. void send_event(const string &message) {
  14370. lock_guard<mutex> lk(m_);
  14371. cid_ = id_++;
  14372. message_ = message;
  14373. cv_.notify_all();
  14374. }
  14375. private:
  14376. mutex m_;
  14377. condition_variable cv_;
  14378. atomic_int id_{0};
  14379. atomic_int cid_{-1};
  14380. string message_;
  14381. };
  14382. TEST(ClientInThreadTest, Issue2068) {
  14383. EventDispatcher ed;
  14384. Server svr;
  14385. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  14386. res.set_chunked_content_provider("text/event-stream",
  14387. [&](size_t /*offset*/, DataSink &sink) {
  14388. return ed.wait_event(&sink);
  14389. });
  14390. });
  14391. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  14392. svr.wait_until_ready();
  14393. thread event_thread([&] {
  14394. int id = 0;
  14395. while (svr.is_running()) {
  14396. this_thread::sleep_for(chrono::milliseconds(500));
  14397. std::stringstream ss;
  14398. ss << "data: " << id << "\n\n";
  14399. ed.send_event(ss.str());
  14400. id++;
  14401. }
  14402. });
  14403. auto se = detail::scope_exit([&] {
  14404. svr.stop();
  14405. listen_thread.join();
  14406. event_thread.join();
  14407. ASSERT_FALSE(svr.is_running());
  14408. });
  14409. {
  14410. auto client = detail::make_unique<Client>(HOST, PORT);
  14411. client->set_read_timeout(std::chrono::minutes(10));
  14412. std::atomic<bool> stop{false};
  14413. std::thread t([&] {
  14414. client->Get("/event1",
  14415. [&](const char *, size_t) -> bool { return !stop; });
  14416. });
  14417. std::this_thread::sleep_for(std::chrono::seconds(2));
  14418. stop = true;
  14419. client->stop();
  14420. t.join();
  14421. // Reset client after thread has finished
  14422. client.reset();
  14423. }
  14424. }
  14425. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  14426. auto handled = false;
  14427. Server svr;
  14428. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14429. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14430. auto se = detail::scope_exit([&] {
  14431. svr.stop();
  14432. t.join();
  14433. ASSERT_FALSE(svr.is_running());
  14434. ASSERT_FALSE(handled);
  14435. });
  14436. svr.wait_until_ready();
  14437. // Two Content-Length headers with different values — must be rejected
  14438. auto req = "POST /test HTTP/1.1\r\n"
  14439. "Content-Length: 5\r\n"
  14440. "Content-Length: 10\r\n"
  14441. "\r\n"
  14442. "hello";
  14443. std::string response;
  14444. ASSERT_TRUE(send_request(1, req, &response));
  14445. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14446. response.substr(0, response.find("\r\n")));
  14447. }
  14448. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  14449. auto handled = false;
  14450. Server svr;
  14451. svr.Post("/test", [&](const Request &, Response &res) {
  14452. handled = true;
  14453. res.set_content("ok", "text/plain");
  14454. });
  14455. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14456. auto se = detail::scope_exit([&] {
  14457. svr.stop();
  14458. t.join();
  14459. ASSERT_FALSE(svr.is_running());
  14460. ASSERT_TRUE(handled);
  14461. });
  14462. svr.wait_until_ready();
  14463. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  14464. auto req = "POST /test HTTP/1.1\r\n"
  14465. "Content-Length: 5\r\n"
  14466. "Content-Length: 5\r\n"
  14467. "\r\n"
  14468. "hello";
  14469. std::string response;
  14470. ASSERT_TRUE(send_request(1, req, &response));
  14471. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  14472. }
  14473. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  14474. Server svr;
  14475. svr.Get("/", [](const Request &req, Response &res) {
  14476. EXPECT_EQ(2U, req.trailers.size());
  14477. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  14478. // Denied
  14479. EXPECT_FALSE(req.has_trailer("Content-Length"));
  14480. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  14481. // Accepted
  14482. EXPECT_TRUE(req.has_trailer("X-Hello"));
  14483. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  14484. EXPECT_TRUE(req.has_trailer("X-World"));
  14485. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  14486. res.set_content("ok", "text/plain");
  14487. });
  14488. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14489. auto se = detail::scope_exit([&] {
  14490. svr.stop();
  14491. t.join();
  14492. ASSERT_FALSE(svr.is_running());
  14493. });
  14494. svr.wait_until_ready();
  14495. const std::string req = "GET / HTTP/1.1\r\n"
  14496. "Transfer-Encoding: chunked\r\n"
  14497. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  14498. "\r\n"
  14499. "0\r\n"
  14500. "Content-Length: 10\r\n"
  14501. "Host: internal.local\r\n"
  14502. "Content-Type: malicious/content\r\n"
  14503. "Cookie: any\r\n"
  14504. "Set-Cookie: any\r\n"
  14505. "X-Forwarded-For: attacker.com\r\n"
  14506. "X-Real-Ip: 1.1.1.1\r\n"
  14507. "X-Hello: hello\r\n"
  14508. "X-World: world\r\n"
  14509. "\r\n";
  14510. std::string res;
  14511. ASSERT_TRUE(send_request(1, req, &res));
  14512. }
  14513. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  14514. // several field lines, and the combined value is what has to be parsed. A
  14515. // Trailer field split across lines therefore declares every name it lists;
  14516. // reading only the first line silently drops the trailers the later lines
  14517. // declare. The prohibited-trailer filter still applies to every line.
  14518. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  14519. Server svr;
  14520. size_t observed_trailer_count = 0;
  14521. std::string observed_hello;
  14522. std::string observed_world;
  14523. bool observed_content_length = true;
  14524. svr.Get("/", [&](const Request &req, Response &res) {
  14525. observed_trailer_count = req.trailers.size();
  14526. observed_hello = req.get_trailer_value("X-Hello");
  14527. observed_world = req.get_trailer_value("X-World");
  14528. observed_content_length = req.has_trailer("Content-Length");
  14529. res.set_content("ok", "text/plain");
  14530. });
  14531. auto port = svr.bind_to_any_port(HOST);
  14532. thread t = thread([&]() { svr.listen_after_bind(); });
  14533. auto se = detail::scope_exit([&] {
  14534. svr.stop();
  14535. t.join();
  14536. ASSERT_FALSE(svr.is_running());
  14537. });
  14538. svr.wait_until_ready();
  14539. const std::string req = "GET / HTTP/1.1\r\n"
  14540. "Transfer-Encoding: chunked\r\n"
  14541. "Trailer: X-Hello\r\n"
  14542. "Trailer: X-World, Content-Length\r\n"
  14543. "\r\n"
  14544. "0\r\n"
  14545. "X-Hello: hello\r\n"
  14546. "X-World: world\r\n"
  14547. "Content-Length: 10\r\n"
  14548. "\r\n";
  14549. std::string res;
  14550. ASSERT_TRUE(send_request(1, req, &res, port));
  14551. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  14552. // Accepted: both field lines contribute to the declared set
  14553. EXPECT_EQ(2U, observed_trailer_count);
  14554. EXPECT_EQ(observed_hello, "hello");
  14555. EXPECT_EQ(observed_world, "world");
  14556. // Denied: a prohibited name stays prohibited on a later field line
  14557. EXPECT_FALSE(observed_content_length);
  14558. }
  14559. // A direct client that is not listed in trusted_proxies must not be able to
  14560. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  14561. // the peer address on the actual TCP connection determines whether the
  14562. // header is honored.
  14563. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  14564. Server svr;
  14565. // Deliberately does NOT include the loopback address the test client
  14566. // actually connects from, so the direct connection is not a trusted proxy.
  14567. svr.set_trusted_proxies({"203.0.113.66"});
  14568. std::string observed_remote_addr;
  14569. svr.Get("/ip", [&](const Request &req, Response &res) {
  14570. observed_remote_addr = req.remote_addr;
  14571. res.set_content("ok", "text/plain");
  14572. });
  14573. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14574. auto se = detail::scope_exit([&] {
  14575. svr.stop();
  14576. t.join();
  14577. ASSERT_FALSE(svr.is_running());
  14578. });
  14579. svr.wait_until_ready();
  14580. Client cli(HOST, PORT);
  14581. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  14582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14583. EXPECT_EQ(StatusCode::OK_200, res->status);
  14584. // The connecting peer is not a trusted proxy, so the spoofed header must be
  14585. // ignored entirely and the real connection-level address retained.
  14586. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14587. observed_remote_addr == "127.0.0.1");
  14588. }
  14589. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  14590. Server svr;
  14591. std::string observed_remote_addr;
  14592. std::string observed_xff;
  14593. svr.Get("/ip", [&](const Request &req, Response &res) {
  14594. observed_remote_addr = req.remote_addr;
  14595. observed_xff = req.get_header_value("X-Forwarded-For");
  14596. res.set_content("ok", "text/plain");
  14597. });
  14598. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14599. auto se = detail::scope_exit([&] {
  14600. svr.stop();
  14601. t.join();
  14602. ASSERT_FALSE(svr.is_running());
  14603. });
  14604. svr.wait_until_ready();
  14605. Client cli(HOST, PORT);
  14606. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  14607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14608. EXPECT_EQ(StatusCode::OK_200, res->status);
  14609. EXPECT_EQ(observed_xff, "203.0.113.66");
  14610. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14611. observed_remote_addr == "127.0.0.1");
  14612. }
  14613. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  14614. Server svr;
  14615. svr.set_trusted_proxies({"203.0.113.66"});
  14616. std::string observed_remote_addr;
  14617. std::string observed_xff;
  14618. svr.Get("/ip", [&](const Request &req, Response &res) {
  14619. observed_remote_addr = req.remote_addr;
  14620. observed_xff = req.get_header_value("X-Forwarded-For");
  14621. res.set_content("ok", "text/plain");
  14622. });
  14623. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14624. auto se = detail::scope_exit([&] {
  14625. svr.stop();
  14626. t.join();
  14627. ASSERT_FALSE(svr.is_running());
  14628. });
  14629. svr.wait_until_ready();
  14630. Client cli(HOST, PORT);
  14631. auto res = cli.Get("/ip");
  14632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14633. EXPECT_EQ(StatusCode::OK_200, res->status);
  14634. EXPECT_EQ(observed_xff, "");
  14635. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14636. observed_remote_addr == "127.0.0.1");
  14637. }
  14638. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  14639. Server svr;
  14640. // Include the loopback address the test client actually connects from, so
  14641. // the direct connection itself is recognized as the trusted proxy hop.
  14642. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  14643. std::string observed_remote_addr;
  14644. std::string observed_xff;
  14645. svr.Get("/ip", [&](const Request &req, Response &res) {
  14646. observed_remote_addr = req.remote_addr;
  14647. observed_xff = req.get_header_value("X-Forwarded-For");
  14648. res.set_content("ok", "text/plain");
  14649. });
  14650. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14651. auto se = detail::scope_exit([&] {
  14652. svr.stop();
  14653. t.join();
  14654. ASSERT_FALSE(svr.is_running());
  14655. });
  14656. svr.wait_until_ready();
  14657. Client cli(HOST, PORT);
  14658. auto res = cli.Get(
  14659. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  14660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14661. EXPECT_EQ(StatusCode::OK_200, res->status);
  14662. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  14663. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14664. }
  14665. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  14666. Server svr;
  14667. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  14668. std::string observed_remote_addr;
  14669. std::string observed_xff;
  14670. svr.Get("/ip", [&](const Request &req, Response &res) {
  14671. observed_remote_addr = req.remote_addr;
  14672. observed_xff = req.get_header_value("X-Forwarded-For");
  14673. res.set_content("ok", "text/plain");
  14674. });
  14675. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14676. auto se = detail::scope_exit([&] {
  14677. svr.stop();
  14678. t.join();
  14679. ASSERT_FALSE(svr.is_running());
  14680. });
  14681. svr.wait_until_ready();
  14682. Client cli(HOST, PORT);
  14683. auto res = cli.Get(
  14684. "/ip",
  14685. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14687. EXPECT_EQ(StatusCode::OK_200, res->status);
  14688. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14689. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14690. }
  14691. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  14692. Server svr;
  14693. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14694. std::string observed_remote_addr;
  14695. std::string observed_xff;
  14696. svr.Get("/ip", [&](const Request &req, Response &res) {
  14697. observed_remote_addr = req.remote_addr;
  14698. observed_xff = req.get_header_value("X-Forwarded-For");
  14699. res.set_content("ok", "text/plain");
  14700. });
  14701. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14702. auto se = detail::scope_exit([&] {
  14703. svr.stop();
  14704. t.join();
  14705. ASSERT_FALSE(svr.is_running());
  14706. });
  14707. svr.wait_until_ready();
  14708. Client cli(HOST, PORT);
  14709. auto res = cli.Get(
  14710. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  14711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14712. EXPECT_EQ(StatusCode::OK_200, res->status);
  14713. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  14714. // by the closest hop) is used. The leftmost entry is fully client-controlled
  14715. // and must not be selected.
  14716. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  14717. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  14718. }
  14719. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  14720. Server svr;
  14721. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  14722. std::string observed_remote_addr;
  14723. svr.Get("/ip", [&](const Request &req, Response &res) {
  14724. observed_remote_addr = req.remote_addr;
  14725. res.set_content("ok", "text/plain");
  14726. });
  14727. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14728. auto se = detail::scope_exit([&] {
  14729. svr.stop();
  14730. t.join();
  14731. ASSERT_FALSE(svr.is_running());
  14732. });
  14733. svr.wait_until_ready();
  14734. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  14735. // a forged address and the trusted proxy's own address; the forged value must
  14736. // not win over the address the trusted proxy actually recorded.
  14737. Client cli(HOST, PORT);
  14738. auto res = cli.Get(
  14739. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  14740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14741. EXPECT_EQ(StatusCode::OK_200, res->status);
  14742. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  14743. }
  14744. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  14745. Server svr;
  14746. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14747. std::string observed_remote_addr;
  14748. std::string observed_xff;
  14749. svr.Get("/ip", [&](const Request &req, Response &res) {
  14750. observed_remote_addr = req.remote_addr;
  14751. observed_xff = req.get_header_value("X-Forwarded-For");
  14752. res.set_content("ok", "text/plain");
  14753. });
  14754. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14755. auto se = detail::scope_exit([&] {
  14756. svr.stop();
  14757. t.join();
  14758. ASSERT_FALSE(svr.is_running());
  14759. });
  14760. svr.wait_until_ready();
  14761. Client cli(HOST, PORT);
  14762. auto res = cli.Get(
  14763. "/ip",
  14764. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14766. EXPECT_EQ(StatusCode::OK_200, res->status);
  14767. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14768. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14769. }
  14770. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  14771. Server svr;
  14772. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14773. std::string observed_remote_addr;
  14774. std::string observed_xff;
  14775. svr.Get("/ip", [&](const Request &req, Response &res) {
  14776. observed_remote_addr = req.remote_addr;
  14777. observed_xff = req.get_header_value("X-Forwarded-For");
  14778. res.set_content("ok", "text/plain");
  14779. });
  14780. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14781. auto se = detail::scope_exit([&] {
  14782. svr.stop();
  14783. t.join();
  14784. ASSERT_FALSE(svr.is_running());
  14785. });
  14786. svr.wait_until_ready();
  14787. std::string raw_req =
  14788. "GET /ip HTTP/1.1\r\n"
  14789. "Host: localhost\r\n"
  14790. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  14791. "Connection: close\r\n"
  14792. "\r\n";
  14793. std::string out;
  14794. ASSERT_TRUE(send_request(5, raw_req, &out));
  14795. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14796. // Header parser trims surrounding whitespace of the header value
  14797. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  14798. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14799. }
  14800. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  14801. // one comma-joined value, in the order received. Proxies such as HAProxy append
  14802. // their own X-Forwarded-For as a separate field line rather than extending the
  14803. // one the client sent, so every occurrence has to be taken into account.
  14804. // Reading only the first one hands back the address the client chose.
  14805. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  14806. Server svr;
  14807. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14808. std::string observed_remote_addr;
  14809. size_t observed_xff_count = 0;
  14810. svr.Get("/ip", [&](const Request &req, Response &res) {
  14811. observed_remote_addr = req.remote_addr;
  14812. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  14813. res.set_content("ok", "text/plain");
  14814. });
  14815. auto port = svr.bind_to_any_port(HOST);
  14816. thread t = thread([&]() { svr.listen_after_bind(); });
  14817. auto se = detail::scope_exit([&] {
  14818. svr.stop();
  14819. t.join();
  14820. ASSERT_FALSE(svr.is_running());
  14821. });
  14822. svr.wait_until_ready();
  14823. // The client supplies the first field line; the trusted proxy appends the
  14824. // address it observed as a second one.
  14825. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  14826. "Host: localhost\r\n"
  14827. "X-Forwarded-For: 1.2.3.4\r\n"
  14828. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  14829. "Connection: close\r\n"
  14830. "\r\n";
  14831. std::string out;
  14832. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14833. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14834. EXPECT_EQ(observed_xff_count, 2U);
  14835. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14836. // The same chain spread over one field line per hop derives the same client
  14837. // address, i.e. the split and the comma-joined representations agree.
  14838. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  14839. "Host: localhost\r\n"
  14840. "X-Forwarded-For: 1.2.3.4\r\n"
  14841. "X-Forwarded-For: 198.51.100.23\r\n"
  14842. "X-Forwarded-For: 192.0.2.45\r\n"
  14843. "Connection: close\r\n"
  14844. "\r\n";
  14845. out.clear();
  14846. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  14847. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14848. EXPECT_EQ(observed_xff_count, 3U);
  14849. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14850. }
  14851. // An X-Forwarded-For header whose value parses to zero IP segments must not
  14852. // crash the server (it used to call front() on an empty vector inside
  14853. // get_client_ip). The connection-level remote address must be retained instead.
  14854. static void run_malformed_xff_test(const std::string &xff_value) {
  14855. Server svr;
  14856. svr.set_trusted_proxies({"192.0.2.45"});
  14857. std::string observed_remote_addr;
  14858. svr.Get("/ip", [&](const Request &req, Response &res) {
  14859. observed_remote_addr = req.remote_addr;
  14860. res.set_content("ok", "text/plain");
  14861. });
  14862. int port = 0;
  14863. thread t = thread([&]() {
  14864. port = svr.bind_to_any_port(HOST);
  14865. svr.listen_after_bind();
  14866. });
  14867. auto se = detail::scope_exit([&] {
  14868. svr.stop();
  14869. t.join();
  14870. ASSERT_FALSE(svr.is_running());
  14871. });
  14872. svr.wait_until_ready();
  14873. Client cli(HOST, port);
  14874. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  14875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14876. EXPECT_EQ(StatusCode::OK_200, res->status);
  14877. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14878. observed_remote_addr == "127.0.0.1");
  14879. }
  14880. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  14881. run_malformed_xff_test("");
  14882. }
  14883. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  14884. run_malformed_xff_test(",");
  14885. }
  14886. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  14887. run_malformed_xff_test(", , ,");
  14888. }
  14889. // The same rule applies to Accept: a request whose acceptable types are spread
  14890. // over several field lines must be negotiated against all of them.
  14891. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  14892. // case-insensitive connection options. Comparing the whole field value against
  14893. // one option misses a client that sends several of them, and misses every
  14894. // casing but the one written in the comparison.
  14895. //
  14896. // Sends req, reads the response, then reuses the same socket for a second
  14897. // request to find out whether the server kept the connection.
  14898. static void probe_connection_reuse(int port, const std::string &req,
  14899. bool *announced_close, bool *reusable) {
  14900. auto error = Error::Success;
  14901. auto sock = detail::create_client_socket(
  14902. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  14903. /*connection_timeout_sec=*/5, 0,
  14904. /*read_timeout_sec=*/1, 0,
  14905. /*write_timeout_sec=*/5, 0, std::string(), error);
  14906. ASSERT_NE(sock, INVALID_SOCKET);
  14907. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  14908. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  14909. "Host: localhost\r\n"
  14910. "Connection: close\r\n"
  14911. "\r\n";
  14912. std::string first_response;
  14913. std::string second_response;
  14914. detail::process_client_socket(
  14915. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  14916. [&](Stream &strm) {
  14917. if (strm.write(req.data(), req.size()) !=
  14918. static_cast<ssize_t>(req.size())) {
  14919. return false;
  14920. }
  14921. char buf[512];
  14922. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  14923. // Headers plus the two-byte body of the handler below
  14924. while (reader.getline()) {
  14925. first_response += reader.ptr();
  14926. if (first_response.find("ok") != std::string::npos) { break; }
  14927. }
  14928. if (strm.write(second.data(), second.size()) !=
  14929. static_cast<ssize_t>(second.size())) {
  14930. return true;
  14931. }
  14932. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  14933. while (reader2.getline()) {
  14934. second_response += reader2.ptr();
  14935. if (second_response.find("ok") != std::string::npos) { break; }
  14936. }
  14937. return true;
  14938. });
  14939. *announced_close =
  14940. first_response.find("Connection: close") != std::string::npos;
  14941. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  14942. }
  14943. class ConnectionTokenTest : public ::testing::Test {
  14944. protected:
  14945. void SetUp() override {
  14946. svr_.Get("/keepalive", [](const Request &, Response &res) {
  14947. res.set_content("ok", "text/plain");
  14948. });
  14949. port_ = svr_.bind_to_any_port(HOST);
  14950. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14951. svr_.wait_until_ready();
  14952. }
  14953. void TearDown() override {
  14954. svr_.stop();
  14955. if (thread_.joinable()) { thread_.join(); }
  14956. }
  14957. Server svr_;
  14958. int port_ = 0;
  14959. thread thread_;
  14960. };
  14961. // "close" alongside another option still closes the connection, and the
  14962. // response says so rather than leaving the peer to discover it.
  14963. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  14964. bool announced_close = false;
  14965. bool reusable = true;
  14966. probe_connection_reuse(port_,
  14967. "GET /keepalive HTTP/1.1\r\n"
  14968. "Host: localhost\r\n"
  14969. "Connection: keep-alive, close\r\n"
  14970. "\r\n",
  14971. &announced_close, &reusable);
  14972. EXPECT_TRUE(announced_close);
  14973. EXPECT_FALSE(reusable);
  14974. }
  14975. // "close" split over two field lines is the same list, so it is honored too.
  14976. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  14977. bool announced_close = false;
  14978. bool reusable = true;
  14979. probe_connection_reuse(port_,
  14980. "GET /keepalive HTTP/1.1\r\n"
  14981. "Host: localhost\r\n"
  14982. "Connection: keep-alive\r\n"
  14983. "Connection: close\r\n"
  14984. "\r\n",
  14985. &announced_close, &reusable);
  14986. EXPECT_TRUE(announced_close);
  14987. EXPECT_FALSE(reusable);
  14988. }
  14989. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  14990. // keep-alive in the spelling everyone actually sends keeps its connection.
  14991. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  14992. bool announced_close = false;
  14993. bool reusable = false;
  14994. probe_connection_reuse(port_,
  14995. "GET /keepalive HTTP/1.0\r\n"
  14996. "Host: localhost\r\n"
  14997. "Connection: keep-alive\r\n"
  14998. "\r\n",
  14999. &announced_close, &reusable);
  15000. EXPECT_FALSE(announced_close);
  15001. EXPECT_TRUE(reusable);
  15002. }
  15003. // A token the value merely contains is not the token itself.
  15004. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  15005. bool announced_close = false;
  15006. bool reusable = false;
  15007. probe_connection_reuse(port_,
  15008. "GET /keepalive HTTP/1.1\r\n"
  15009. "Host: localhost\r\n"
  15010. "Connection: notclose\r\n"
  15011. "\r\n",
  15012. &announced_close, &reusable);
  15013. EXPECT_FALSE(announced_close);
  15014. EXPECT_TRUE(reusable);
  15015. }
  15016. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  15017. Server svr;
  15018. std::vector<std::string> observed_types;
  15019. svr.Get("/", [&](const Request &req, Response &res) {
  15020. observed_types = req.accept_content_types;
  15021. res.set_content("ok", "text/plain");
  15022. });
  15023. auto port = svr.bind_to_any_port(HOST);
  15024. thread t = thread([&]() { svr.listen_after_bind(); });
  15025. auto se = detail::scope_exit([&] {
  15026. svr.stop();
  15027. t.join();
  15028. ASSERT_FALSE(svr.is_running());
  15029. });
  15030. svr.wait_until_ready();
  15031. Client cli(HOST, port);
  15032. Headers headers;
  15033. headers.emplace("Accept", "text/plain;q=0.5");
  15034. headers.emplace("Accept", "application/json");
  15035. auto res = cli.Get("/", headers);
  15036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15037. EXPECT_EQ(StatusCode::OK_200, res->status);
  15038. // Sorted by q-value, so the second field line's type comes first
  15039. ASSERT_EQ(2U, observed_types.size());
  15040. EXPECT_EQ("application/json", observed_types[0]);
  15041. EXPECT_EQ("text/plain", observed_types[1]);
  15042. }
  15043. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  15044. // empty field line must not contribute a bare comma to the combined value.
  15045. // parse_accept_header() rejects a leading comma outright, so a stray one would
  15046. // turn a legal request into 400 Bad Request.
  15047. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  15048. Server svr;
  15049. std::vector<std::string> observed_types;
  15050. svr.Get("/", [&](const Request &req, Response &res) {
  15051. observed_types = req.accept_content_types;
  15052. res.set_content("ok", "text/plain");
  15053. });
  15054. auto port = svr.bind_to_any_port(HOST);
  15055. thread t = thread([&]() { svr.listen_after_bind(); });
  15056. auto se = detail::scope_exit([&] {
  15057. svr.stop();
  15058. t.join();
  15059. ASSERT_FALSE(svr.is_running());
  15060. });
  15061. svr.wait_until_ready();
  15062. // Empty first field line, then a real one
  15063. std::string raw_req = "GET / HTTP/1.1\r\n"
  15064. "Host: localhost\r\n"
  15065. "Accept:\r\n"
  15066. "Accept: application/json\r\n"
  15067. "Connection: close\r\n"
  15068. "\r\n";
  15069. std::string out;
  15070. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15071. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15072. ASSERT_EQ(1U, observed_types.size());
  15073. EXPECT_EQ("application/json", observed_types[0]);
  15074. }
  15075. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15076. // An encoding offered on a later Accept-Encoding field line is still offered.
  15077. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  15078. Server svr;
  15079. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15080. res.set_content(std::string(1024, 'x'), "text/plain");
  15081. });
  15082. auto port = svr.bind_to_any_port(HOST);
  15083. thread t = thread([&]() { svr.listen_after_bind(); });
  15084. auto se = detail::scope_exit([&] {
  15085. svr.stop();
  15086. t.join();
  15087. ASSERT_FALSE(svr.is_running());
  15088. });
  15089. svr.wait_until_ready();
  15090. Client cli(HOST, port);
  15091. cli.set_decompress(false);
  15092. Headers headers;
  15093. headers.emplace("Accept-Encoding", "identity");
  15094. headers.emplace("Accept-Encoding", "gzip");
  15095. auto res = cli.Get("/", headers);
  15096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15097. EXPECT_EQ(StatusCode::OK_200, res->status);
  15098. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  15099. }
  15100. #endif
  15101. #ifndef _WIN32
  15102. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  15103. Server svr;
  15104. svr.Post("/post", [&](const Request &req, Response &res) {
  15105. res.set_content(req.body, "text/plain");
  15106. });
  15107. svr.Put("/put", [&](const Request &req, Response &res) {
  15108. res.set_content(req.body, "text/plain");
  15109. });
  15110. svr.Patch("/patch", [&](const Request &req, Response &res) {
  15111. res.set_content(req.body, "text/plain");
  15112. });
  15113. svr.Delete("/delete", [&](const Request &req, Response &res) {
  15114. res.set_content(req.body, "text/plain");
  15115. });
  15116. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15117. auto se = detail::scope_exit([&] {
  15118. svr.stop();
  15119. t.join();
  15120. ASSERT_FALSE(svr.is_running());
  15121. });
  15122. svr.wait_until_ready();
  15123. std::string resp;
  15124. // POST without Content-Length
  15125. ASSERT_TRUE(send_request(5,
  15126. "POST /post HTTP/1.1\r\n"
  15127. "Host: localhost\r\n"
  15128. "Connection: close\r\n"
  15129. "\r\n",
  15130. &resp));
  15131. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15132. // PUT without Content-Length
  15133. resp.clear();
  15134. ASSERT_TRUE(send_request(5,
  15135. "PUT /put HTTP/1.1\r\n"
  15136. "Host: localhost\r\n"
  15137. "Connection: close\r\n"
  15138. "\r\n",
  15139. &resp));
  15140. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15141. // PATCH without Content-Length
  15142. resp.clear();
  15143. ASSERT_TRUE(send_request(5,
  15144. "PATCH /patch HTTP/1.1\r\n"
  15145. "Host: localhost\r\n"
  15146. "Connection: close\r\n"
  15147. "\r\n",
  15148. &resp));
  15149. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15150. // DELETE without Content-Length
  15151. resp.clear();
  15152. ASSERT_TRUE(send_request(5,
  15153. "DELETE /delete HTTP/1.1\r\n"
  15154. "Host: localhost\r\n"
  15155. "Connection: close\r\n"
  15156. "\r\n",
  15157. &resp));
  15158. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15159. }
  15160. #endif
  15161. //==============================================================================
  15162. // open_stream() Tests
  15163. //==============================================================================
  15164. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  15165. std::string result;
  15166. char buf[8192];
  15167. ssize_t n;
  15168. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15169. result.append(buf, static_cast<size_t>(n));
  15170. }
  15171. return result;
  15172. }
  15173. // Mock stream for unit tests
  15174. class MockStream : public Stream {
  15175. public:
  15176. std::string data;
  15177. size_t pos = 0;
  15178. ssize_t error_after = -1; // -1 = no error
  15179. explicit MockStream(const std::string &d, ssize_t err = -1)
  15180. : data(d), error_after(err) {}
  15181. bool is_readable() const override { return true; }
  15182. bool wait_readable() const override { return true; }
  15183. bool wait_writable() const override { return true; }
  15184. ssize_t read(char *ptr, size_t size) override {
  15185. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  15186. if (pos >= data.size()) return 0;
  15187. size_t limit =
  15188. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  15189. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  15190. std::memcpy(ptr, data.data() + pos, to_read);
  15191. pos += to_read;
  15192. return static_cast<ssize_t>(to_read);
  15193. }
  15194. ssize_t write(const char *, size_t) override { return -1; }
  15195. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  15196. ip = "127.0.0.1";
  15197. port = 0;
  15198. }
  15199. void get_local_ip_and_port(std::string &ip, int &port) const override {
  15200. ip = "127.0.0.1";
  15201. port = 0;
  15202. }
  15203. socket_t socket() const override { return INVALID_SOCKET; }
  15204. time_t duration() const override { return 0; }
  15205. };
  15206. TEST(StreamHandleTest, Basic) {
  15207. ClientImpl::StreamHandle handle;
  15208. EXPECT_FALSE(handle.is_valid());
  15209. handle.response = detail::make_unique<Response>();
  15210. handle.error = Error::Connection;
  15211. EXPECT_FALSE(handle.is_valid());
  15212. handle.error = Error::Success;
  15213. EXPECT_TRUE(handle.is_valid());
  15214. }
  15215. TEST(BodyReaderTest, Basic) {
  15216. MockStream stream("Hello, World!");
  15217. detail::BodyReader reader;
  15218. reader.stream = &stream;
  15219. reader.content_length = 13;
  15220. char buf[32];
  15221. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  15222. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  15223. EXPECT_TRUE(reader.eof);
  15224. }
  15225. TEST(BodyReaderTest, NoStream) {
  15226. detail::BodyReader reader;
  15227. char buf[32];
  15228. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15229. EXPECT_EQ(Error::Connection, reader.last_error);
  15230. }
  15231. TEST(BodyReaderTest, Error) {
  15232. MockStream stream("Hello, World!", 5);
  15233. detail::BodyReader reader;
  15234. reader.stream = &stream;
  15235. reader.content_length = 13;
  15236. char buf[32];
  15237. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  15238. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15239. EXPECT_EQ(Error::Read, reader.last_error);
  15240. }
  15241. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  15242. // Mock-based StreamHandle tests relying on private internals are removed.
  15243. class OpenStreamTest : public ::testing::Test {
  15244. protected:
  15245. void SetUp() override {
  15246. svr_.Get("/hello", [](const Request &, Response &res) {
  15247. res.set_content("Hello World!", "text/plain");
  15248. });
  15249. svr_.Get("/large", [](const Request &, Response &res) {
  15250. res.set_content(std::string(10000, 'X'), "text/plain");
  15251. });
  15252. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  15253. res.set_content("Hello World!", "image/jpeg");
  15254. res.set_header("Content-Encoding", "UTF-8");
  15255. });
  15256. svr_.Get("/chunked", [](const Request &, Response &res) {
  15257. res.set_chunked_content_provider("text/plain",
  15258. [](size_t offset, DataSink &sink) {
  15259. if (offset < 15) {
  15260. sink.write("chunk", 5);
  15261. return true;
  15262. }
  15263. sink.done();
  15264. return true;
  15265. });
  15266. });
  15267. svr_.Get("/compressible", [](const Request &, Response &res) {
  15268. res.set_chunked_content_provider("text/plain", [](size_t offset,
  15269. DataSink &sink) {
  15270. if (offset < 100 * 1024) {
  15271. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  15272. sink.write(chunk.data(), chunk.size());
  15273. return true;
  15274. }
  15275. sink.done();
  15276. return true;
  15277. });
  15278. });
  15279. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  15280. [](const Request & /*req*/, Response &res) {
  15281. auto i = new int(0);
  15282. res.set_header("Trailer", "Content-Length, X-Allowed");
  15283. res.set_chunked_content_provider(
  15284. "text/plain",
  15285. [i](size_t /*offset*/, DataSink &sink) {
  15286. switch (*i) {
  15287. case 0: sink.os << "123"; break;
  15288. case 1: sink.os << "456"; break;
  15289. case 2: sink.os << "789"; break;
  15290. case 3: {
  15291. sink.done_with_trailer(
  15292. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  15293. } break;
  15294. }
  15295. (*i)++;
  15296. return true;
  15297. },
  15298. [i](bool success) {
  15299. EXPECT_TRUE(success);
  15300. delete i;
  15301. });
  15302. });
  15303. // Echo headers endpoint for header-related tests
  15304. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  15305. std::string body;
  15306. for (const auto &h : req.headers) {
  15307. body.append(h.first);
  15308. body.push_back(':');
  15309. body.append(h.second);
  15310. body.push_back('\n');
  15311. }
  15312. res.set_content(body, "text/plain");
  15313. });
  15314. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  15315. std::string body;
  15316. for (const auto &h : req.headers) {
  15317. body.append(h.first);
  15318. body.push_back(':');
  15319. body.append(h.second);
  15320. body.push_back('\n');
  15321. }
  15322. res.set_content(body, "text/plain");
  15323. });
  15324. port_ = svr_.bind_to_any_port("127.0.0.1");
  15325. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15326. svr_.wait_until_ready();
  15327. }
  15328. void TearDown() override {
  15329. svr_.stop();
  15330. if (thread_.joinable()) thread_.join();
  15331. }
  15332. Server svr_;
  15333. std::thread thread_;
  15334. int port_ = 0;
  15335. };
  15336. TEST_F(OpenStreamTest, Basic) {
  15337. Client cli("127.0.0.1", port_);
  15338. auto handle = cli.open_stream("GET", "/hello");
  15339. EXPECT_TRUE(handle.is_valid());
  15340. EXPECT_EQ("Hello World!", read_all(handle));
  15341. }
  15342. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  15343. Client cli("127.0.0.1", port_);
  15344. auto handle = cli.open_stream("GET", "/unknown-encoding");
  15345. ASSERT_TRUE(handle.is_valid());
  15346. EXPECT_EQ("Hello World!", read_all(handle));
  15347. }
  15348. TEST_F(OpenStreamTest, SmallBuffer) {
  15349. Client cli("127.0.0.1", port_);
  15350. auto handle = cli.open_stream("GET", "/hello");
  15351. std::string result;
  15352. char buf[4];
  15353. ssize_t n;
  15354. while ((n = handle.read(buf, sizeof(buf))) > 0)
  15355. result.append(buf, static_cast<size_t>(n));
  15356. EXPECT_EQ("Hello World!", result);
  15357. }
  15358. TEST_F(OpenStreamTest, DefaultHeaders) {
  15359. Client cli("127.0.0.1", port_);
  15360. // open_stream GET should include Host, User-Agent and Accept-Encoding
  15361. {
  15362. auto handle = cli.open_stream("GET", "/echo-headers");
  15363. ASSERT_TRUE(handle.is_valid());
  15364. auto body = read_all(handle);
  15365. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  15366. std::string::npos);
  15367. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  15368. std::string::npos);
  15369. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  15370. }
  15371. // open_stream POST with body and no explicit content_type should NOT add
  15372. // text/plain Content-Type (behavior differs from non-streaming path), but
  15373. // should include Content-Length
  15374. {
  15375. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  15376. ASSERT_TRUE(handle.is_valid());
  15377. auto body = read_all(handle);
  15378. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  15379. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  15380. }
  15381. // open_stream POST with explicit Content-Type should preserve it
  15382. {
  15383. auto handle = cli.open_stream("POST", "/echo-headers", {},
  15384. {{"Content-Type", "application/custom"}},
  15385. "{}", "application/custom");
  15386. ASSERT_TRUE(handle.is_valid());
  15387. auto body = read_all(handle);
  15388. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  15389. }
  15390. // User-specified User-Agent must not be overwritten for stream API
  15391. {
  15392. auto handle = cli.open_stream("GET", "/echo-headers", {},
  15393. {{"User-Agent", "MyAgent/1.2"}});
  15394. ASSERT_TRUE(handle.is_valid());
  15395. auto body = read_all(handle);
  15396. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  15397. }
  15398. }
  15399. TEST_F(OpenStreamTest, Large) {
  15400. Client cli("127.0.0.1", port_);
  15401. auto handle = cli.open_stream("GET", "/large");
  15402. EXPECT_EQ(10000u, read_all(handle).size());
  15403. }
  15404. TEST_F(OpenStreamTest, ConnectionError) {
  15405. Client cli("127.0.0.1", 9999);
  15406. auto handle = cli.open_stream("GET", "/hello");
  15407. EXPECT_FALSE(handle.is_valid());
  15408. }
  15409. TEST_F(OpenStreamTest, Chunked) {
  15410. Client cli("127.0.0.1", port_);
  15411. auto handle = cli.open_stream("GET", "/chunked");
  15412. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15413. "Transfer-Encoding") == "chunked");
  15414. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  15415. }
  15416. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  15417. Client cli("127.0.0.1", port_);
  15418. auto handle =
  15419. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  15420. ASSERT_TRUE(handle.is_valid());
  15421. // Consume body to allow trailers to be received/parsed
  15422. auto body = read_all(handle);
  15423. // Explicitly parse trailers (ensure trailers are available for assertion)
  15424. handle.parse_trailers_if_needed();
  15425. EXPECT_EQ(std::string("123456789"), body);
  15426. // The response should include a Trailer header declaring both names
  15427. ASSERT_TRUE(handle.response);
  15428. EXPECT_TRUE(handle.response->has_header("Trailer"));
  15429. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  15430. handle.response->get_header_value("Trailer"));
  15431. // Prohibited trailer must not be present
  15432. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  15433. // Allowed trailer should be present
  15434. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  15435. EXPECT_EQ(std::string("yes"),
  15436. handle.response->get_trailer_value("X-Allowed"));
  15437. // Verify trailers are NOT present as regular headers
  15438. EXPECT_EQ(std::string(""),
  15439. handle.response->get_header_value("Content-Length"));
  15440. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  15441. }
  15442. static std::thread serve_single_response(std::promise<int> &port_promise,
  15443. const std::string &response) {
  15444. return std::thread([&port_promise, response] {
  15445. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15446. default_socket_options(srv);
  15447. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  15448. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  15449. sockaddr_in addr{};
  15450. addr.sin_family = AF_INET;
  15451. addr.sin_port = htons(0); // Let OS assign a free port
  15452. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15453. int opt = 1;
  15454. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  15455. #ifdef _WIN32
  15456. reinterpret_cast<const char *>(&opt),
  15457. #else
  15458. &opt,
  15459. #endif
  15460. sizeof(opt));
  15461. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  15462. ::listen(srv, 1) != 0) {
  15463. port_promise.set_value(-1);
  15464. detail::close_socket(srv);
  15465. return;
  15466. }
  15467. socklen_t addr_len = sizeof(addr);
  15468. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  15469. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  15470. sockaddr_in cli_addr{};
  15471. socklen_t cli_len = sizeof(cli_addr);
  15472. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15473. if (cli != INVALID_SOCKET) {
  15474. // Read the complete HTTP request (until the blank line that terminates
  15475. // headers) before sending the response. If the server closes the socket
  15476. // while the client's request data is still unread in the kernel receive
  15477. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  15478. // connection on both sides: it discards the client's receive buffer
  15479. // (which already holds our response) and causes any in-progress write on
  15480. // the client to fail with ECONNRESET. Reading all request data first
  15481. // ensures close() emits a graceful FIN.
  15482. {
  15483. char rbuf[256];
  15484. std::string req;
  15485. while (req.find("\r\n\r\n") == std::string::npos) {
  15486. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  15487. if (n <= 0) { break; }
  15488. req.append(rbuf, static_cast<size_t>(n));
  15489. }
  15490. }
  15491. ::send(cli,
  15492. #ifdef _WIN32
  15493. static_cast<const char *>(response.c_str()),
  15494. static_cast<int>(response.size()),
  15495. #else
  15496. response.c_str(), response.size(),
  15497. #endif
  15498. 0);
  15499. detail::close_socket(cli);
  15500. }
  15501. detail::close_socket(srv);
  15502. });
  15503. }
  15504. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  15505. #ifndef _WIN32
  15506. signal(SIGPIPE, SIG_IGN);
  15507. #endif
  15508. std::promise<int> port_promise;
  15509. auto port_future = port_promise.get_future();
  15510. auto server_thread =
  15511. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  15512. "Content-Type: text/plain\r\n"
  15513. "Content-Length: not-a-number\r\n"
  15514. "Connection: close\r\n"
  15515. "\r\n"
  15516. "hello");
  15517. auto port = port_future.get();
  15518. ASSERT_GT(port, 0);
  15519. Client cli("127.0.0.1", port);
  15520. auto handle = cli.open_stream("GET", "/");
  15521. EXPECT_FALSE(handle.is_valid());
  15522. server_thread.join();
  15523. }
  15524. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  15525. #ifndef _WIN32
  15526. signal(SIGPIPE, SIG_IGN);
  15527. #endif
  15528. std::promise<int> port_promise;
  15529. auto port_future = port_promise.get_future();
  15530. auto server_thread = serve_single_response(
  15531. port_promise, "HTTP/1.1 200 OK\r\n"
  15532. "Content-Type: text/plain\r\n"
  15533. "Content-Length: 99999999999999999999999999\r\n"
  15534. "Connection: close\r\n"
  15535. "\r\n"
  15536. "hello");
  15537. auto port = port_future.get();
  15538. ASSERT_GT(port, 0);
  15539. // Historically std::stoull would throw std::out_of_range here and crash
  15540. // the process, then parsing silently clamped to a bogus framing length and
  15541. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  15542. // so the stream fails to open, matching the not-a-number case above. The
  15543. // process still must NOT terminate.
  15544. Client cli("127.0.0.1", port);
  15545. auto handle = cli.open_stream("GET", "/");
  15546. EXPECT_FALSE(handle.is_valid());
  15547. server_thread.join();
  15548. }
  15549. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15550. TEST_F(OpenStreamTest, Gzip) {
  15551. Client cli("127.0.0.1", port_);
  15552. auto handle = cli.open_stream("GET", "/compressible", {},
  15553. {{"Accept-Encoding", "gzip"}});
  15554. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  15555. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15556. }
  15557. #endif
  15558. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15559. TEST_F(OpenStreamTest, Brotli) {
  15560. Client cli("127.0.0.1", port_);
  15561. auto handle =
  15562. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  15563. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  15564. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15565. }
  15566. #endif
  15567. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15568. TEST_F(OpenStreamTest, Zstd) {
  15569. Client cli("127.0.0.1", port_);
  15570. auto handle = cli.open_stream("GET", "/compressible", {},
  15571. {{"Accept-Encoding", "zstd"}});
  15572. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  15573. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15574. }
  15575. #endif
  15576. #ifdef CPPHTTPLIB_SSL_ENABLED
  15577. class SSLOpenStreamTest : public ::testing::Test {
  15578. protected:
  15579. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  15580. void SetUp() override {
  15581. svr_.Get("/hello", [](const Request &, Response &res) {
  15582. res.set_content("Hello SSL World!", "text/plain");
  15583. });
  15584. svr_.Get("/chunked", [](const Request &, Response &res) {
  15585. res.set_chunked_content_provider("text/plain",
  15586. [](size_t offset, DataSink &sink) {
  15587. if (offset < 15) {
  15588. sink.write("chunk", 5);
  15589. return true;
  15590. }
  15591. sink.done();
  15592. return true;
  15593. });
  15594. });
  15595. svr_.Post("/echo", [](const Request &req, Response &res) {
  15596. res.set_content(req.body, req.get_header_value("Content-Type"));
  15597. });
  15598. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  15599. std::string body = req.body;
  15600. res.set_chunked_content_provider(
  15601. "text/plain", [body](size_t offset, DataSink &sink) {
  15602. if (offset < body.size()) {
  15603. sink.write(body.data() + offset, body.size() - offset);
  15604. }
  15605. sink.done();
  15606. return true;
  15607. });
  15608. });
  15609. port_ = svr_.bind_to_any_port("127.0.0.1");
  15610. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15611. svr_.wait_until_ready();
  15612. }
  15613. void TearDown() override {
  15614. svr_.stop();
  15615. if (thread_.joinable()) thread_.join();
  15616. }
  15617. SSLServer svr_;
  15618. std::thread thread_;
  15619. int port_ = 0;
  15620. };
  15621. TEST_F(SSLOpenStreamTest, Basic) {
  15622. SSLClient cli("127.0.0.1", port_);
  15623. cli.enable_server_certificate_verification(false);
  15624. auto handle = cli.open_stream("GET", "/hello");
  15625. ASSERT_TRUE(handle.is_valid());
  15626. EXPECT_EQ("Hello SSL World!", read_all(handle));
  15627. }
  15628. TEST_F(SSLOpenStreamTest, Chunked) {
  15629. SSLClient cli("127.0.0.1", port_);
  15630. cli.enable_server_certificate_verification(false);
  15631. auto handle = cli.open_stream("GET", "/chunked");
  15632. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15633. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15634. "Transfer-Encoding") == "chunked");
  15635. auto body = read_all(handle);
  15636. EXPECT_EQ("chunkchunkchunk", body);
  15637. }
  15638. TEST_F(SSLOpenStreamTest, Post) {
  15639. SSLClient cli("127.0.0.1", port_);
  15640. cli.enable_server_certificate_verification(false);
  15641. auto handle =
  15642. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  15643. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15644. EXPECT_EQ(200, handle.response->status);
  15645. auto body = read_all(handle);
  15646. EXPECT_EQ("Hello SSL POST", body);
  15647. }
  15648. TEST_F(SSLOpenStreamTest, PostChunked) {
  15649. SSLClient cli("127.0.0.1", port_);
  15650. cli.enable_server_certificate_verification(false);
  15651. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  15652. "Chunked SSL Data", "text/plain");
  15653. ASSERT_TRUE(handle.is_valid());
  15654. EXPECT_EQ(200, handle.response->status);
  15655. auto body = read_all(handle);
  15656. EXPECT_EQ("Chunked SSL Data", body);
  15657. }
  15658. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  15659. // Content-Length is terminated by the server closing the connection. When the
  15660. // SSL peer sends a close_notify after the body, the client must treat it as a
  15661. // clean EOF and return a successful response rather than an error.
  15662. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  15663. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15664. ASSERT_TRUE(svr.is_valid());
  15665. svr.set_keep_alive_max_count(1);
  15666. const std::string expected_body = "Hello from connection-close response!";
  15667. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  15668. res.set_content_provider("text/plain",
  15669. [&](size_t offset, DataSink &sink) -> bool {
  15670. if (offset < expected_body.size()) {
  15671. sink.write(expected_body.data() + offset,
  15672. expected_body.size() - offset);
  15673. }
  15674. sink.done();
  15675. return true;
  15676. });
  15677. });
  15678. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  15679. auto se = detail::scope_exit([&] {
  15680. svr.stop();
  15681. listen_thread.join();
  15682. ASSERT_FALSE(svr.is_running());
  15683. });
  15684. svr.wait_until_ready();
  15685. SSLClient cli(HOST, PORT);
  15686. cli.enable_server_certificate_verification(false);
  15687. auto res = cli.Get("/no-content-length");
  15688. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  15689. EXPECT_EQ(StatusCode::OK_200, res->status);
  15690. EXPECT_EQ(expected_body, res->body);
  15691. }
  15692. #endif // CPPHTTPLIB_SSL_ENABLED
  15693. //==============================================================================
  15694. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  15695. // results for various scenarios.
  15696. //==============================================================================
  15697. TEST(ParityTest, GetVsOpenStream) {
  15698. Server svr;
  15699. const std::string path = "/parity";
  15700. const std::string content = "Parity test content: hello world";
  15701. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15702. res.set_content(content, "text/plain");
  15703. });
  15704. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15705. auto se = detail::scope_exit([&] {
  15706. svr.stop();
  15707. t.join();
  15708. ASSERT_FALSE(svr.is_running());
  15709. });
  15710. svr.wait_until_ready();
  15711. Client cli(HOST, PORT);
  15712. // Non-stream path
  15713. auto r1 = cli.Get(path);
  15714. ASSERT_TRUE(r1);
  15715. EXPECT_EQ(StatusCode::OK_200, r1->status);
  15716. // Stream path
  15717. auto h = cli.open_stream("GET", path);
  15718. ASSERT_TRUE(h.is_valid());
  15719. EXPECT_EQ(r1->body, read_all(h));
  15720. }
  15721. // Helper to compress data with provided compressor type T
  15722. template <typename Compressor>
  15723. static std::string compress_payload_for_parity(const std::string &in) {
  15724. std::string out;
  15725. Compressor compressor;
  15726. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  15727. [&](const char *data, size_t n) {
  15728. out.append(data, n);
  15729. return true;
  15730. });
  15731. EXPECT_TRUE(ok);
  15732. return out;
  15733. }
  15734. // Helper function for compression parity tests
  15735. template <typename Compressor>
  15736. static void test_compression_parity(const std::string &original,
  15737. const std::string &path,
  15738. const std::string &encoding) {
  15739. const std::string compressed =
  15740. compress_payload_for_parity<Compressor>(original);
  15741. Server svr;
  15742. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15743. res.set_content(compressed, "application/octet-stream");
  15744. res.set_header("Content-Encoding", encoding);
  15745. });
  15746. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  15747. auto se = detail::scope_exit([&] {
  15748. svr.stop();
  15749. t.join();
  15750. ASSERT_FALSE(svr.is_running());
  15751. });
  15752. svr.wait_until_ready();
  15753. Client cli(HOST, PORT);
  15754. // Non-streaming
  15755. {
  15756. auto res = cli.Get(path);
  15757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15758. EXPECT_EQ(StatusCode::OK_200, res->status);
  15759. EXPECT_EQ(original, res->body);
  15760. }
  15761. // Streaming
  15762. {
  15763. auto h = cli.open_stream("GET", path);
  15764. ASSERT_TRUE(h.is_valid());
  15765. EXPECT_EQ(original, read_all(h));
  15766. }
  15767. }
  15768. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15769. TEST(ParityTest, Gzip) {
  15770. test_compression_parity<detail::gzip_compressor>(
  15771. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  15772. }
  15773. #endif
  15774. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15775. TEST(ParityTest, Brotli) {
  15776. test_compression_parity<detail::brotli_compressor>(
  15777. "Hello, brotli parity test payload", "/parity-br", "br");
  15778. }
  15779. #endif
  15780. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15781. TEST(ParityTest, Zstd) {
  15782. test_compression_parity<detail::zstd_compressor>(
  15783. "Zstandard parity test payload", "/parity-zstd", "zstd");
  15784. }
  15785. #endif
  15786. //==============================================================================
  15787. // New Stream API Tests
  15788. //==============================================================================
  15789. inline std::string read_body(httplib::stream::Result &result) {
  15790. std::string body;
  15791. while (result.next()) {
  15792. body.append(result.data(), result.size());
  15793. }
  15794. return body;
  15795. }
  15796. TEST(ClientConnectionTest, Basic) {
  15797. httplib::ClientConnection conn;
  15798. EXPECT_FALSE(conn.is_open());
  15799. conn.sock = 1;
  15800. EXPECT_TRUE(conn.is_open());
  15801. httplib::ClientConnection conn2(std::move(conn));
  15802. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  15803. conn2.sock = INVALID_SOCKET;
  15804. }
  15805. // Unified test server for all stream::* tests
  15806. class StreamApiTest : public ::testing::Test {
  15807. protected:
  15808. void SetUp() override {
  15809. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15810. res.set_content("Hello World!", "text/plain");
  15811. });
  15812. svr_.Get("/echo-params",
  15813. [](const httplib::Request &req, httplib::Response &res) {
  15814. std::string r;
  15815. for (const auto &p : req.params) {
  15816. if (!r.empty()) r += "&";
  15817. r += p.first + "=" + p.second;
  15818. }
  15819. res.set_content(r, "text/plain");
  15820. });
  15821. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15822. res.set_content(req.body, req.get_header_value("Content-Type"));
  15823. });
  15824. svr_.Post("/echo-headers",
  15825. [](const httplib::Request &req, httplib::Response &res) {
  15826. std::string r;
  15827. for (const auto &h : req.headers)
  15828. r += h.first + ": " + h.second + "\n";
  15829. res.set_content(r, "text/plain");
  15830. });
  15831. svr_.Post("/echo-params",
  15832. [](const httplib::Request &req, httplib::Response &res) {
  15833. std::string r = "params:";
  15834. for (const auto &p : req.params)
  15835. r += p.first + "=" + p.second + ";";
  15836. res.set_content(r + " body:" + req.body, "text/plain");
  15837. });
  15838. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  15839. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  15840. });
  15841. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15842. res.set_content("PUT:" + req.body, "text/plain");
  15843. });
  15844. svr_.Patch("/echo",
  15845. [](const httplib::Request &req, httplib::Response &res) {
  15846. res.set_content("PATCH:" + req.body, "text/plain");
  15847. });
  15848. svr_.Delete(
  15849. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  15850. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  15851. "text/plain");
  15852. });
  15853. svr_.Get("/head-test",
  15854. [](const httplib::Request &, httplib::Response &res) {
  15855. res.set_content("body for HEAD", "text/plain");
  15856. });
  15857. svr_.Options("/options",
  15858. [](const httplib::Request &, httplib::Response &res) {
  15859. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  15860. });
  15861. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  15862. svr_.wait_until_ready();
  15863. }
  15864. void TearDown() override {
  15865. svr_.stop();
  15866. if (thread_.joinable()) thread_.join();
  15867. }
  15868. httplib::Server svr_;
  15869. std::thread thread_;
  15870. };
  15871. // stream::Get tests
  15872. TEST_F(StreamApiTest, GetBasic) {
  15873. httplib::Client cli(HOST, PORT);
  15874. auto result = httplib::stream::Get(cli, "/hello");
  15875. ASSERT_TRUE(result.is_valid());
  15876. EXPECT_EQ(200, result.status());
  15877. EXPECT_EQ("Hello World!", read_body(result));
  15878. }
  15879. TEST_F(StreamApiTest, GetWithParams) {
  15880. httplib::Client cli(HOST, PORT);
  15881. httplib::Params params{{"foo", "bar"}};
  15882. auto result = httplib::stream::Get(cli, "/echo-params", params);
  15883. ASSERT_TRUE(result.is_valid());
  15884. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  15885. }
  15886. TEST_F(StreamApiTest, GetConnectionError) {
  15887. httplib::Client cli(HOST, 9999);
  15888. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  15889. }
  15890. TEST_F(StreamApiTest, Get404) {
  15891. httplib::Client cli(HOST, PORT);
  15892. auto result = httplib::stream::Get(cli, "/nonexistent");
  15893. EXPECT_TRUE(result.is_valid());
  15894. EXPECT_EQ(404, result.status());
  15895. }
  15896. // stream::Post tests
  15897. TEST_F(StreamApiTest, PostBasic) {
  15898. httplib::Client cli(HOST, PORT);
  15899. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  15900. "application/json");
  15901. ASSERT_TRUE(result.is_valid());
  15902. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  15903. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  15904. }
  15905. TEST_F(StreamApiTest, PostWithHeaders) {
  15906. httplib::Client cli(HOST, PORT);
  15907. httplib::Headers headers{{"X-Custom", "value"}};
  15908. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  15909. "text/plain");
  15910. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  15911. }
  15912. TEST_F(StreamApiTest, PostWithParams) {
  15913. httplib::Client cli(HOST, PORT);
  15914. httplib::Params params{{"k", "v"}};
  15915. auto result =
  15916. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  15917. auto body = read_body(result);
  15918. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  15919. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  15920. }
  15921. TEST_F(StreamApiTest, PostLarge) {
  15922. httplib::Client cli(HOST, PORT);
  15923. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  15924. size_t total = 0;
  15925. while (result.next()) {
  15926. total += result.size();
  15927. }
  15928. EXPECT_EQ(100u * 1024u, total);
  15929. }
  15930. // stream::Put/Patch tests
  15931. TEST_F(StreamApiTest, PutAndPatch) {
  15932. httplib::Client cli(HOST, PORT);
  15933. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  15934. EXPECT_EQ("PUT:test", read_body(put));
  15935. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  15936. EXPECT_EQ("PATCH:test", read_body(patch));
  15937. }
  15938. // stream::Delete tests
  15939. TEST_F(StreamApiTest, Delete) {
  15940. httplib::Client cli(HOST, PORT);
  15941. auto del1 = httplib::stream::Delete(cli, "/resource");
  15942. EXPECT_EQ("Deleted", read_body(del1));
  15943. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  15944. EXPECT_EQ("Deleted:data", read_body(del2));
  15945. }
  15946. // stream::Head/Options tests
  15947. TEST_F(StreamApiTest, HeadAndOptions) {
  15948. httplib::Client cli(HOST, PORT);
  15949. auto head = httplib::stream::Head(cli, "/head-test");
  15950. EXPECT_TRUE(head.is_valid());
  15951. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  15952. auto opts = httplib::stream::Options(cli, "/options");
  15953. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  15954. }
  15955. // SSL stream::* tests
  15956. #ifdef CPPHTTPLIB_SSL_ENABLED
  15957. class SSLStreamApiTest : public ::testing::Test {
  15958. protected:
  15959. void SetUp() override {
  15960. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15961. res.set_content("Hello SSL!", "text/plain");
  15962. });
  15963. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15964. res.set_content(req.body, "text/plain");
  15965. });
  15966. port_ = svr_.bind_to_any_port("127.0.0.1");
  15967. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15968. svr_.wait_until_ready();
  15969. }
  15970. void TearDown() override {
  15971. svr_.stop();
  15972. if (thread_.joinable()) thread_.join();
  15973. }
  15974. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  15975. std::thread thread_;
  15976. int port_ = 0;
  15977. };
  15978. TEST_F(SSLStreamApiTest, GetAndPost) {
  15979. httplib::SSLClient cli("127.0.0.1", port_);
  15980. cli.enable_server_certificate_verification(false);
  15981. auto get = httplib::stream::Get(cli, "/hello");
  15982. EXPECT_EQ("Hello SSL!", read_body(get));
  15983. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  15984. EXPECT_EQ("test", read_body(post));
  15985. }
  15986. #endif
  15987. // Tests for Error::Timeout and Error::ConnectionClosed error types
  15988. // These errors are set in SocketStream/SSLSocketStream and propagated through
  15989. // BodyReader
  15990. TEST(ErrorHandlingTest, StreamReadTimeout) {
  15991. // Test that read timeout during streaming is detected
  15992. // Use a large content-length response where server delays mid-stream
  15993. Server svr;
  15994. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15995. // Send a large response with delay in the middle
  15996. res.set_content_provider(
  15997. 1000, // content_length
  15998. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  15999. if (offset < 100) {
  16000. // Send first 100 bytes immediately
  16001. std::string data(100, 'A');
  16002. sink.write(data.c_str(), data.size());
  16003. return true;
  16004. }
  16005. // Then delay longer than client timeout
  16006. std::this_thread::sleep_for(std::chrono::seconds(3));
  16007. std::string data(900, 'B');
  16008. sink.write(data.c_str(), data.size());
  16009. return true;
  16010. });
  16011. });
  16012. auto port = 8091;
  16013. std::thread t([&]() { svr.listen("localhost", port); });
  16014. svr.wait_until_ready();
  16015. Client cli("localhost", port);
  16016. cli.set_read_timeout(1, 0); // 1 second timeout
  16017. auto handle = cli.open_stream("GET", "/slow-stream");
  16018. ASSERT_TRUE(handle.is_valid());
  16019. char buf[256];
  16020. ssize_t total = 0;
  16021. ssize_t n;
  16022. bool got_error = false;
  16023. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16024. total += n;
  16025. }
  16026. if (n < 0) {
  16027. got_error = true;
  16028. // Should be timeout or read error
  16029. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16030. handle.get_read_error() == Error::Read)
  16031. << "Actual error: " << to_string(handle.get_read_error());
  16032. }
  16033. // Either we got an error, or we got less data than expected
  16034. EXPECT_TRUE(got_error || total < 1000)
  16035. << "Expected timeout but got all " << total << " bytes";
  16036. svr.stop();
  16037. t.join();
  16038. }
  16039. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  16040. // Test connection closed detection via BodyReader
  16041. Server svr;
  16042. std::atomic<bool> close_now{false};
  16043. svr.Get("/will-close", [&](const Request &, Response &res) {
  16044. res.set_content_provider(
  16045. 10000, // Large content_length that we won't fully send
  16046. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16047. if (offset < 100) {
  16048. std::string data(100, 'X');
  16049. sink.write(data.c_str(), data.size());
  16050. return true;
  16051. }
  16052. // Wait for signal then abort
  16053. while (!close_now) {
  16054. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16055. }
  16056. return false; // Abort - server will close connection
  16057. });
  16058. });
  16059. auto port = 8092;
  16060. std::thread t([&]() { svr.listen("localhost", port); });
  16061. svr.wait_until_ready();
  16062. Client cli("localhost", port);
  16063. auto handle = cli.open_stream("GET", "/will-close");
  16064. ASSERT_TRUE(handle.is_valid());
  16065. char buf[256];
  16066. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16067. EXPECT_GT(n, 0) << "First read should succeed";
  16068. // Signal server to close
  16069. close_now = true;
  16070. // Keep reading until error or EOF
  16071. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16072. // Keep reading
  16073. }
  16074. // Should get an error since content_length wasn't satisfied
  16075. if (n < 0) {
  16076. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16077. handle.get_read_error() == Error::Read)
  16078. << "Actual error: " << to_string(handle.get_read_error());
  16079. }
  16080. svr.stop();
  16081. t.join();
  16082. }
  16083. #ifdef CPPHTTPLIB_SSL_ENABLED
  16084. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  16085. // Test that read timeout during SSL streaming is detected
  16086. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16087. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16088. res.set_content_provider(
  16089. 1000, "text/plain",
  16090. [](size_t offset, size_t /*length*/, DataSink &sink) {
  16091. if (offset < 100) {
  16092. std::string data(100, 'A');
  16093. sink.write(data.c_str(), data.size());
  16094. return true;
  16095. }
  16096. std::this_thread::sleep_for(std::chrono::seconds(3));
  16097. std::string data(900, 'B');
  16098. sink.write(data.c_str(), data.size());
  16099. return true;
  16100. });
  16101. });
  16102. auto port = 8093;
  16103. std::thread t([&]() { svr.listen("localhost", port); });
  16104. svr.wait_until_ready();
  16105. SSLClient cli("localhost", port);
  16106. cli.enable_server_certificate_verification(false);
  16107. cli.set_read_timeout(1, 0); // 1 second timeout
  16108. auto handle = cli.open_stream("GET", "/slow-stream");
  16109. ASSERT_TRUE(handle.is_valid());
  16110. char buf[256];
  16111. ssize_t total = 0;
  16112. ssize_t n;
  16113. bool got_error = false;
  16114. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16115. total += n;
  16116. }
  16117. if (n < 0) {
  16118. got_error = true;
  16119. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16120. handle.get_read_error() == Error::Read)
  16121. << "Actual error: " << to_string(handle.get_read_error());
  16122. }
  16123. EXPECT_TRUE(got_error || total < 1000)
  16124. << "Expected timeout but got all " << total << " bytes";
  16125. svr.stop();
  16126. t.join();
  16127. }
  16128. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  16129. // Test SSL connection closed detection
  16130. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16131. std::atomic<bool> close_now{false};
  16132. svr.Get("/will-close", [&](const Request &, Response &res) {
  16133. res.set_content_provider(
  16134. 10000, "text/plain",
  16135. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16136. if (offset < 100) {
  16137. std::string data(100, 'X');
  16138. sink.write(data.c_str(), data.size());
  16139. return true;
  16140. }
  16141. while (!close_now) {
  16142. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16143. }
  16144. return false;
  16145. });
  16146. });
  16147. auto port = 8094;
  16148. std::thread t([&]() { svr.listen("localhost", port); });
  16149. svr.wait_until_ready();
  16150. SSLClient cli("localhost", port);
  16151. cli.enable_server_certificate_verification(false);
  16152. auto handle = cli.open_stream("GET", "/will-close");
  16153. ASSERT_TRUE(handle.is_valid());
  16154. char buf[256];
  16155. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16156. EXPECT_GT(n, 0);
  16157. // Signal server to close
  16158. close_now = true;
  16159. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16160. // Keep reading
  16161. }
  16162. if (n < 0) {
  16163. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16164. handle.get_read_error() == Error::Read)
  16165. << "Actual error: " << to_string(handle.get_read_error());
  16166. }
  16167. svr.stop();
  16168. t.join();
  16169. }
  16170. #endif
  16171. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  16172. using namespace httplib;
  16173. // Create a test file
  16174. const char *fname = "etag_testfile.txt";
  16175. const char *content = "etag-content";
  16176. {
  16177. std::ofstream ofs(fname);
  16178. ofs << content;
  16179. ASSERT_TRUE(ofs.good());
  16180. }
  16181. Server svr;
  16182. svr.set_mount_point("/static", ".");
  16183. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16184. svr.wait_until_ready();
  16185. Client cli(HOST, PORT);
  16186. // First request: should get 200 with ETag header
  16187. auto res1 = cli.Get("/static/etag_testfile.txt");
  16188. ASSERT_TRUE(res1);
  16189. ASSERT_EQ(200, res1->status);
  16190. ASSERT_TRUE(res1->has_header("ETag"));
  16191. std::string etag = res1->get_header_value("ETag");
  16192. EXPECT_FALSE(etag.empty());
  16193. // Verify ETag format: W/"hex-hex"
  16194. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  16195. EXPECT_EQ('W', etag[0]);
  16196. EXPECT_EQ('/', etag[1]);
  16197. EXPECT_EQ('"', etag[2]);
  16198. EXPECT_EQ('"', etag.back());
  16199. // Exact match: expect 304 Not Modified
  16200. Headers h2 = {{"If-None-Match", etag}};
  16201. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  16202. ASSERT_TRUE(res2);
  16203. EXPECT_EQ(304, res2->status);
  16204. // Wildcard match: expect 304 Not Modified
  16205. Headers h3 = {{"If-None-Match", "*"}};
  16206. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  16207. ASSERT_TRUE(res3);
  16208. EXPECT_EQ(304, res3->status);
  16209. // Non-matching ETag: expect 200
  16210. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  16211. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  16212. ASSERT_TRUE(res4);
  16213. EXPECT_EQ(200, res4->status);
  16214. // Multiple ETags with one matching: expect 304
  16215. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  16216. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  16217. ASSERT_TRUE(res5);
  16218. EXPECT_EQ(304, res5->status);
  16219. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  16220. // that equivalent to the single comma-separated list above, so the match on
  16221. // the second line must still be found.
  16222. Headers h6;
  16223. h6.emplace("If-None-Match", "W/\"other\"");
  16224. h6.emplace("If-None-Match", etag);
  16225. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  16226. ASSERT_TRUE(res6);
  16227. EXPECT_EQ(304, res6->status);
  16228. svr.stop();
  16229. t.join();
  16230. std::remove(fname);
  16231. }
  16232. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  16233. using namespace httplib;
  16234. Server svr;
  16235. svr.set_mount_point("/static", ".");
  16236. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16237. svr.wait_until_ready();
  16238. Client cli(HOST, PORT);
  16239. // Send If-None-Match: * to a non-existent file
  16240. Headers h = {{"If-None-Match", "*"}};
  16241. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  16242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16243. EXPECT_EQ(404, res->status);
  16244. svr.stop();
  16245. t.join();
  16246. }
  16247. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  16248. using namespace httplib;
  16249. // Create a test file
  16250. const char *fname = "etag_boundary_testfile.txt";
  16251. const char *content = "boundary-test";
  16252. {
  16253. std::ofstream ofs(fname);
  16254. ofs << content;
  16255. ASSERT_TRUE(ofs.good());
  16256. }
  16257. Server svr;
  16258. svr.set_mount_point("/static", ".");
  16259. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16260. svr.wait_until_ready();
  16261. Client cli(HOST, PORT);
  16262. // Get the actual ETag
  16263. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  16264. ASSERT_TRUE(res1);
  16265. ASSERT_EQ(200, res1->status);
  16266. ASSERT_TRUE(res1->has_header("ETag"));
  16267. std::string etag = res1->get_header_value("ETag");
  16268. // Test 1: Very long ETag value (longer than actual ETag)
  16269. // Should NOT match and return 200 (not trigger out-of-bounds read)
  16270. Headers h1 = {{"If-None-Match", "W/"
  16271. "\"very-long-etag-value-that-is-much-longer-"
  16272. "than-the-actual-etag-value\""}};
  16273. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  16274. ASSERT_TRUE(res2);
  16275. EXPECT_EQ(200, res2->status); // Should not match
  16276. // Test 2: Long string followed by wildcard
  16277. // Should match on "*" and return 304 (without out-of-bounds read on the long
  16278. // string)
  16279. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  16280. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  16281. ASSERT_TRUE(res3);
  16282. EXPECT_EQ(304, res3->status); // Should match on "*"
  16283. // Test 3: Wildcard followed by long string
  16284. // Should match on "*" immediately and return 304
  16285. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  16286. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  16287. ASSERT_TRUE(res4);
  16288. EXPECT_EQ(304, res4->status); // Should match on "*"
  16289. // Test 4: Multiple long non-matching values
  16290. // Should NOT match and return 200 (test that all comparisons are safe)
  16291. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  16292. "W/\"second-long-non-matching-value\", "
  16293. "W/\"third-long-non-matching-value\""}};
  16294. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  16295. ASSERT_TRUE(res5);
  16296. EXPECT_EQ(200, res5->status); // Should not match
  16297. // Test 5: Single character that is not "*" (edge case)
  16298. Headers h5 = {{"If-None-Match", "X"}};
  16299. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  16300. ASSERT_TRUE(res6);
  16301. EXPECT_EQ(200, res6->status); // Should not match
  16302. svr.stop();
  16303. t.join();
  16304. std::remove(fname);
  16305. }
  16306. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  16307. using namespace httplib;
  16308. // Create a test file
  16309. const char *fname = "ims_testfile.txt";
  16310. const char *content = "if-modified-since-test";
  16311. {
  16312. std::ofstream ofs(fname);
  16313. ofs << content;
  16314. ASSERT_TRUE(ofs.good());
  16315. }
  16316. Server svr;
  16317. svr.set_mount_point("/static", ".");
  16318. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16319. svr.wait_until_ready();
  16320. Client cli(HOST, PORT);
  16321. // First request: should get 200 with Last-Modified header
  16322. auto res1 = cli.Get("/static/ims_testfile.txt");
  16323. ASSERT_TRUE(res1);
  16324. ASSERT_EQ(200, res1->status);
  16325. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16326. std::string last_modified = res1->get_header_value("Last-Modified");
  16327. EXPECT_FALSE(last_modified.empty());
  16328. // If-Modified-Since with same time: expect 304
  16329. Headers h2 = {{"If-Modified-Since", last_modified}};
  16330. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  16331. ASSERT_TRUE(res2);
  16332. EXPECT_EQ(304, res2->status);
  16333. // If-Modified-Since with future time: expect 304
  16334. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16335. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  16336. ASSERT_TRUE(res3);
  16337. EXPECT_EQ(304, res3->status);
  16338. // If-Modified-Since with past time: expect 200
  16339. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16340. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  16341. ASSERT_TRUE(res4);
  16342. EXPECT_EQ(200, res4->status);
  16343. // If-None-Match takes precedence over If-Modified-Since
  16344. // (send matching ETag with old If-Modified-Since -> should still be 304)
  16345. ASSERT_TRUE(res1->has_header("ETag"));
  16346. std::string etag = res1->get_header_value("ETag");
  16347. Headers h5 = {{"If-None-Match", etag},
  16348. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16349. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  16350. ASSERT_TRUE(res5);
  16351. EXPECT_EQ(304, res5->status);
  16352. svr.stop();
  16353. t.join();
  16354. std::remove(fname);
  16355. }
  16356. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  16357. using namespace httplib;
  16358. Server svr;
  16359. // Endpoint that returns compressible content
  16360. svr.Get("/compressible", [](const Request &, Response &res) {
  16361. // Return a large enough body to trigger compression
  16362. std::string body(1000, 'a');
  16363. res.set_content(body, "text/plain");
  16364. });
  16365. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16366. svr.wait_until_ready();
  16367. Client cli(HOST, PORT);
  16368. // Request with gzip support: should get Vary header when compressed
  16369. cli.set_compress(true);
  16370. auto res1 = cli.Get("/compressible");
  16371. ASSERT_TRUE(res1);
  16372. EXPECT_EQ(200, res1->status);
  16373. // If Content-Encoding is set, Vary should also be set
  16374. if (res1->has_header("Content-Encoding")) {
  16375. EXPECT_TRUE(res1->has_header("Vary"));
  16376. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  16377. }
  16378. // Request without Accept-Encoding header: should not have compression
  16379. Headers h_no_compress;
  16380. auto res2 = cli.Get("/compressible", h_no_compress);
  16381. ASSERT_TRUE(res2);
  16382. EXPECT_EQ(200, res2->status);
  16383. // Verify Vary header is present when compression is applied
  16384. // (the exact behavior depends on server configuration)
  16385. svr.stop();
  16386. t.join();
  16387. }
  16388. TEST(ETagTest, IfRangeWithETag) {
  16389. using namespace httplib;
  16390. // Create a test file with known content
  16391. const char *fname = "if_range_testfile.txt";
  16392. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  16393. {
  16394. std::ofstream ofs(fname);
  16395. ofs << content;
  16396. ASSERT_TRUE(ofs.good());
  16397. }
  16398. Server svr;
  16399. svr.set_mount_point("/static", ".");
  16400. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16401. svr.wait_until_ready();
  16402. Client cli(HOST, PORT);
  16403. // First request: get ETag
  16404. auto res1 = cli.Get("/static/if_range_testfile.txt");
  16405. ASSERT_TRUE(res1);
  16406. ASSERT_EQ(200, res1->status);
  16407. ASSERT_TRUE(res1->has_header("ETag"));
  16408. std::string etag = res1->get_header_value("ETag");
  16409. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  16410. // Since our server generates weak ETags (W/"..."), If-Range with our
  16411. // ETag should NOT result in partial content - it should return full content.
  16412. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  16413. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  16414. ASSERT_TRUE(res2);
  16415. // Weak ETag in If-Range -> full content (200), not partial (206)
  16416. EXPECT_EQ(200, res2->status);
  16417. EXPECT_EQ(content, res2->body);
  16418. EXPECT_FALSE(res2->has_header("Content-Range"));
  16419. // Range request with non-matching If-Range (ETag): should get 200 (full
  16420. // content)
  16421. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  16422. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  16423. ASSERT_TRUE(res3);
  16424. EXPECT_EQ(200, res3->status);
  16425. EXPECT_EQ(content, res3->body);
  16426. EXPECT_FALSE(res3->has_header("Content-Range"));
  16427. // Range request with strong ETag (hypothetical - our server doesn't generate
  16428. // strong ETags, but if client sends a strong ETag that doesn't match, it
  16429. // should return full content)
  16430. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  16431. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  16432. ASSERT_TRUE(res4);
  16433. EXPECT_EQ(200, res4->status);
  16434. EXPECT_EQ(content, res4->body);
  16435. EXPECT_FALSE(res4->has_header("Content-Range"));
  16436. svr.stop();
  16437. t.join();
  16438. std::remove(fname);
  16439. }
  16440. TEST(ETagTest, IfRangeWithDate) {
  16441. using namespace httplib;
  16442. // Create a test file
  16443. const char *fname = "if_range_date_testfile.txt";
  16444. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  16445. {
  16446. std::ofstream ofs(fname);
  16447. ofs << content;
  16448. ASSERT_TRUE(ofs.good());
  16449. }
  16450. Server svr;
  16451. svr.set_mount_point("/static", ".");
  16452. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16453. svr.wait_until_ready();
  16454. Client cli(HOST, PORT);
  16455. // First request: get Last-Modified
  16456. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  16457. ASSERT_TRUE(res1);
  16458. ASSERT_EQ(200, res1->status);
  16459. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16460. std::string last_modified = res1->get_header_value("Last-Modified");
  16461. // Range request with matching If-Range (date): should get 206
  16462. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  16463. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  16464. ASSERT_TRUE(res2);
  16465. EXPECT_EQ(206, res2->status);
  16466. EXPECT_EQ("FGHIJ", res2->body);
  16467. // Range request with old If-Range date: should get 200 (full content)
  16468. Headers h3 = {{"Range", "bytes=5-9"},
  16469. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16470. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  16471. ASSERT_TRUE(res3);
  16472. EXPECT_EQ(200, res3->status);
  16473. EXPECT_EQ(content, res3->body);
  16474. // Range request with future If-Range date: should get 206
  16475. Headers h4 = {{"Range", "bytes=0-4"},
  16476. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16477. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  16478. ASSERT_TRUE(res4);
  16479. EXPECT_EQ(206, res4->status);
  16480. EXPECT_EQ("ABCDE", res4->body);
  16481. svr.stop();
  16482. t.join();
  16483. std::remove(fname);
  16484. }
  16485. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  16486. using namespace httplib;
  16487. const char *fname = "etag_malformed.txt";
  16488. const char *content = "malformed-etag";
  16489. {
  16490. std::ofstream ofs(fname);
  16491. ofs << content;
  16492. ASSERT_TRUE(ofs.good());
  16493. }
  16494. Server svr;
  16495. svr.set_mount_point("/static", ".");
  16496. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16497. svr.wait_until_ready();
  16498. Client cli(HOST, PORT);
  16499. // baseline: should get 200 and an ETag
  16500. auto res1 = cli.Get("/static/etag_malformed.txt");
  16501. ASSERT_TRUE(res1);
  16502. ASSERT_EQ(200, res1->status);
  16503. ASSERT_TRUE(res1->has_header("ETag"));
  16504. // Malformed ETag value (missing quotes) should be treated as non-matching
  16505. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  16506. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  16507. ASSERT_TRUE(res_bad);
  16508. EXPECT_EQ(200, res_bad->status);
  16509. // Whitespace-only header value should be considered invalid / non-matching
  16510. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  16511. "Host: localhost\r\n"
  16512. "If-None-Match: \r\n"
  16513. "Connection: close\r\n"
  16514. "\r\n";
  16515. std::string out;
  16516. ASSERT_TRUE(send_request(5, raw_req, &out));
  16517. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16518. svr.stop();
  16519. t.join();
  16520. std::remove(fname);
  16521. }
  16522. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  16523. using namespace httplib;
  16524. const char *fname = "ims_invalid_format.txt";
  16525. const char *content = "ims-bad-format";
  16526. {
  16527. std::ofstream ofs(fname);
  16528. ofs << content;
  16529. ASSERT_TRUE(ofs.good());
  16530. }
  16531. Server svr;
  16532. svr.set_mount_point("/static", ".");
  16533. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16534. svr.wait_until_ready();
  16535. Client cli(HOST, PORT);
  16536. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  16537. ASSERT_TRUE(res1);
  16538. ASSERT_EQ(200, res1->status);
  16539. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16540. // If-Modified-Since with invalid format should not result in 304
  16541. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  16542. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  16543. ASSERT_TRUE(res_bad);
  16544. EXPECT_EQ(200, res_bad->status);
  16545. // If-Range with invalid date format should be treated as mismatch -> full
  16546. // content (200)
  16547. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  16548. {"If-Range", "invalid-date"}};
  16549. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  16550. ASSERT_TRUE(res_ifrange);
  16551. EXPECT_EQ(200, res_ifrange->status);
  16552. svr.stop();
  16553. t.join();
  16554. std::remove(fname);
  16555. }
  16556. TEST(ETagTest, IfRangeWithMalformedETag) {
  16557. using namespace httplib;
  16558. const char *fname = "ifrange_malformed.txt";
  16559. const std::string content = "0123456789";
  16560. {
  16561. std::ofstream ofs(fname);
  16562. ofs << content;
  16563. ASSERT_TRUE(ofs.good());
  16564. }
  16565. Server svr;
  16566. svr.set_mount_point("/static", ".");
  16567. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16568. svr.wait_until_ready();
  16569. Client cli(HOST, PORT);
  16570. // First request: get ETag
  16571. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  16572. ASSERT_TRUE(res1);
  16573. ASSERT_EQ(200, res1->status);
  16574. ASSERT_TRUE(res1->has_header("ETag"));
  16575. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  16576. // full content (200)
  16577. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  16578. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  16579. ASSERT_TRUE(res2);
  16580. EXPECT_EQ(200, res2->status);
  16581. EXPECT_EQ(content, res2->body);
  16582. svr.stop();
  16583. t.join();
  16584. std::remove(fname);
  16585. }
  16586. TEST(ETagTest, ExtremeLargeDateValues) {
  16587. using namespace httplib;
  16588. const char *fname = "ims_extreme_date.txt";
  16589. const char *content = "ims-extreme-date";
  16590. {
  16591. std::ofstream ofs(fname);
  16592. ofs << content;
  16593. ASSERT_TRUE(ofs.good());
  16594. }
  16595. Server svr;
  16596. svr.set_mount_point("/static", ".");
  16597. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16598. svr.wait_until_ready();
  16599. Client cli(HOST, PORT);
  16600. auto res1 = cli.Get(std::string("/static/") + fname);
  16601. ASSERT_TRUE(res1);
  16602. ASSERT_EQ(200, res1->status);
  16603. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16604. // Extremely large year that may overflow date parsing routines.
  16605. Headers h_large_date = {
  16606. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16607. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  16608. ASSERT_TRUE(res_bad);
  16609. // Expect server to treat this as invalid/mismatch and return full content
  16610. EXPECT_EQ(200, res_bad->status);
  16611. // If-Range with extremely large date should be treated as mismatch -> full
  16612. // content (200)
  16613. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  16614. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16615. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  16616. ASSERT_TRUE(res_ifrange);
  16617. EXPECT_EQ(200, res_ifrange->status);
  16618. svr.stop();
  16619. t.join();
  16620. std::remove(fname);
  16621. }
  16622. TEST(ETagTest, NegativeFileModificationTime) {
  16623. using namespace httplib;
  16624. const char *fname = "ims_negative_mtime.txt";
  16625. const std::string content = "negative-mtime";
  16626. {
  16627. std::ofstream ofs(fname);
  16628. ofs << content;
  16629. ASSERT_TRUE(ofs.good());
  16630. }
  16631. // Try to set file mtime to a negative value. This may fail on some
  16632. // platforms/filesystems; if it fails, the test will still verify server
  16633. // behaves safely by performing a regular conditional request.
  16634. #if defined(__APPLE__) || defined(__linux__)
  16635. bool set_negative = false;
  16636. do {
  16637. struct timeval times[2];
  16638. // access time: now
  16639. times[0].tv_sec = time(nullptr);
  16640. times[0].tv_usec = 0;
  16641. // modification time: negative (e.g., -1)
  16642. times[1].tv_sec = -1;
  16643. times[1].tv_usec = 0;
  16644. if (utimes(fname, times) == 0) { set_negative = true; }
  16645. } while (0);
  16646. #else
  16647. bool set_negative = false;
  16648. #endif
  16649. Server svr;
  16650. svr.set_mount_point("/static", ".");
  16651. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16652. svr.wait_until_ready();
  16653. Client cli(HOST, PORT);
  16654. auto res1 = cli.Get(std::string("/static/") + fname);
  16655. ASSERT_TRUE(res1);
  16656. ASSERT_EQ(200, res1->status);
  16657. bool has_last_modified = res1->has_header("Last-Modified");
  16658. std::string last_modified;
  16659. if (has_last_modified) {
  16660. last_modified = res1->get_header_value("Last-Modified");
  16661. }
  16662. if (set_negative) {
  16663. // If we successfully set a negative mtime, ensure server returns a
  16664. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  16665. // with an old date and ensure server handles it without crash.
  16666. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  16667. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  16668. ASSERT_TRUE(res2);
  16669. // Behavior may vary; at minimum ensure server responds (200 or 304).
  16670. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  16671. } else {
  16672. // Could not set negative mtime on this platform; fall back to verifying
  16673. // that normal invalid/malformed dates are treated safely (non-304).
  16674. Headers h_bad_date = {
  16675. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16676. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  16677. ASSERT_TRUE(res_bad);
  16678. EXPECT_EQ(200, res_bad->status);
  16679. }
  16680. svr.stop();
  16681. t.join();
  16682. std::remove(fname);
  16683. }
  16684. //==============================================================================
  16685. // SSE Parsing Tests
  16686. //==============================================================================
  16687. class SSEParsingTest : public ::testing::Test {
  16688. protected:
  16689. // Test helper that mimics SSE parsing behavior
  16690. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  16691. int &retry_ms) {
  16692. // Blank line signals end of event
  16693. if (line.empty() || line == "\r") { return true; }
  16694. // Lines starting with ':' are comments (ignored)
  16695. if (!line.empty() && line[0] == ':') { return false; }
  16696. // Find the colon separator
  16697. auto colon_pos = line.find(':');
  16698. if (colon_pos == std::string::npos) {
  16699. // Line with no colon is treated as field name with empty value
  16700. return false;
  16701. }
  16702. std::string field = line.substr(0, colon_pos);
  16703. std::string value;
  16704. // Value starts after colon, skip optional single space
  16705. if (colon_pos + 1 < line.size()) {
  16706. size_t value_start = colon_pos + 1;
  16707. if (line[value_start] == ' ') { value_start++; }
  16708. value = line.substr(value_start);
  16709. // Remove trailing \r if present
  16710. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  16711. }
  16712. // Handle known fields
  16713. if (field == "event") {
  16714. msg.event = value;
  16715. } else if (field == "data") {
  16716. // Multiple data lines are concatenated with newlines
  16717. if (!msg.data.empty()) { msg.data += "\n"; }
  16718. msg.data += value;
  16719. } else if (field == "id") {
  16720. // Empty id is valid (clears the last event ID)
  16721. msg.id = value;
  16722. } else if (field == "retry") {
  16723. // Parse retry interval in milliseconds
  16724. {
  16725. int v = 0;
  16726. auto res =
  16727. detail::from_chars(value.data(), value.data() + value.size(), v);
  16728. if (res.ec == std::errc{}) { retry_ms = v; }
  16729. }
  16730. }
  16731. // Unknown fields are ignored per SSE spec
  16732. return false;
  16733. }
  16734. };
  16735. // Test: Single-line data
  16736. TEST_F(SSEParsingTest, SingleLineData) {
  16737. sse::SSEMessage msg;
  16738. int retry_ms = 3000;
  16739. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  16740. EXPECT_EQ(msg.data, "hello");
  16741. EXPECT_EQ(msg.event, "message");
  16742. // Blank line ends event
  16743. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16744. }
  16745. // Test: Multi-line data
  16746. TEST_F(SSEParsingTest, MultiLineData) {
  16747. sse::SSEMessage msg;
  16748. int retry_ms = 3000;
  16749. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  16750. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  16751. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  16752. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  16753. }
  16754. // Test: Custom event types
  16755. TEST_F(SSEParsingTest, CustomEventType) {
  16756. sse::SSEMessage msg;
  16757. int retry_ms = 3000;
  16758. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  16759. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  16760. EXPECT_EQ(msg.event, "update");
  16761. EXPECT_EQ(msg.data, "payload");
  16762. }
  16763. // Test: Event ID handling
  16764. TEST_F(SSEParsingTest, EventIdHandling) {
  16765. sse::SSEMessage msg;
  16766. int retry_ms = 3000;
  16767. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  16768. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  16769. EXPECT_EQ(msg.id, "12345");
  16770. }
  16771. // Test: Empty event ID (clears last event ID)
  16772. TEST_F(SSEParsingTest, EmptyEventId) {
  16773. sse::SSEMessage msg;
  16774. msg.id = "previous";
  16775. int retry_ms = 3000;
  16776. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  16777. EXPECT_EQ(msg.id, "");
  16778. }
  16779. // Test: Retry field parsing
  16780. TEST_F(SSEParsingTest, RetryFieldParsing) {
  16781. sse::SSEMessage msg;
  16782. int retry_ms = 3000;
  16783. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  16784. EXPECT_EQ(retry_ms, 5000);
  16785. }
  16786. // Test: Invalid retry value
  16787. TEST_F(SSEParsingTest, InvalidRetryValue) {
  16788. sse::SSEMessage msg;
  16789. int retry_ms = 3000;
  16790. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  16791. EXPECT_EQ(retry_ms, 3000); // Unchanged
  16792. }
  16793. // Test: Comments (lines starting with :)
  16794. TEST_F(SSEParsingTest, CommentsIgnored) {
  16795. sse::SSEMessage msg;
  16796. int retry_ms = 3000;
  16797. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  16798. EXPECT_EQ(msg.data, "");
  16799. EXPECT_EQ(msg.event, "message");
  16800. }
  16801. // Test: Colon in value
  16802. TEST_F(SSEParsingTest, ColonInValue) {
  16803. sse::SSEMessage msg;
  16804. int retry_ms = 3000;
  16805. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  16806. EXPECT_EQ(msg.data, "hello:world:test");
  16807. }
  16808. // Test: Line with no colon (field name only)
  16809. TEST_F(SSEParsingTest, FieldNameOnly) {
  16810. sse::SSEMessage msg;
  16811. int retry_ms = 3000;
  16812. // According to SSE spec, this is treated as field name with empty value
  16813. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  16814. // Since we don't recognize "data" without colon, data should be empty
  16815. EXPECT_EQ(msg.data, "");
  16816. }
  16817. // Test: Trailing \r handling
  16818. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  16819. sse::SSEMessage msg;
  16820. int retry_ms = 3000;
  16821. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  16822. EXPECT_EQ(msg.data, "hello");
  16823. }
  16824. // Test: Unknown fields ignored
  16825. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  16826. sse::SSEMessage msg;
  16827. int retry_ms = 3000;
  16828. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  16829. EXPECT_EQ(msg.data, "");
  16830. EXPECT_EQ(msg.event, "message");
  16831. }
  16832. // Test: Space after colon is optional
  16833. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  16834. sse::SSEMessage msg1, msg2;
  16835. int retry_ms = 3000;
  16836. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  16837. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  16838. EXPECT_EQ(msg1.data, "hello");
  16839. EXPECT_EQ(msg2.data, "hello");
  16840. }
  16841. // Test: SSEMessage clear
  16842. TEST_F(SSEParsingTest, MessageClear) {
  16843. sse::SSEMessage msg;
  16844. msg.event = "custom";
  16845. msg.data = "some data";
  16846. msg.id = "123";
  16847. msg.clear();
  16848. EXPECT_EQ(msg.event, "message");
  16849. EXPECT_EQ(msg.data, "");
  16850. EXPECT_EQ(msg.id, "");
  16851. }
  16852. // Test: Complete event parsing
  16853. TEST_F(SSEParsingTest, CompleteEventParsing) {
  16854. sse::SSEMessage msg;
  16855. int retry_ms = 3000;
  16856. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  16857. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  16858. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  16859. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  16860. // Blank line ends event
  16861. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16862. EXPECT_EQ(msg.event, "notification");
  16863. EXPECT_EQ(msg.id, "evt-42");
  16864. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  16865. EXPECT_EQ(retry_ms, 1000);
  16866. }
  16867. //==============================================================================
  16868. // Integration Tests with Server
  16869. //==============================================================================
  16870. class SSEIntegrationTest : public ::testing::Test {
  16871. protected:
  16872. void SetUp() override {
  16873. stop_server_.store(false);
  16874. events_.clear();
  16875. server_ = httplib::detail::make_unique<Server>();
  16876. setup_server();
  16877. start_server();
  16878. }
  16879. void TearDown() override {
  16880. stop_server_.store(true);
  16881. event_cv_.notify_all();
  16882. server_->stop();
  16883. if (server_thread_.joinable()) { server_thread_.join(); }
  16884. }
  16885. void setup_server() {
  16886. // Simple SSE endpoint
  16887. server_->Get("/events", [this](const Request &req, Response &res) {
  16888. auto last_id = req.get_header_value("Last-Event-ID");
  16889. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  16890. res.set_chunked_content_provider(
  16891. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  16892. std::unique_lock<std::mutex> lock(event_mutex_);
  16893. if (event_cv_.wait_for(
  16894. lock, std::chrono::milliseconds(200), [this] {
  16895. return !events_.empty() || stop_server_.load();
  16896. })) {
  16897. if (stop_server_.load()) { return false; }
  16898. if (!events_.empty()) {
  16899. std::string event = events_.front();
  16900. events_.erase(events_.begin());
  16901. sink.write(event.data(), event.size());
  16902. return true;
  16903. }
  16904. }
  16905. return !stop_server_.load();
  16906. });
  16907. });
  16908. // Endpoint that returns error
  16909. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  16910. res.status = 500;
  16911. res.set_content("Internal Server Error", "text/plain");
  16912. });
  16913. // Endpoint for custom event types
  16914. server_->Get("/custom-events", [](const Request &, Response &res) {
  16915. res.set_chunked_content_provider(
  16916. "text/event-stream", [](size_t offset, DataSink &sink) {
  16917. if (offset == 0) {
  16918. std::string event = "event: update\ndata: updated\n\n"
  16919. "event: delete\ndata: deleted\n\n";
  16920. sink.write(event.data(), event.size());
  16921. }
  16922. return false; // End stream after sending
  16923. });
  16924. });
  16925. }
  16926. void start_server() {
  16927. port_ = server_->bind_to_any_port(HOST);
  16928. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16929. // Wait for server to start
  16930. while (!server_->is_running()) {
  16931. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16932. }
  16933. }
  16934. int get_port() const { return port_; }
  16935. void send_event(const std::string &event) {
  16936. std::lock_guard<std::mutex> lock(event_mutex_);
  16937. events_.push_back(event);
  16938. event_cv_.notify_all();
  16939. }
  16940. std::unique_ptr<Server> server_;
  16941. std::thread server_thread_;
  16942. std::mutex event_mutex_;
  16943. std::condition_variable event_cv_;
  16944. std::vector<std::string> events_;
  16945. std::atomic<bool> stop_server_{false};
  16946. std::string last_received_event_id_;
  16947. int port_ = 0;
  16948. };
  16949. // Test: Successful connection and on_open callback
  16950. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  16951. // Add a simple endpoint that sends one event and closes
  16952. server_->Get("/simple-event", [](const Request &, Response &res) {
  16953. res.set_chunked_content_provider(
  16954. "text/event-stream", [](size_t offset, DataSink &sink) {
  16955. if (offset == 0) {
  16956. std::string event = "data: hello\n\n";
  16957. sink.write(event.data(), event.size());
  16958. }
  16959. return false; // Close stream after sending
  16960. });
  16961. });
  16962. Client client("localhost", get_port());
  16963. sse::SSEClient sse(client, "/simple-event");
  16964. std::atomic<bool> open_called{false};
  16965. std::atomic<bool> message_received{false};
  16966. sse.on_open([&open_called]() { open_called.store(true); });
  16967. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  16968. if (msg.data == "hello") { message_received.store(true); }
  16969. });
  16970. sse.set_reconnect_interval(100);
  16971. sse.set_max_reconnect_attempts(1);
  16972. // Start async
  16973. sse.start_async();
  16974. // Wait for message to be processed
  16975. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16976. sse.stop();
  16977. EXPECT_TRUE(open_called.load());
  16978. EXPECT_TRUE(message_received.load());
  16979. }
  16980. // Test: on_message callback
  16981. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  16982. // Endpoint that sends multiple events then closes
  16983. server_->Get("/multi-event", [](const Request &, Response &res) {
  16984. res.set_chunked_content_provider(
  16985. "text/event-stream", [](size_t offset, DataSink &sink) {
  16986. if (offset == 0) {
  16987. std::string events = "data: message1\n\ndata: message2\n\n";
  16988. sink.write(events.data(), events.size());
  16989. }
  16990. return false;
  16991. });
  16992. });
  16993. Client client("localhost", get_port());
  16994. sse::SSEClient sse(client, "/multi-event");
  16995. std::vector<std::string> received_messages;
  16996. std::mutex messages_mutex;
  16997. sse.on_message([&](const sse::SSEMessage &msg) {
  16998. std::lock_guard<std::mutex> lock(messages_mutex);
  16999. received_messages.push_back(msg.data);
  17000. });
  17001. sse.set_reconnect_interval(100);
  17002. sse.set_max_reconnect_attempts(1);
  17003. sse.start_async();
  17004. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17005. sse.stop();
  17006. std::lock_guard<std::mutex> lock(messages_mutex);
  17007. EXPECT_GE(received_messages.size(), 2u);
  17008. if (received_messages.size() >= 2) {
  17009. EXPECT_EQ(received_messages[0], "message1");
  17010. EXPECT_EQ(received_messages[1], "message2");
  17011. }
  17012. }
  17013. // Test: on_event for specific types
  17014. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  17015. Client client("localhost", get_port());
  17016. sse::SSEClient sse(client, "/custom-events");
  17017. std::atomic<bool> update_received{false};
  17018. std::atomic<bool> delete_received{false};
  17019. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  17020. if (msg.data == "updated") { update_received.store(true); }
  17021. });
  17022. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  17023. if (msg.data == "deleted") { delete_received.store(true); }
  17024. });
  17025. sse.set_max_reconnect_attempts(1);
  17026. sse.start_async();
  17027. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  17028. sse.stop();
  17029. EXPECT_TRUE(update_received.load());
  17030. EXPECT_TRUE(delete_received.load());
  17031. }
  17032. // Test: on_error callback on connection failure
  17033. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  17034. // Connect to a non-existent port
  17035. Client client("localhost", 59999);
  17036. sse::SSEClient sse(client, "/events");
  17037. std::atomic<bool> error_called{false};
  17038. Error received_error = Error::Success;
  17039. sse.on_error([&](Error err) {
  17040. error_called.store(true);
  17041. received_error = err;
  17042. });
  17043. sse.set_reconnect_interval(50);
  17044. sse.set_max_reconnect_attempts(1);
  17045. sse.start_async();
  17046. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17047. sse.stop();
  17048. EXPECT_TRUE(error_called.load());
  17049. EXPECT_NE(received_error, Error::Success);
  17050. }
  17051. // Test: Last-Event-ID header sent on reconnect
  17052. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  17053. // Endpoint that sends event with ID
  17054. server_->Get("/event-with-id", [](const Request &, Response &res) {
  17055. res.set_chunked_content_provider(
  17056. "text/event-stream", [](size_t offset, DataSink &sink) {
  17057. if (offset == 0) {
  17058. std::string event = "id: evt-123\ndata: test\n\n";
  17059. sink.write(event.data(), event.size());
  17060. }
  17061. return false;
  17062. });
  17063. });
  17064. Client client("localhost", get_port());
  17065. sse::SSEClient sse(client, "/event-with-id");
  17066. std::atomic<bool> id_received{false};
  17067. sse.on_message([&](const sse::SSEMessage &msg) {
  17068. if (!msg.id.empty()) { id_received.store(true); }
  17069. });
  17070. sse.set_reconnect_interval(100);
  17071. sse.set_max_reconnect_attempts(1);
  17072. sse.start_async();
  17073. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17074. sse.stop();
  17075. EXPECT_TRUE(id_received.load());
  17076. EXPECT_EQ(sse.last_event_id(), "evt-123");
  17077. }
  17078. // Test: Manual stop
  17079. TEST_F(SSEIntegrationTest, ManualStop) {
  17080. // Endpoint that sends one event and stays open briefly
  17081. std::atomic<bool> handler_running{true};
  17082. server_->Get("/stay-open", [&handler_running](const Request &,
  17083. Response &res) {
  17084. res.set_chunked_content_provider(
  17085. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  17086. if (offset == 0) {
  17087. std::string event = "data: connected\n\n";
  17088. sink.write(event.data(), event.size());
  17089. }
  17090. // Keep connection open while handler_running is true
  17091. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  17092. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17093. }
  17094. return false;
  17095. });
  17096. });
  17097. Client client("localhost", get_port());
  17098. sse::SSEClient sse(client, "/stay-open");
  17099. std::atomic<bool> connected{false};
  17100. sse.on_open([&connected]() { connected.store(true); });
  17101. sse.set_reconnect_interval(100);
  17102. sse.set_max_reconnect_attempts(1);
  17103. sse.start_async();
  17104. // Wait for connection to establish
  17105. for (int i = 0; i < 20 && !connected.load(); ++i) {
  17106. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17107. }
  17108. EXPECT_TRUE(connected.load());
  17109. EXPECT_TRUE(sse.is_connected());
  17110. // Signal handler to stop
  17111. handler_running.store(false);
  17112. // Stop SSE client
  17113. sse.stop();
  17114. EXPECT_FALSE(sse.is_connected());
  17115. }
  17116. // Test: SSEClient with custom headers
  17117. TEST_F(SSEIntegrationTest, CustomHeaders) {
  17118. // Setup a server endpoint that checks for custom header
  17119. std::atomic<bool> header_received{false};
  17120. server_->Get("/header-check", [&](const Request &req, Response &res) {
  17121. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  17122. header_received.store(true);
  17123. }
  17124. res.set_chunked_content_provider("text/event-stream",
  17125. [](size_t, DataSink &) { return false; });
  17126. });
  17127. Client client("localhost", get_port());
  17128. Headers headers = {{"X-Custom-Header", "custom-value"}};
  17129. sse::SSEClient sse(client, "/header-check", headers);
  17130. sse.set_max_reconnect_attempts(1);
  17131. sse.start_async();
  17132. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17133. sse.stop();
  17134. EXPECT_TRUE(header_received.load());
  17135. }
  17136. // Test: Reconnect interval configuration
  17137. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  17138. Client client("localhost", get_port());
  17139. sse::SSEClient sse(client, "/events");
  17140. auto &result = sse.set_reconnect_interval(500);
  17141. // Builder pattern should return reference to self
  17142. EXPECT_EQ(&result, &sse);
  17143. }
  17144. // Test: Max reconnect attempts
  17145. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  17146. // Connect to non-existent port to force reconnects
  17147. Client client("localhost", 59998);
  17148. sse::SSEClient sse(client, "/events");
  17149. std::atomic<int> error_count{0};
  17150. sse.on_error([&](Error) { error_count.fetch_add(1); });
  17151. sse.set_reconnect_interval(50);
  17152. sse.set_max_reconnect_attempts(2);
  17153. auto start = std::chrono::steady_clock::now();
  17154. sse.start(); // Blocking call
  17155. auto end = std::chrono::steady_clock::now();
  17156. // Should have stopped after 2 failed attempts
  17157. EXPECT_GE(error_count.load(), 2);
  17158. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  17159. auto duration =
  17160. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  17161. #ifdef _WIN32
  17162. // Windows is much slower for socket connection failures
  17163. EXPECT_LT(duration.count(), 7000);
  17164. #else
  17165. EXPECT_LT(duration.count(), 1000);
  17166. #endif
  17167. }
  17168. // Test: Multi-line data in integration
  17169. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  17170. // Endpoint with multi-line data
  17171. server_->Get("/multiline-data", [](const Request &, Response &res) {
  17172. res.set_chunked_content_provider(
  17173. "text/event-stream", [](size_t offset, DataSink &sink) {
  17174. if (offset == 0) {
  17175. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  17176. sink.write(event.data(), event.size());
  17177. }
  17178. return false;
  17179. });
  17180. });
  17181. Client client("localhost", get_port());
  17182. sse::SSEClient sse(client, "/multiline-data");
  17183. std::string received_data;
  17184. std::mutex data_mutex;
  17185. sse.on_message([&](const sse::SSEMessage &msg) {
  17186. std::lock_guard<std::mutex> lock(data_mutex);
  17187. received_data = msg.data;
  17188. });
  17189. sse.set_reconnect_interval(100);
  17190. sse.set_max_reconnect_attempts(1);
  17191. sse.start_async();
  17192. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17193. sse.stop();
  17194. std::lock_guard<std::mutex> lock(data_mutex);
  17195. EXPECT_EQ(received_data, "line1\nline2\nline3");
  17196. }
  17197. // Test: Auto-reconnect after server disconnection
  17198. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  17199. std::atomic<int> connection_count{0};
  17200. std::atomic<int> message_count{0};
  17201. // Endpoint that sends one event and closes, forcing reconnect
  17202. server_->Get("/reconnect-test",
  17203. [&connection_count](const Request &, Response &res) {
  17204. connection_count.fetch_add(1);
  17205. res.set_chunked_content_provider(
  17206. "text/event-stream", [](size_t offset, DataSink &sink) {
  17207. if (offset == 0) {
  17208. std::string event = "data: hello\n\n";
  17209. sink.write(event.data(), event.size());
  17210. }
  17211. return false; // Close connection after sending
  17212. });
  17213. });
  17214. Client client("localhost", get_port());
  17215. sse::SSEClient sse(client, "/reconnect-test");
  17216. sse.on_message([&message_count](const sse::SSEMessage &) {
  17217. message_count.fetch_add(1);
  17218. });
  17219. sse.set_reconnect_interval(100);
  17220. sse.set_max_reconnect_attempts(3);
  17221. sse.start_async();
  17222. // Wait long enough for multiple reconnects
  17223. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17224. sse.stop();
  17225. // Should have connected multiple times (initial + reconnects)
  17226. EXPECT_GE(connection_count.load(), 2);
  17227. // Should have received messages from multiple connections
  17228. EXPECT_GE(message_count.load(), 2);
  17229. }
  17230. // Test: Last-Event-ID sent on reconnect
  17231. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  17232. std::atomic<int> connection_count{0};
  17233. std::vector<std::string> received_last_event_ids;
  17234. std::mutex id_mutex;
  17235. // Endpoint that checks Last-Event-ID header and sends event with ID
  17236. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  17237. int conn = connection_count.fetch_add(1);
  17238. // Capture the Last-Event-ID header from each connection
  17239. {
  17240. std::lock_guard<std::mutex> lock(id_mutex);
  17241. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  17242. }
  17243. res.set_chunked_content_provider(
  17244. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  17245. if (offset == 0) {
  17246. std::string event =
  17247. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  17248. sink.write(event.data(), event.size());
  17249. }
  17250. return false;
  17251. });
  17252. });
  17253. Client client("localhost", get_port());
  17254. sse::SSEClient sse(client, "/reconnect-with-id");
  17255. sse.set_reconnect_interval(100);
  17256. sse.set_max_reconnect_attempts(3);
  17257. sse.start_async();
  17258. // Wait for at least 2 connections
  17259. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17260. sse.stop();
  17261. // Verify behavior
  17262. std::lock_guard<std::mutex> lock(id_mutex);
  17263. EXPECT_GE(received_last_event_ids.size(), 2u);
  17264. // First connection should have no Last-Event-ID
  17265. if (!received_last_event_ids.empty()) {
  17266. EXPECT_EQ(received_last_event_ids[0], "");
  17267. }
  17268. // Second connection should have Last-Event-ID from first connection
  17269. if (received_last_event_ids.size() >= 2) {
  17270. EXPECT_EQ(received_last_event_ids[1], "event-0");
  17271. }
  17272. }
  17273. // Test: set_headers updates headers used on reconnect
  17274. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  17275. std::vector<std::string> received_tokens;
  17276. std::mutex token_mutex;
  17277. // Endpoint that captures Authorization header
  17278. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  17279. {
  17280. std::lock_guard<std::mutex> lock(token_mutex);
  17281. received_tokens.push_back(req.get_header_value("Authorization"));
  17282. }
  17283. res.set_chunked_content_provider(
  17284. "text/event-stream", [](size_t offset, DataSink &sink) {
  17285. if (offset == 0) {
  17286. std::string event = "data: hello\n\n";
  17287. sink.write(event.data(), event.size());
  17288. }
  17289. return false; // Close connection to trigger reconnect
  17290. });
  17291. });
  17292. Client client("localhost", get_port());
  17293. Headers headers = {{"Authorization", "Bearer old-token"}};
  17294. sse::SSEClient sse(client, "/auth-check", headers);
  17295. // Update headers on each successful connection
  17296. sse.on_open(
  17297. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  17298. sse.set_reconnect_interval(100);
  17299. sse.set_max_reconnect_attempts(3);
  17300. sse.start_async();
  17301. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17302. sse.stop();
  17303. std::lock_guard<std::mutex> lock(token_mutex);
  17304. ASSERT_GE(received_tokens.size(), 2u);
  17305. // First connection uses original header
  17306. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  17307. // Second connection uses updated header from set_headers
  17308. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  17309. }
  17310. // Test: 401 allows reconnection (so on_error can refresh headers)
  17311. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  17312. std::atomic<int> connection_count{0};
  17313. // Endpoint: returns 401 on first attempt, 200 on second
  17314. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  17315. int conn = connection_count.fetch_add(1);
  17316. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  17317. res.status = StatusCode::Unauthorized_401;
  17318. res.set_content("Unauthorized", "text/plain");
  17319. return;
  17320. }
  17321. res.set_chunked_content_provider(
  17322. "text/event-stream", [](size_t offset, DataSink &sink) {
  17323. if (offset == 0) {
  17324. std::string event = "data: authenticated\n\n";
  17325. sink.write(event.data(), event.size());
  17326. }
  17327. return false;
  17328. });
  17329. });
  17330. Client client("localhost", get_port());
  17331. Headers headers = {{"Authorization", "Bearer expired"}};
  17332. sse::SSEClient sse(client, "/auth-retry", headers);
  17333. std::atomic<bool> message_received{false};
  17334. // Refresh token on error
  17335. sse.on_error(
  17336. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  17337. sse.on_message([&](const sse::SSEMessage &msg) {
  17338. if (msg.data == "authenticated") { message_received.store(true); }
  17339. });
  17340. sse.set_reconnect_interval(100);
  17341. sse.set_max_reconnect_attempts(3);
  17342. sse.start_async();
  17343. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17344. sse.stop();
  17345. // Should have reconnected after 401 and succeeded with new token
  17346. EXPECT_GE(connection_count.load(), 2);
  17347. EXPECT_TRUE(message_received.load());
  17348. }
  17349. TEST(Issue2318Test, EmptyHostString) {
  17350. {
  17351. httplib::Client cli_empty("", PORT);
  17352. auto res = cli_empty.Get("/");
  17353. ASSERT_FALSE(res);
  17354. EXPECT_EQ(httplib::Error::Connection, res.error());
  17355. }
  17356. {
  17357. httplib::Client cli(" ", PORT);
  17358. auto res = cli.Get("/");
  17359. ASSERT_FALSE(res);
  17360. EXPECT_EQ(httplib::Error::Connection, res.error());
  17361. }
  17362. }
  17363. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17364. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  17365. Server svr;
  17366. // Set a small payload limit (1KB)
  17367. svr.set_payload_max_length(1024);
  17368. svr.Post("/test", [&](const Request &req, Response &res) {
  17369. res.set_content("Body size: " + std::to_string(req.body.size()),
  17370. "text/plain");
  17371. });
  17372. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17373. auto se = detail::scope_exit([&] {
  17374. svr.stop();
  17375. listen_thread.join();
  17376. });
  17377. svr.wait_until_ready();
  17378. // Create data that compresses well but exceeds limit when decompressed
  17379. // 8KB of repeated null bytes compresses to a very small size
  17380. std::string original_data(8 * 1024, '\0');
  17381. // Compress the data using gzip
  17382. std::string compressed_data;
  17383. detail::gzip_compressor compressor;
  17384. compressor.compress(original_data.data(), original_data.size(), true,
  17385. [&](const char *data, size_t size) {
  17386. compressed_data.append(data, size);
  17387. return true;
  17388. });
  17389. // Verify compression worked (compressed should be much smaller)
  17390. ASSERT_LT(compressed_data.size(), original_data.size());
  17391. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  17392. // Send compressed data with Content-Encoding: gzip
  17393. Client cli(HOST, PORT);
  17394. Headers headers = {{"Content-Encoding", "gzip"}};
  17395. auto res =
  17396. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  17397. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  17398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17399. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  17400. }
  17401. #endif
  17402. // ============================================================================
  17403. // OpenSSL-Specific Tests
  17404. // ============================================================================
  17405. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17406. X509 *readCertificate(const std::string &strFileName) {
  17407. std::ifstream inStream(strFileName);
  17408. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  17409. std::istreambuf_iterator<char>());
  17410. if (strCertPEM.empty()) return (nullptr);
  17411. BIO *pbCert = BIO_new(BIO_s_mem());
  17412. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  17413. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  17414. BIO_free(pbCert);
  17415. return (pCert);
  17416. }
  17417. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  17418. std::ifstream inStream(strFileName);
  17419. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  17420. std::istreambuf_iterator<char>());
  17421. if (strPrivateKeyPEM.empty()) return (nullptr);
  17422. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  17423. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  17424. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  17425. BIO_free(pbPrivKey);
  17426. return (pPrivateKey);
  17427. }
  17428. TEST(BindServerTest, UpdateCerts) {
  17429. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17430. int port = svr.bind_to_any_port("0.0.0.0");
  17431. ASSERT_TRUE(svr.is_valid());
  17432. ASSERT_TRUE(port > 0);
  17433. X509 *cert = readCertificate(SERVER_CERT_FILE);
  17434. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  17435. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  17436. ASSERT_TRUE(cert != nullptr);
  17437. ASSERT_TRUE(ca_cert != nullptr);
  17438. ASSERT_TRUE(key != nullptr);
  17439. X509_STORE *cert_store = X509_STORE_new();
  17440. X509_STORE_add_cert(cert_store, ca_cert);
  17441. // svr.update_certs(cert, key, cert_store); // deprecated
  17442. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  17443. CLIENT_CA_CERT_FILE);
  17444. ASSERT_TRUE(svr.is_valid());
  17445. svr.stop();
  17446. X509_STORE_free(cert_store);
  17447. X509_free(cert);
  17448. X509_free(ca_cert);
  17449. EVP_PKEY_free(key);
  17450. }
  17451. // Test that update_certs() updates client CA list correctly
  17452. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  17453. // Start with file-based constructor
  17454. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17455. ASSERT_TRUE(svr.is_valid());
  17456. // Initially no client CA list should be set
  17457. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17458. ASSERT_TRUE(ssl_ctx != nullptr);
  17459. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  17460. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  17461. EXPECT_EQ(0, count_before);
  17462. // Now update with client CA (PEM string)
  17463. std::string cert_pem, key_pem, ca_pem;
  17464. read_file(SERVER_CERT_FILE, cert_pem);
  17465. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  17466. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  17467. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  17468. ASSERT_TRUE(svr.is_valid());
  17469. // Now client CA list should be set
  17470. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  17471. ASSERT_TRUE(ca_list_after != nullptr);
  17472. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  17473. }
  17474. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  17475. // Test that the file-path SSLServer constructor properly sets the client CA
  17476. // list that is sent to clients during the TLS handshake (CertificateRequest)
  17477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17478. ASSERT_TRUE(svr.is_valid());
  17479. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17480. ASSERT_TRUE(ssl_ctx != nullptr);
  17481. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  17482. ASSERT_TRUE(ca_list != nullptr);
  17483. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  17484. }
  17485. #endif
  17486. // ============================================================================
  17487. // MbedTLS-Specific Tests
  17488. // ============================================================================
  17489. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  17490. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  17491. using namespace httplib::tls;
  17492. // Track if callback was invoked
  17493. bool callback_invoked = false;
  17494. // The callback receives void* ctx which is actually MbedTlsContext*
  17495. // We can access the mbedtls_ssl_config via the context
  17496. auto setup_callback = [&callback_invoked](void *ctx) {
  17497. callback_invoked = true;
  17498. // Cast to MbedTlsContext* to access the ssl config
  17499. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  17500. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  17501. // Use static variables to hold certificate data (simplified for test)
  17502. static mbedtls_x509_crt own_cert;
  17503. static mbedtls_pk_context own_key;
  17504. static mbedtls_x509_crt ca_chain;
  17505. static bool initialized = false;
  17506. if (!initialized) {
  17507. mbedtls_x509_crt_init(&own_cert);
  17508. mbedtls_pk_init(&own_key);
  17509. mbedtls_x509_crt_init(&ca_chain);
  17510. // Load server certificate
  17511. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  17512. return false;
  17513. }
  17514. // Load server private key.
  17515. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  17516. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  17517. #if MBEDTLS_VERSION_MAJOR == 3
  17518. ,
  17519. mbedtls_ctr_drbg_random, nullptr
  17520. #endif
  17521. ) != 0) {
  17522. return false;
  17523. }
  17524. // Load CA chain for client verification
  17525. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  17526. return false;
  17527. }
  17528. initialized = true;
  17529. }
  17530. // Configure the SSL config
  17531. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  17532. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  17533. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17534. // Set minimum TLS version using mbedTLS native API
  17535. #if MBEDTLS_VERSION_MAJOR >= 3
  17536. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17537. #else
  17538. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17539. MBEDTLS_SSL_MINOR_VERSION_3);
  17540. #endif
  17541. return true;
  17542. };
  17543. SSLServer svr(setup_callback);
  17544. ASSERT_TRUE(svr.is_valid());
  17545. ASSERT_TRUE(callback_invoked);
  17546. svr.Get("/test", [&](const Request &req, Response &res) {
  17547. res.set_content("test", "text/plain");
  17548. auto cert = req.peer_cert();
  17549. ASSERT_TRUE(static_cast<bool>(cert));
  17550. auto common_name = cert.subject_cn();
  17551. EXPECT_EQ("Common Name", common_name);
  17552. });
  17553. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17554. auto se = detail::scope_exit([&] {
  17555. svr.stop();
  17556. t.join();
  17557. ASSERT_FALSE(svr.is_running());
  17558. });
  17559. svr.wait_until_ready();
  17560. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  17561. cli.enable_server_certificate_verification(false);
  17562. cli.set_connection_timeout(30);
  17563. auto res = cli.Get("/test");
  17564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17565. ASSERT_EQ(StatusCode::OK_200, res->status);
  17566. }
  17567. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  17568. // context (owning mbedtls_ssl_config) before shutting down a still-open
  17569. // keep-alive SSL session, which reads through that config in
  17570. // mbedtls_ssl_close_notify.
  17571. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  17572. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17573. ASSERT_TRUE(svr.is_valid());
  17574. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17575. res.set_content("test", "text/plain");
  17576. });
  17577. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17578. auto se = detail::scope_exit([&] {
  17579. svr.stop();
  17580. t.join();
  17581. ASSERT_FALSE(svr.is_running());
  17582. });
  17583. svr.wait_until_ready();
  17584. {
  17585. SSLClient cli(HOST, PORT);
  17586. cli.enable_server_certificate_verification(false);
  17587. cli.set_keep_alive(true);
  17588. auto res = cli.Get("/test");
  17589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17590. ASSERT_EQ(StatusCode::OK_200, res->status);
  17591. // cli is destructed here with the keep-alive SSL session still open.
  17592. }
  17593. }
  17594. #endif
  17595. // WebSocket Tests
  17596. TEST(WebSocketTest, RSVBitsMustBeZero) {
  17597. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  17598. // defining the meaning of these bits has been negotiated.
  17599. auto make_frame = [](uint8_t first_byte) {
  17600. std::string frame;
  17601. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  17602. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  17603. frame += "Hello";
  17604. return frame;
  17605. };
  17606. // RSV1 set (0x40)
  17607. {
  17608. detail::BufferStream strm;
  17609. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  17610. ws::Opcode opcode;
  17611. std::string payload;
  17612. bool fin;
  17613. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17614. false, 1024));
  17615. }
  17616. // RSV2 set (0x20)
  17617. {
  17618. detail::BufferStream strm;
  17619. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  17620. ws::Opcode opcode;
  17621. std::string payload;
  17622. bool fin;
  17623. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17624. false, 1024));
  17625. }
  17626. // RSV3 set (0x10)
  17627. {
  17628. detail::BufferStream strm;
  17629. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  17630. ws::Opcode opcode;
  17631. std::string payload;
  17632. bool fin;
  17633. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17634. false, 1024));
  17635. }
  17636. // No RSV bits set - should succeed
  17637. {
  17638. detail::BufferStream strm;
  17639. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  17640. ws::Opcode opcode;
  17641. std::string payload;
  17642. bool fin;
  17643. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17644. false, 1024));
  17645. EXPECT_EQ(ws::Opcode::Text, opcode);
  17646. EXPECT_EQ("Hello", payload);
  17647. EXPECT_TRUE(fin);
  17648. }
  17649. }
  17650. TEST(WebSocketTest, ControlFrameValidation) {
  17651. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  17652. // payload length <= 125.
  17653. // Ping with FIN=0 - must be rejected
  17654. {
  17655. detail::BufferStream strm;
  17656. std::string frame;
  17657. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  17658. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17659. strm.write(frame.data(), frame.size());
  17660. ws::Opcode opcode;
  17661. std::string payload;
  17662. bool fin;
  17663. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17664. false, 1024));
  17665. }
  17666. // Close with FIN=0 - must be rejected
  17667. {
  17668. detail::BufferStream strm;
  17669. std::string frame;
  17670. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  17671. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17672. strm.write(frame.data(), frame.size());
  17673. ws::Opcode opcode;
  17674. std::string payload;
  17675. bool fin;
  17676. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17677. false, 1024));
  17678. }
  17679. // Ping with payload_len=126 (extended length) - must be rejected
  17680. {
  17681. detail::BufferStream strm;
  17682. std::string frame;
  17683. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17684. frame += static_cast<char>(126); // payload_len=126 (>125)
  17685. frame += static_cast<char>(0x00); // extended length high byte
  17686. frame += static_cast<char>(126); // extended length low byte
  17687. frame += std::string(126, 'x');
  17688. strm.write(frame.data(), frame.size());
  17689. ws::Opcode opcode;
  17690. std::string payload;
  17691. bool fin;
  17692. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17693. false, 1024));
  17694. }
  17695. // Ping with FIN=1 and payload_len=125 - should succeed
  17696. {
  17697. detail::BufferStream strm;
  17698. std::string frame;
  17699. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17700. frame += static_cast<char>(125); // payload_len=125
  17701. frame += std::string(125, 'x');
  17702. strm.write(frame.data(), frame.size());
  17703. ws::Opcode opcode;
  17704. std::string payload;
  17705. bool fin;
  17706. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17707. false, 1024));
  17708. EXPECT_EQ(ws::Opcode::Ping, opcode);
  17709. EXPECT_EQ(125u, payload.size());
  17710. EXPECT_TRUE(fin);
  17711. }
  17712. }
  17713. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  17714. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  17715. // length MUST be 0.
  17716. // MSB set - must be rejected
  17717. {
  17718. detail::BufferStream strm;
  17719. std::string frame;
  17720. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17721. frame += static_cast<char>(127); // 64-bit extended length
  17722. frame += static_cast<char>(0x80); // MSB set (invalid)
  17723. frame += std::string(7, '\0'); // remaining 7 bytes of length
  17724. strm.write(frame.data(), frame.size());
  17725. ws::Opcode opcode;
  17726. std::string payload;
  17727. bool fin;
  17728. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17729. false, 1024));
  17730. }
  17731. // MSB clear - should pass length parsing (will be rejected by max_len,
  17732. // but that's a different check; use a small length to verify)
  17733. {
  17734. detail::BufferStream strm;
  17735. std::string frame;
  17736. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17737. frame += static_cast<char>(127); // 64-bit extended length
  17738. frame += std::string(7, '\0'); // high bytes = 0
  17739. frame += static_cast<char>(0x03); // length = 3
  17740. frame += "abc";
  17741. strm.write(frame.data(), frame.size());
  17742. ws::Opcode opcode;
  17743. std::string payload;
  17744. bool fin;
  17745. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17746. false, 1024));
  17747. EXPECT_EQ(ws::Opcode::Text, opcode);
  17748. EXPECT_EQ("abc", payload);
  17749. }
  17750. }
  17751. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  17752. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  17753. // Valid UTF-8
  17754. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  17755. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  17756. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  17757. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  17758. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  17759. // Invalid UTF-8
  17760. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  17761. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  17762. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  17763. EXPECT_FALSE(
  17764. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  17765. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  17766. }
  17767. TEST(WebSocketTest, ConnectAndDisconnect) {
  17768. Server svr;
  17769. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17770. std::string msg;
  17771. while (ws.read(msg)) {}
  17772. });
  17773. auto port = svr.bind_to_any_port(HOST);
  17774. std::thread t([&]() { svr.listen_after_bind(); });
  17775. svr.wait_until_ready();
  17776. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17777. auto res = client.connect();
  17778. ASSERT_TRUE(res);
  17779. EXPECT_EQ(Error::Success, res.error());
  17780. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  17781. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  17782. EXPECT_TRUE(client.is_open());
  17783. client.close();
  17784. EXPECT_FALSE(client.is_open());
  17785. svr.stop();
  17786. t.join();
  17787. }
  17788. TEST(WebSocketTest, ValidURL) {
  17789. ws::WebSocketClient ws1("ws://localhost:8080/path");
  17790. EXPECT_TRUE(ws1.is_valid());
  17791. ws::WebSocketClient ws2("ws://example.com/path");
  17792. EXPECT_TRUE(ws2.is_valid());
  17793. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  17794. EXPECT_TRUE(ws3.is_valid());
  17795. #ifdef CPPHTTPLIB_SSL_ENABLED
  17796. ws::WebSocketClient wss1("wss://example.com/path");
  17797. EXPECT_TRUE(wss1.is_valid());
  17798. ws::WebSocketClient wss2("wss://example.com:443/path");
  17799. EXPECT_TRUE(wss2.is_valid());
  17800. #endif
  17801. }
  17802. TEST(WebSocketTest, InvalidURL) {
  17803. // No scheme
  17804. ws::WebSocketClient ws1("localhost:8080/path");
  17805. EXPECT_FALSE(ws1.is_valid());
  17806. // No path
  17807. ws::WebSocketClient ws2("ws://localhost:8080");
  17808. EXPECT_FALSE(ws2.is_valid());
  17809. // Empty string
  17810. ws::WebSocketClient ws3("");
  17811. EXPECT_FALSE(ws3.is_valid());
  17812. // Missing host
  17813. ws::WebSocketClient ws4("ws://:8080/path");
  17814. EXPECT_FALSE(ws4.is_valid());
  17815. // Port number overflow — should not crash
  17816. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  17817. EXPECT_FALSE(ws5.is_valid());
  17818. // Port out of range
  17819. ws::WebSocketClient ws6("ws://localhost:99999/path");
  17820. EXPECT_FALSE(ws6.is_valid());
  17821. }
  17822. TEST(WebSocketTest, UnsupportedScheme) {
  17823. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17824. ws::WebSocketClient ws1("http://localhost:8080/path");
  17825. EXPECT_FALSE(ws1.is_valid());
  17826. ws::WebSocketClient ws2("https://localhost:8080/path");
  17827. EXPECT_FALSE(ws2.is_valid());
  17828. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  17829. EXPECT_FALSE(ws3.is_valid());
  17830. #else
  17831. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  17832. std::invalid_argument);
  17833. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  17834. std::invalid_argument);
  17835. #endif
  17836. }
  17837. TEST(WebSocketTest, ConnectWhenInvalid) {
  17838. ws::WebSocketClient ws("not a valid url");
  17839. EXPECT_FALSE(ws.is_valid());
  17840. auto res = ws.connect();
  17841. EXPECT_FALSE(res);
  17842. EXPECT_EQ(Error::Connection, res.error());
  17843. EXPECT_EQ(-1, res.status());
  17844. }
  17845. TEST(WebSocketTest, ConnectRefusedReportsError) {
  17846. // Grab a port that is free, then close it again so nothing listens there
  17847. Server svr;
  17848. auto port = svr.bind_to_any_port(HOST);
  17849. svr.stop();
  17850. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17851. auto res = client.connect();
  17852. ASSERT_FALSE(res);
  17853. EXPECT_EQ(Error::Connection, res.error());
  17854. EXPECT_EQ(-1, res.status());
  17855. }
  17856. TEST(WebSocketTest, DefaultPort) {
  17857. ws::WebSocketClient ws1("ws://example.com/path");
  17858. EXPECT_TRUE(ws1.is_valid());
  17859. // ws:// defaults to port 80 (verified by successful parse)
  17860. #ifdef CPPHTTPLIB_SSL_ENABLED
  17861. ws::WebSocketClient ws2("wss://example.com/path");
  17862. EXPECT_TRUE(ws2.is_valid());
  17863. // wss:// defaults to port 443 (verified by successful parse)
  17864. #endif
  17865. }
  17866. TEST(WebSocketTest, IPv6LiteralAddress) {
  17867. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  17868. EXPECT_TRUE(ws1.is_valid());
  17869. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  17870. EXPECT_TRUE(ws2.is_valid());
  17871. }
  17872. TEST(WebSocketTest, ComplexPath) {
  17873. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  17874. EXPECT_TRUE(ws1.is_valid());
  17875. ws::WebSocketClient ws2("ws://localhost:8080/");
  17876. EXPECT_TRUE(ws2.is_valid());
  17877. }
  17878. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  17879. Server svr;
  17880. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17881. std::string msg;
  17882. while (ws.read(msg)) {}
  17883. });
  17884. auto port = svr.bind_to_any_port(HOST);
  17885. std::thread t([&]() { svr.listen_after_bind(); });
  17886. svr.wait_until_ready();
  17887. auto another_host = "example.com";
  17888. auto wrong_ip = "192.0.2.1";
  17889. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17890. client.set_hostname_addr_map({{another_host, wrong_ip}});
  17891. ASSERT_TRUE(client.connect());
  17892. EXPECT_TRUE(client.is_open());
  17893. client.close();
  17894. svr.stop();
  17895. t.join();
  17896. }
  17897. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  17898. Server svr;
  17899. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17900. std::string msg;
  17901. while (ws.read(msg)) {}
  17902. });
  17903. auto port = svr.bind_to_any_port(HOST);
  17904. std::thread t([&]() { svr.listen_after_bind(); });
  17905. svr.wait_until_ready();
  17906. auto wrong_ip = "192.0.2.1";
  17907. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17908. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  17909. client.set_connection_timeout(1);
  17910. client.set_read_timeout(1);
  17911. client.set_write_timeout(1);
  17912. EXPECT_FALSE(client.connect());
  17913. EXPECT_FALSE(client.is_open());
  17914. svr.stop();
  17915. t.join();
  17916. }
  17917. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  17918. // A mapped value that is not an IP literal must be resolved. HOST resolves
  17919. // from the hosts file, so this test needs no external DNS. "target.invalid"
  17920. // (RFC 6761) is only a map key and the Host header value.
  17921. auto host = "target.invalid";
  17922. Server svr;
  17923. std::string received_host;
  17924. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17925. received_host = req.get_header_value("Host");
  17926. std::string msg;
  17927. while (ws.read(msg)) {}
  17928. });
  17929. auto port = svr.bind_to_any_port(HOST);
  17930. std::thread t([&]() { svr.listen_after_bind(); });
  17931. // ASSERT_* below returns from the test body, which would leave t joinable
  17932. // and make ~thread call std::terminate.
  17933. auto se = detail::scope_exit([&] {
  17934. svr.stop();
  17935. if (t.joinable()) { t.join(); }
  17936. });
  17937. svr.wait_until_ready();
  17938. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  17939. std::to_string(port) + "/ws");
  17940. client.set_hostname_addr_map({{host, HOST}});
  17941. ASSERT_TRUE(client.connect());
  17942. EXPECT_TRUE(client.is_open());
  17943. client.close();
  17944. svr.stop();
  17945. t.join();
  17946. // The mapping only redirects the connection; the identity stays host_.
  17947. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  17948. }
  17949. class WebSocketIntegrationTest : public ::testing::Test {
  17950. protected:
  17951. void SetUp() override {
  17952. server_ = httplib::detail::make_unique<Server>();
  17953. setup_server();
  17954. start_server();
  17955. }
  17956. void TearDown() override {
  17957. server_->stop();
  17958. if (server_thread_.joinable()) { server_thread_.join(); }
  17959. }
  17960. void setup_server() {
  17961. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17962. std::string msg;
  17963. ws::ReadResult ret;
  17964. while ((ret = ws.read(msg))) {
  17965. if (ret == ws::Binary) {
  17966. ws.send(msg.data(), msg.size());
  17967. } else {
  17968. ws.send(msg);
  17969. }
  17970. }
  17971. });
  17972. server_->WebSocket("/ws-echo-string",
  17973. [](const Request &, ws::WebSocket &ws) {
  17974. std::string msg;
  17975. while (ws.read(msg)) {
  17976. ws.send("echo: " + msg);
  17977. }
  17978. });
  17979. server_->WebSocket(
  17980. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  17981. // Echo back request metadata
  17982. ws.send("path:" + req.path);
  17983. ws.send("header:" + req.get_header_value("X-Test-Header"));
  17984. std::string msg;
  17985. while (ws.read(msg)) {}
  17986. });
  17987. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  17988. std::string msg;
  17989. ws.read(msg); // wait for a message
  17990. ws.close();
  17991. });
  17992. server_->WebSocket("/ws-close-status",
  17993. [](const Request &, ws::WebSocket &ws) {
  17994. std::string msg;
  17995. ws.read(msg); // wait for a message
  17996. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  17997. });
  17998. server_->WebSocket(
  17999. "/ws-subprotocol",
  18000. [](const Request &, ws::WebSocket &ws) {
  18001. std::string msg;
  18002. while (ws.read(msg)) {
  18003. ws.send(msg);
  18004. }
  18005. },
  18006. [](const std::vector<std::string> &protocols) -> std::string {
  18007. for (const auto &p : protocols) {
  18008. if (p == "graphql-ws") { return p; }
  18009. }
  18010. return "";
  18011. });
  18012. }
  18013. void start_server() {
  18014. port_ = server_->bind_to_any_port(HOST);
  18015. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18016. server_->wait_until_ready();
  18017. }
  18018. std::unique_ptr<Server> server_;
  18019. std::thread server_thread_;
  18020. int port_ = 0;
  18021. };
  18022. TEST_F(WebSocketIntegrationTest, TextEcho) {
  18023. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18024. "/ws-echo");
  18025. ASSERT_TRUE(client.connect());
  18026. ASSERT_TRUE(client.is_open());
  18027. ASSERT_TRUE(client.send("Hello WebSocket"));
  18028. std::string msg;
  18029. EXPECT_EQ(ws::Text, client.read(msg));
  18030. EXPECT_EQ("Hello WebSocket", msg);
  18031. client.close();
  18032. }
  18033. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  18034. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18035. "/ws-echo");
  18036. ASSERT_TRUE(client.connect());
  18037. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  18038. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  18039. std::string msg;
  18040. EXPECT_EQ(ws::Binary, client.read(msg));
  18041. EXPECT_EQ(binary_data, msg);
  18042. client.close();
  18043. }
  18044. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  18045. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18046. "/ws-echo");
  18047. ASSERT_TRUE(client.connect());
  18048. for (int i = 0; i < 10; i++) {
  18049. auto text = "message " + std::to_string(i);
  18050. ASSERT_TRUE(client.send(text));
  18051. std::string msg;
  18052. ASSERT_TRUE(client.read(msg));
  18053. EXPECT_EQ(text, msg);
  18054. }
  18055. client.close();
  18056. }
  18057. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  18058. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18059. "/ws-close");
  18060. ASSERT_TRUE(client.connect());
  18061. // Send a message to trigger the server to close
  18062. ASSERT_TRUE(client.send("trigger close"));
  18063. // The server will close, so read should return false
  18064. std::string msg;
  18065. EXPECT_FALSE(client.read(msg));
  18066. EXPECT_FALSE(client.is_open());
  18067. }
  18068. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  18069. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18070. "/ws-echo");
  18071. ASSERT_TRUE(client.connect());
  18072. // 128KB message
  18073. std::string large_data(128 * 1024, 'X');
  18074. ASSERT_TRUE(client.send(large_data));
  18075. std::string msg;
  18076. ASSERT_TRUE(client.read(msg));
  18077. EXPECT_EQ(large_data, msg);
  18078. client.close();
  18079. }
  18080. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  18081. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18082. "/ws-echo");
  18083. ASSERT_TRUE(client.connect());
  18084. const int num_threads = 4;
  18085. std::vector<std::thread> threads;
  18086. std::atomic<int> send_count{0};
  18087. for (int t = 0; t < num_threads; t++) {
  18088. threads.emplace_back([&client, &send_count, t]() {
  18089. for (int i = 0; i < 5; i++) {
  18090. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  18091. if (client.send(text)) { send_count++; }
  18092. }
  18093. });
  18094. }
  18095. for (auto &th : threads) {
  18096. th.join();
  18097. }
  18098. int received = 0;
  18099. std::string msg;
  18100. while (received < send_count.load()) {
  18101. if (!client.read(msg)) { break; }
  18102. received++;
  18103. }
  18104. EXPECT_EQ(send_count.load(), received);
  18105. client.close();
  18106. }
  18107. TEST_F(WebSocketIntegrationTest, ReadString) {
  18108. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18109. "/ws-echo-string");
  18110. ASSERT_TRUE(client.connect());
  18111. ASSERT_TRUE(client.send("hello"));
  18112. std::string msg;
  18113. ASSERT_TRUE(client.read(msg));
  18114. EXPECT_EQ("echo: hello", msg);
  18115. ASSERT_TRUE(client.send("world"));
  18116. ASSERT_TRUE(client.read(msg));
  18117. EXPECT_EQ("echo: world", msg);
  18118. client.close();
  18119. }
  18120. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  18121. Headers headers = {{"X-Test-Header", "test-value"}};
  18122. ws::WebSocketClient client(
  18123. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  18124. ASSERT_TRUE(client.connect());
  18125. std::string msg;
  18126. ASSERT_TRUE(client.read(msg));
  18127. EXPECT_EQ("path:/ws-request-info", msg);
  18128. ASSERT_TRUE(client.read(msg));
  18129. EXPECT_EQ("header:test-value", msg);
  18130. client.close();
  18131. }
  18132. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  18133. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18134. "/ws-echo");
  18135. client.set_read_timeout(1, 0); // 1 second
  18136. ASSERT_TRUE(client.connect());
  18137. // Don't send anything — server echo handler waits for a message,
  18138. // so read() should time out and return false.
  18139. std::string msg;
  18140. EXPECT_FALSE(client.read(msg));
  18141. }
  18142. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  18143. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18144. "/ws-echo");
  18145. client.set_read_timeout(5, 0);
  18146. ASSERT_TRUE(client.connect());
  18147. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18148. // The server should reject it and close the connection.
  18149. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  18150. client.send(oversized);
  18151. // The server's read() should have failed due to payload limit,
  18152. // so our read() should return false (connection closed).
  18153. std::string msg;
  18154. EXPECT_FALSE(client.read(msg));
  18155. }
  18156. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  18157. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18158. "/ws-echo");
  18159. client.set_read_timeout(10, 0);
  18160. ASSERT_TRUE(client.connect());
  18161. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18162. // This should succeed.
  18163. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  18164. ASSERT_TRUE(client.send(at_limit));
  18165. std::string msg;
  18166. ASSERT_TRUE(client.read(msg));
  18167. EXPECT_EQ(at_limit.size(), msg.size());
  18168. client.close();
  18169. }
  18170. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  18171. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18172. "/nonexistent");
  18173. auto res = client.connect();
  18174. EXPECT_FALSE(res);
  18175. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18176. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  18177. EXPECT_FALSE(client.is_open());
  18178. }
  18179. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  18180. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18181. "/ws-echo");
  18182. ASSERT_TRUE(client.connect());
  18183. ASSERT_TRUE(client.send(""));
  18184. std::string msg;
  18185. EXPECT_EQ(ws::Text, client.read(msg));
  18186. EXPECT_EQ("", msg);
  18187. client.close();
  18188. }
  18189. TEST_F(WebSocketIntegrationTest, Reconnect) {
  18190. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18191. "/ws-echo");
  18192. // First connection
  18193. ASSERT_TRUE(client.connect());
  18194. ASSERT_TRUE(client.send("first"));
  18195. std::string msg;
  18196. ASSERT_TRUE(client.read(msg));
  18197. EXPECT_EQ("first", msg);
  18198. client.close();
  18199. EXPECT_FALSE(client.is_open());
  18200. // Reconnect using the same client object
  18201. ASSERT_TRUE(client.connect());
  18202. ASSERT_TRUE(client.is_open());
  18203. ASSERT_TRUE(client.send("second"));
  18204. ASSERT_TRUE(client.read(msg));
  18205. EXPECT_EQ("second", msg);
  18206. client.close();
  18207. }
  18208. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  18209. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18210. "/ws-close-status");
  18211. ASSERT_TRUE(client.connect());
  18212. // Trigger the server to close with GoingAway status
  18213. ASSERT_TRUE(client.send("trigger"));
  18214. // read() should return false after receiving the close frame
  18215. std::string msg;
  18216. EXPECT_FALSE(client.read(msg));
  18217. EXPECT_FALSE(client.is_open());
  18218. }
  18219. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  18220. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18221. "/ws-echo");
  18222. ASSERT_TRUE(client.connect());
  18223. client.close(ws::CloseStatus::GoingAway, "client leaving");
  18224. EXPECT_FALSE(client.is_open());
  18225. }
  18226. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  18227. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  18228. ws::WebSocketClient client(
  18229. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18230. ASSERT_TRUE(client.connect());
  18231. // Server should have selected graphql-ws
  18232. EXPECT_EQ("graphql-ws", client.subprotocol());
  18233. client.close();
  18234. }
  18235. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  18236. Headers headers;
  18237. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  18238. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  18239. ws::WebSocketClient client(
  18240. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18241. ASSERT_TRUE(client.connect());
  18242. // The offer on the second field line counts too, so graphql-ws is selected
  18243. EXPECT_EQ("graphql-ws", client.subprotocol());
  18244. client.close();
  18245. }
  18246. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  18247. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  18248. ws::WebSocketClient client(
  18249. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18250. ASSERT_TRUE(client.connect());
  18251. // Server should not have selected any subprotocol
  18252. EXPECT_TRUE(client.subprotocol().empty());
  18253. client.close();
  18254. }
  18255. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  18256. // Connect without requesting any subprotocol
  18257. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18258. "/ws-subprotocol");
  18259. ASSERT_TRUE(client.connect());
  18260. EXPECT_TRUE(client.subprotocol().empty());
  18261. client.close();
  18262. }
  18263. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  18264. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18265. "/ws-echo");
  18266. client.set_tcp_nodelay(true);
  18267. client.set_connection_timeout(3, 0);
  18268. bool socket_options_called = false;
  18269. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  18270. ASSERT_TRUE(client.connect());
  18271. ASSERT_TRUE(client.is_open());
  18272. EXPECT_TRUE(socket_options_called);
  18273. ASSERT_TRUE(client.send("hello"));
  18274. std::string msg;
  18275. auto result = client.read(msg);
  18276. EXPECT_EQ(result, ws::ReadResult::Text);
  18277. EXPECT_EQ(msg, "hello");
  18278. client.close();
  18279. }
  18280. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  18281. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18282. "/ws-echo");
  18283. client.set_connection_timeout(std::chrono::seconds(3));
  18284. client.set_write_timeout(std::chrono::seconds(3));
  18285. // A sub-second remainder exercises the seconds/microseconds split.
  18286. client.set_read_timeout(std::chrono::milliseconds(1500));
  18287. ASSERT_TRUE(client.connect());
  18288. auto start = std::chrono::steady_clock::now();
  18289. std::string msg;
  18290. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  18291. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18292. std::chrono::steady_clock::now() - start)
  18293. .count();
  18294. // Above 1s so that dropping the microseconds half of the split fails here,
  18295. // and well under the 300s default so that ignoring the setter fails too.
  18296. EXPECT_GE(elapsed, 1400);
  18297. EXPECT_LT(elapsed, 30000);
  18298. }
  18299. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  18300. Server svr;
  18301. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  18302. if (!req.has_header("Authorization")) {
  18303. res.status = StatusCode::Unauthorized_401;
  18304. res.set_content("Unauthorized", "text/plain");
  18305. return Server::HandlerResponse::Handled;
  18306. }
  18307. return Server::HandlerResponse::Unhandled;
  18308. });
  18309. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18310. std::string msg;
  18311. while (ws.read(msg)) {
  18312. ws.send(msg);
  18313. }
  18314. });
  18315. auto port = svr.bind_to_any_port("localhost");
  18316. std::thread t([&]() { svr.listen_after_bind(); });
  18317. svr.wait_until_ready();
  18318. // Without Authorization header - should be rejected before upgrade
  18319. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  18320. EXPECT_FALSE(client1.connect());
  18321. // With Authorization header - should succeed
  18322. Headers headers = {{"Authorization", "Bearer token123"}};
  18323. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  18324. headers);
  18325. ASSERT_TRUE(client2.connect());
  18326. ASSERT_TRUE(client2.send("hello"));
  18327. std::string msg;
  18328. ASSERT_TRUE(client2.read(msg));
  18329. EXPECT_EQ("hello", msg);
  18330. client2.close();
  18331. svr.stop();
  18332. t.join();
  18333. }
  18334. TEST(WebSocketTest, QueryStringInHandshake) {
  18335. Server svr;
  18336. std::mutex mtx;
  18337. std::string received_target;
  18338. std::string received_token;
  18339. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18340. {
  18341. std::lock_guard<std::mutex> lock(mtx);
  18342. received_target = req.target;
  18343. if (req.has_param("token")) {
  18344. received_token = req.get_param_value("token");
  18345. }
  18346. }
  18347. std::string msg;
  18348. while (ws.read(msg)) {
  18349. ws.send(msg);
  18350. }
  18351. });
  18352. auto port = svr.bind_to_any_port("localhost");
  18353. std::thread t([&]() { svr.listen_after_bind(); });
  18354. svr.wait_until_ready();
  18355. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  18356. "/ws?token=ABC&session=123");
  18357. ASSERT_TRUE(client.connect());
  18358. // Round-trip ensures the handler has run and captured the request.
  18359. ASSERT_TRUE(client.send("hello"));
  18360. std::string msg;
  18361. ASSERT_TRUE(client.read(msg));
  18362. EXPECT_EQ("hello", msg);
  18363. client.close();
  18364. {
  18365. std::lock_guard<std::mutex> lock(mtx);
  18366. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  18367. EXPECT_EQ("ABC", received_token);
  18368. }
  18369. svr.stop();
  18370. t.join();
  18371. }
  18372. // Run a handshake against a throwaway server and hand the request the server
  18373. // received back to the caller, so tests can assert on the headers the client
  18374. // actually put on the wire.
  18375. static void capture_websocket_handshake_request(
  18376. const Headers &client_headers,
  18377. std::function<void(const Request &, int port)> verify) {
  18378. Server svr;
  18379. std::mutex mtx;
  18380. Request received;
  18381. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18382. {
  18383. std::lock_guard<std::mutex> lock(mtx);
  18384. received = req;
  18385. }
  18386. std::string msg;
  18387. while (ws.read(msg)) {
  18388. ws.send(msg);
  18389. }
  18390. });
  18391. auto port = svr.bind_to_any_port("localhost");
  18392. std::thread t([&]() { svr.listen_after_bind(); });
  18393. auto se = detail::scope_exit([&] {
  18394. svr.stop();
  18395. t.join();
  18396. });
  18397. svr.wait_until_ready();
  18398. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  18399. client_headers);
  18400. ASSERT_TRUE(client.connect());
  18401. ASSERT_TRUE(client.send("hello"));
  18402. std::string msg;
  18403. ASSERT_TRUE(client.read(msg));
  18404. client.close();
  18405. {
  18406. std::lock_guard<std::mutex> lock(mtx);
  18407. verify(received, port);
  18408. }
  18409. }
  18410. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  18411. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  18412. // Non-default port must be present in the Host header. Default ports
  18413. // (80/443) are omitted; that logic is covered by
  18414. // MakeHostAndPortStringTest.
  18415. EXPECT_EQ("localhost:" + std::to_string(port),
  18416. req.get_header_value("Host"));
  18417. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  18418. req.get_header_value("User-Agent"));
  18419. EXPECT_FALSE(req.has_header("Accept"));
  18420. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  18421. EXPECT_FALSE(req.has_header("Content-Length"));
  18422. });
  18423. }
  18424. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  18425. capture_websocket_handshake_request(
  18426. {{"Host", "example.com"},
  18427. {"User-Agent", "custom-agent"},
  18428. {"X-Custom", "value"}},
  18429. [](const Request &req, int) {
  18430. EXPECT_EQ("example.com", req.get_header_value("Host"));
  18431. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  18432. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  18433. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  18434. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  18435. });
  18436. }
  18437. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  18438. capture_websocket_handshake_request(
  18439. {{"Upgrade", "bogus"},
  18440. {"Connection", "close"},
  18441. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  18442. {"Sec-WebSocket-Version", "8"}},
  18443. [](const Request &req, int) {
  18444. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  18445. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  18446. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  18447. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  18448. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  18449. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  18450. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  18451. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  18452. req.get_header_value("Sec-WebSocket-Key"));
  18453. });
  18454. }
  18455. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  18456. // A header the client refuses to send must abort the handshake before any
  18457. // part of it reaches the wire; a lone request line would otherwise sit in
  18458. // the peer's buffer as a truncated request.
  18459. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18460. ASSERT_NE(INVALID_SOCKET, srv);
  18461. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  18462. sockaddr_in addr{};
  18463. addr.sin_family = AF_INET;
  18464. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  18465. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18466. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18467. ASSERT_EQ(0, ::listen(srv, 1));
  18468. sockaddr_in bound{};
  18469. socklen_t bound_len = sizeof(bound);
  18470. ASSERT_EQ(
  18471. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  18472. auto port = ntohs(bound.sin_port);
  18473. ssize_t received = -1;
  18474. std::thread t([&] {
  18475. // Bound every blocking call so a regression fails the test with a bad
  18476. // value instead of hanging the suite.
  18477. fd_set rfds;
  18478. FD_ZERO(&rfds);
  18479. FD_SET(srv, &rfds);
  18480. timeval tv{5, 0};
  18481. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  18482. 0) {
  18483. return;
  18484. }
  18485. sockaddr_in cli_addr{};
  18486. socklen_t cli_len = sizeof(cli_addr);
  18487. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18488. if (cli == INVALID_SOCKET) { return; }
  18489. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  18490. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18491. char buf[4096];
  18492. received = ::recv(cli, buf, sizeof(buf), 0);
  18493. });
  18494. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  18495. // connect() has already shut the socket down by the time it returns false,
  18496. // so the peer sees EOF without waiting for the client to be destroyed.
  18497. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  18498. {{"X-Bad", "a\r\nInjected: 1"}});
  18499. EXPECT_FALSE(client.connect());
  18500. t.join();
  18501. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  18502. EXPECT_EQ(0, received);
  18503. }
  18504. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  18505. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  18506. // contains "upgrade" as a substring is a different token and must not
  18507. // start a WebSocket handshake.
  18508. auto make_request = [](const std::vector<std::string> &connection_values) {
  18509. Request req;
  18510. req.method = "GET";
  18511. req.headers.emplace("Upgrade", "websocket");
  18512. for (const auto &value : connection_values) {
  18513. req.headers.emplace("Connection", value);
  18514. }
  18515. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18516. req.headers.emplace("Sec-WebSocket-Version", "13");
  18517. return req;
  18518. };
  18519. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  18520. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  18521. EXPECT_TRUE(
  18522. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  18523. EXPECT_TRUE(
  18524. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  18525. EXPECT_TRUE(
  18526. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  18527. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  18528. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  18529. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  18530. EXPECT_FALSE(
  18531. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  18532. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  18533. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18534. }
  18535. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  18536. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  18537. // asks recipients to match each protocol-name case-insensitively, and RFC
  18538. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  18539. // client naming websocket alongside another protocol, or on a second field
  18540. // line, is offering websocket; a value that merely contains "websocket" as a
  18541. // substring is a different protocol name and is not.
  18542. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  18543. Request req;
  18544. req.method = "GET";
  18545. for (const auto &value : upgrade_values) {
  18546. req.headers.emplace("Upgrade", value);
  18547. }
  18548. req.headers.emplace("Connection", "Upgrade");
  18549. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18550. req.headers.emplace("Sec-WebSocket-Version", "13");
  18551. return req;
  18552. };
  18553. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  18554. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  18555. EXPECT_TRUE(
  18556. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  18557. EXPECT_TRUE(
  18558. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  18559. EXPECT_TRUE(
  18560. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  18561. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  18562. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  18563. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  18564. EXPECT_FALSE(
  18565. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  18566. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  18567. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18568. }
  18569. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  18570. Server svr;
  18571. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  18572. auto port = svr.bind_to_any_port("localhost");
  18573. std::thread t([&]() { svr.listen_after_bind(); });
  18574. auto se = detail::scope_exit([&] {
  18575. svr.stop();
  18576. t.join();
  18577. });
  18578. svr.wait_until_ready();
  18579. Headers headers = {{"Upgrade", "websocket"},
  18580. {"Connection", "notupgrade"},
  18581. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  18582. {"Sec-WebSocket-Version", "13"}};
  18583. Client cli("localhost", port);
  18584. auto res = cli.Get("/ws", headers);
  18585. // The route exists only as a WebSocket route, so a request that fails the
  18586. // handshake check falls through to ordinary routing.
  18587. ASSERT_TRUE(res);
  18588. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  18589. }
  18590. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  18591. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  18592. // Connection value is the only thing left for the client to reject.
  18593. Server svr;
  18594. svr.Get("/ws", [](const Request &req, Response &res) {
  18595. res.status = StatusCode::SwitchingProtocol_101;
  18596. res.set_header("Upgrade", "websocket");
  18597. res.set_header("Connection", "notupgrade");
  18598. res.set_header("Sec-WebSocket-Accept",
  18599. detail::websocket_accept_key(
  18600. req.get_header_value("Sec-WebSocket-Key")));
  18601. });
  18602. auto port = svr.bind_to_any_port("localhost");
  18603. std::thread t([&]() { svr.listen_after_bind(); });
  18604. auto se = detail::scope_exit([&] {
  18605. svr.stop();
  18606. t.join();
  18607. });
  18608. svr.wait_until_ready();
  18609. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18610. auto res = client.connect();
  18611. EXPECT_FALSE(res);
  18612. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18613. EXPECT_FALSE(client.is_open());
  18614. }
  18615. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  18616. // The socket path doubles as the URL host, so it must not contain '/'.
  18617. const char *shard = getenv("GTEST_SHARD_INDEX");
  18618. const std::string sock_path =
  18619. shard ? std::string("httplib-ws-") + shard + ".sock"
  18620. : std::string("httplib-ws.sock");
  18621. std::remove(sock_path.c_str());
  18622. Server svr;
  18623. std::mutex mtx;
  18624. std::string received_host;
  18625. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18626. {
  18627. std::lock_guard<std::mutex> lock(mtx);
  18628. received_host = req.get_header_value("Host");
  18629. }
  18630. std::string msg;
  18631. while (ws.read(msg)) {
  18632. ws.send(msg);
  18633. }
  18634. });
  18635. svr.set_address_family(AF_UNIX);
  18636. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  18637. auto se = detail::scope_exit([&] {
  18638. svr.stop();
  18639. t.join();
  18640. std::remove(sock_path.c_str());
  18641. });
  18642. svr.wait_until_ready();
  18643. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  18644. client.set_address_family(AF_UNIX);
  18645. ASSERT_TRUE(client.connect());
  18646. ASSERT_TRUE(client.send("hello"));
  18647. std::string msg;
  18648. ASSERT_TRUE(client.read(msg));
  18649. client.close();
  18650. {
  18651. std::lock_guard<std::mutex> lock(mtx);
  18652. // There is no host:port for a Unix socket, so the same "localhost"
  18653. // placeholder the HTTP client uses is expected.
  18654. EXPECT_EQ("localhost", received_host);
  18655. }
  18656. }
  18657. // Two threads must never parse WebSocket frames from the same stream.
  18658. // close() used to read the peer's Close reply with its own frame read, so it
  18659. // raced a reader thread that was in the middle of a payload: the payload loop
  18660. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  18661. // so bytes taken by close() were replaced with bytes from further along the
  18662. // stream. The message kept its length and silently changed content.
  18663. //
  18664. // The raw peer below sends a frame header plus part of the payload, waits for
  18665. // the handler to call close(), and only then sends the rest. Whichever thread
  18666. // would win the race for those bytes, the message must arrive intact, because
  18667. // close() must not touch the stream while read() owns it.
  18668. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  18669. #ifndef _WIN32
  18670. signal(SIGPIPE, SIG_IGN);
  18671. #endif
  18672. const size_t payload_len = 120; // fits the 7-bit length field
  18673. const size_t prefix_len = 8;
  18674. const int attempts = 8;
  18675. std::string expected(payload_len, '\0');
  18676. for (size_t i = 0; i < payload_len; i++) {
  18677. expected[i] = static_cast<char>('a' + i % 26);
  18678. }
  18679. std::atomic<bool> peer_stalled{false};
  18680. std::atomic<bool> handler_done{false};
  18681. std::mutex received_mutex;
  18682. std::vector<std::string> received;
  18683. // Bound every wait, so a regression fails the test instead of hanging the
  18684. // suite.
  18685. auto wait_for = [](const std::atomic<bool> &flag) {
  18686. for (int i = 0; i < 500 && !flag; i++) {
  18687. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18688. }
  18689. };
  18690. Server svr;
  18691. svr.set_websocket_ping_interval(0);
  18692. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  18693. std::thread reader([&]() {
  18694. std::string msg;
  18695. while (ws.read(msg)) {
  18696. std::lock_guard<std::mutex> guard(received_mutex);
  18697. received.push_back(msg);
  18698. }
  18699. });
  18700. // Wait until the peer stalls mid-payload, so the reader thread is parked
  18701. // inside read_websocket_frame() when close() runs.
  18702. wait_for(peer_stalled);
  18703. ws.close();
  18704. reader.join();
  18705. handler_done = true;
  18706. });
  18707. auto port = svr.bind_to_any_port("127.0.0.1");
  18708. std::thread t([&]() { svr.listen_after_bind(); });
  18709. auto se = detail::scope_exit([&] {
  18710. svr.stop();
  18711. t.join();
  18712. });
  18713. svr.wait_until_ready();
  18714. auto send_bytes = [](socket_t s, const std::string &data) {
  18715. #ifdef _WIN32
  18716. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  18717. #else
  18718. auto n = ::send(s, data.data(), data.size(), 0);
  18719. #endif
  18720. return n == static_cast<decltype(n)>(data.size());
  18721. };
  18722. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  18723. // Every length used here fits the 7-bit length field.
  18724. auto masked_header = [](uint8_t first_byte, size_t len) {
  18725. std::string h;
  18726. h += static_cast<char>(first_byte);
  18727. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  18728. h.append(4, '\0'); // mask key
  18729. return h;
  18730. };
  18731. for (int attempt = 0; attempt < attempts; attempt++) {
  18732. peer_stalled = false;
  18733. handler_done = false;
  18734. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  18735. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  18736. auto se_sock = detail::scope_exit([&] {
  18737. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  18738. });
  18739. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18740. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18741. sockaddr_in addr{};
  18742. addr.sin_family = AF_INET;
  18743. addr.sin_port = htons(static_cast<uint16_t>(port));
  18744. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18745. ASSERT_EQ(
  18746. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  18747. << "attempt " << attempt;
  18748. ASSERT_TRUE(send_bytes(sock,
  18749. "GET /ws HTTP/1.1\r\n"
  18750. "Host: 127.0.0.1\r\n"
  18751. "Upgrade: websocket\r\n"
  18752. "Connection: Upgrade\r\n"
  18753. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  18754. "Sec-WebSocket-Version: 13\r\n"
  18755. "\r\n"))
  18756. << "attempt " << attempt;
  18757. std::string response;
  18758. while (response.find("\r\n\r\n") == std::string::npos) {
  18759. char buf[512];
  18760. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  18761. if (n <= 0) { break; }
  18762. response.append(buf, static_cast<size_t>(n));
  18763. }
  18764. ASSERT_NE(std::string::npos, response.find(" 101 "))
  18765. << "attempt " << attempt;
  18766. // Send the header of a Binary message but only the first prefix_len bytes
  18767. // of its payload, leaving the reader thread stalled inside the payload.
  18768. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  18769. expected.substr(0, prefix_len)))
  18770. << "attempt " << attempt;
  18771. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18772. peer_stalled = true;
  18773. // Let close() send its Close frame and park in its own read before the
  18774. // rest of the payload arrives, so both threads are waiting for it.
  18775. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18776. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  18777. close_frame += static_cast<char>(0x03); // status 1000
  18778. close_frame += static_cast<char>(0xE8);
  18779. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  18780. << "attempt " << attempt;
  18781. // Closing the peer releases the reader thread even on the buggy path,
  18782. // where it waits for bytes another thread already consumed.
  18783. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18784. detail::close_socket(sock);
  18785. sock = INVALID_SOCKET;
  18786. wait_for(handler_done);
  18787. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  18788. }
  18789. std::lock_guard<std::mutex> guard(received_mutex);
  18790. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  18791. << "a message in flight when close() ran was dropped";
  18792. for (size_t i = 0; i < received.size(); i++) {
  18793. EXPECT_EQ(expected, received[i]) << "message " << i;
  18794. }
  18795. }
  18796. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18797. class WebSocketSSLIntegrationTest : public ::testing::Test {
  18798. protected:
  18799. void SetUp() override {
  18800. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  18801. SERVER_PRIVATE_KEY_FILE);
  18802. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18803. std::string msg;
  18804. ws::ReadResult ret;
  18805. while ((ret = ws.read(msg))) {
  18806. if (ret == ws::Binary) {
  18807. ws.send(msg.data(), msg.size());
  18808. } else {
  18809. ws.send(msg);
  18810. }
  18811. }
  18812. });
  18813. port_ = server_->bind_to_any_port(HOST);
  18814. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18815. server_->wait_until_ready();
  18816. }
  18817. void TearDown() override {
  18818. server_->stop();
  18819. if (server_thread_.joinable()) { server_thread_.join(); }
  18820. }
  18821. std::unique_ptr<SSLServer> server_;
  18822. std::thread server_thread_;
  18823. int port_ = 0;
  18824. };
  18825. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  18826. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18827. "/ws-echo");
  18828. client.enable_server_certificate_verification(false);
  18829. ASSERT_TRUE(client.connect());
  18830. ASSERT_TRUE(client.is_open());
  18831. ASSERT_TRUE(client.send("Hello WSS"));
  18832. std::string msg;
  18833. EXPECT_EQ(ws::Text, client.read(msg));
  18834. EXPECT_EQ("Hello WSS", msg);
  18835. client.close();
  18836. }
  18837. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  18838. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  18839. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  18840. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  18841. // client (without calling close() first) is the only path that runs
  18842. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  18843. // bug exactly.
  18844. //
  18845. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  18846. // when linked against an instrumented libssl; run under Valgrind to catch it
  18847. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  18848. // suite (the freed session otherwise stalls on the close handshake) — this test
  18849. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  18850. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  18851. {
  18852. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18853. "/ws-echo");
  18854. client.enable_server_certificate_verification(false);
  18855. client.set_read_timeout(2, 0);
  18856. client.set_write_timeout(2, 0);
  18857. ASSERT_TRUE(client.connect());
  18858. ASSERT_TRUE(client.is_open());
  18859. ASSERT_TRUE(client.send("still open"));
  18860. // Intentionally do NOT call client.close(): leaving scope runs
  18861. // shutdown_and_close() with the WebSocket still open, which must send the
  18862. // close frame while the TLS session is still alive.
  18863. }
  18864. }
  18865. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  18866. // shutdown_and_close() at the start of connect(), reproducing the same
  18867. // use-after-free within the test body rather than at scope exit. The second
  18868. // connect must succeed and echo, proving the close handshake ran over a live
  18869. // session. See the note above about memory-tool requirements.
  18870. TEST_F(WebSocketSSLIntegrationTest,
  18871. ReconnectWhileOpenSendsCloseOverLiveSession) {
  18872. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18873. "/ws-echo");
  18874. client.enable_server_certificate_verification(false);
  18875. client.set_read_timeout(2, 0);
  18876. client.set_write_timeout(2, 0);
  18877. ASSERT_TRUE(client.connect());
  18878. ASSERT_TRUE(client.is_open());
  18879. ASSERT_TRUE(client.send("still open"));
  18880. // Reconnect without closing first: connect() calls shutdown_and_close() on
  18881. // the still-open connection, which must not touch a freed TLS session.
  18882. ASSERT_TRUE(client.connect());
  18883. ASSERT_TRUE(client.is_open());
  18884. ASSERT_TRUE(client.send("after reconnect"));
  18885. std::string msg;
  18886. EXPECT_EQ(ws::Text, client.read(msg));
  18887. EXPECT_EQ("after reconnect", msg);
  18888. client.close();
  18889. }
  18890. #endif
  18891. #ifdef CPPHTTPLIB_SSL_ENABLED
  18892. class WebSocketSSLCATest : public ::testing::Test {
  18893. protected:
  18894. void SetUp() override {
  18895. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  18896. SERVER_PRIVATE_KEY_FILE);
  18897. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18898. std::string msg;
  18899. while (ws.read(msg)) {
  18900. ws.send(msg);
  18901. }
  18902. });
  18903. port_ = server_->bind_to_any_port("127.0.0.1");
  18904. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18905. server_->wait_until_ready();
  18906. }
  18907. void TearDown() override {
  18908. server_->stop();
  18909. if (server_thread_.joinable()) { server_thread_.join(); }
  18910. }
  18911. std::string url() const {
  18912. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  18913. }
  18914. std::unique_ptr<SSLServer> server_;
  18915. std::thread server_thread_;
  18916. int port_ = 0;
  18917. };
  18918. // A custom CA loaded as PEM verifies the server with full certificate
  18919. // verification enabled
  18920. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  18921. ws::WebSocketClient client(url());
  18922. std::string cert;
  18923. read_file(SERVER_CERT2_FILE, cert);
  18924. client.load_ca_cert_store(cert.c_str(), cert.size());
  18925. ASSERT_TRUE(client.connect());
  18926. ASSERT_TRUE(client.send("hello"));
  18927. std::string msg;
  18928. EXPECT_EQ(ws::Text, client.read(msg));
  18929. EXPECT_EQ("hello", msg);
  18930. client.close();
  18931. }
  18932. // A custom CA that does not cover the server must fail verification (the
  18933. // custom CA is exclusive; system certs are not loaded alongside it)
  18934. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  18935. ws::WebSocketClient client(url());
  18936. std::string cert;
  18937. read_file(CLIENT_CA_CERT_FILE, cert);
  18938. client.load_ca_cert_store(cert.c_str(), cert.size());
  18939. auto res = client.connect();
  18940. ASSERT_FALSE(res);
  18941. EXPECT_EQ(Error::SSLServerVerification, res.error());
  18942. EXPECT_EQ(-1, res.status());
  18943. EXPECT_NE(0u, res.ssl_backend_error());
  18944. }
  18945. // The same CA as a file path rather than PEM in memory
  18946. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  18947. ws::WebSocketClient client(url());
  18948. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18949. ASSERT_TRUE(client.connect());
  18950. ASSERT_TRUE(client.send("hello"));
  18951. std::string msg;
  18952. EXPECT_EQ(ws::Text, client.read(msg));
  18953. EXPECT_EQ("hello", msg);
  18954. client.close();
  18955. }
  18956. // ...and a CA file that does not cover the server still fails, so it is the
  18957. // path above that decides the outcome
  18958. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  18959. ws::WebSocketClient client(url());
  18960. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  18961. ASSERT_FALSE(client.connect());
  18962. }
  18963. // Regression test: reconnecting with a native custom CA store used to reuse
  18964. // a store handle the previous TLS context had already freed (use-after-free
  18965. // under the OpenSSL backend). The context now lives as long as the client.
  18966. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  18967. ws::WebSocketClient client(url());
  18968. std::string cert;
  18969. read_file(SERVER_CERT2_FILE, cert);
  18970. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  18971. ASSERT_TRUE(client.connect());
  18972. client.close();
  18973. ASSERT_TRUE(client.connect());
  18974. ASSERT_TRUE(client.send("again"));
  18975. std::string msg;
  18976. EXPECT_EQ(ws::Text, client.read(msg));
  18977. EXPECT_EQ("again", msg);
  18978. client.close();
  18979. }
  18980. // Regression test: a certificate with a trusted chain but no identity match
  18981. // for the server IP must be rejected. The Mbed TLS backend used to skip
  18982. // verification entirely for IP hosts, so this connection succeeded there.
  18983. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  18984. // chain verification while the identity check must still fail.
  18985. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  18986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18987. ASSERT_TRUE(svr.is_valid());
  18988. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18989. std::string msg;
  18990. while (ws.read(msg)) {
  18991. ws.send(msg);
  18992. }
  18993. });
  18994. auto port = svr.bind_to_any_port("127.0.0.1");
  18995. auto t = std::thread([&]() { svr.listen_after_bind(); });
  18996. auto se = detail::scope_exit([&] {
  18997. svr.stop();
  18998. t.join();
  18999. });
  19000. svr.wait_until_ready();
  19001. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  19002. "/echo");
  19003. std::string cert;
  19004. read_file(SERVER_CERT_FILE, cert);
  19005. client.load_ca_cert_store(cert.c_str(), cert.size());
  19006. ASSERT_FALSE(client.connect());
  19007. }
  19008. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  19009. // SNI, so nothing binds the host name to the TLS session. These bind the
  19010. // server to "localhost" instead, the only shape that exercises the SNI and
  19011. // hostname-verification path with certificate verification left enabled.
  19012. class WebSocketSSLDnsHostTest : public ::testing::Test {
  19013. protected:
  19014. void Start(const char *cert_file) {
  19015. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  19016. SERVER_PRIVATE_KEY_FILE);
  19017. ASSERT_TRUE(server_->is_valid());
  19018. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19019. std::string msg;
  19020. while (ws.read(msg)) {
  19021. ws.send(msg);
  19022. }
  19023. });
  19024. port_ = server_->bind_to_any_port("localhost");
  19025. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19026. server_->wait_until_ready();
  19027. }
  19028. void TearDown() override {
  19029. if (server_) { server_->stop(); }
  19030. if (server_thread_.joinable()) { server_thread_.join(); }
  19031. }
  19032. std::string url() const {
  19033. return "wss://localhost:" + std::to_string(port_) + "/echo";
  19034. }
  19035. std::unique_ptr<SSLServer> server_;
  19036. std::thread server_thread_;
  19037. int port_ = 0;
  19038. };
  19039. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  19040. // out and the connection is usable
  19041. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  19042. Start(SERVER_CERT2_FILE);
  19043. ws::WebSocketClient client(url());
  19044. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19045. ASSERT_TRUE(client.connect());
  19046. ASSERT_TRUE(client.send("hello"));
  19047. std::string msg;
  19048. EXPECT_EQ(ws::Text, client.read(msg));
  19049. EXPECT_EQ("hello", msg);
  19050. client.close();
  19051. }
  19052. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  19053. // while the identity check must still reject "localhost"
  19054. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  19055. Start(SERVER_CERT_FILE);
  19056. ws::WebSocketClient client(url());
  19057. client.set_ca_cert_path(SERVER_CERT_FILE);
  19058. auto res = client.connect();
  19059. ASSERT_FALSE(res);
  19060. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  19061. EXPECT_EQ(-1, res.status());
  19062. }
  19063. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  19064. // disabled: the chain is still checked, only the identity check is skipped
  19065. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  19066. Start(SERVER_CERT_FILE);
  19067. ws::WebSocketClient client(url());
  19068. client.set_ca_cert_path(SERVER_CERT_FILE);
  19069. client.enable_server_hostname_verification(false);
  19070. ASSERT_TRUE(client.connect());
  19071. ASSERT_TRUE(client.send("hello"));
  19072. std::string msg;
  19073. EXPECT_EQ(ws::Text, client.read(msg));
  19074. EXPECT_EQ("hello", msg);
  19075. client.close();
  19076. }
  19077. // A CA that did not sign the server certificate fails the chain, even though
  19078. // the name would match
  19079. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  19080. Start(SERVER_CERT2_FILE);
  19081. ws::WebSocketClient client(url());
  19082. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19083. ASSERT_FALSE(client.connect());
  19084. }
  19085. // With verification disabled, neither the chain nor the name is checked
  19086. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  19087. Start(SERVER_CERT_FILE);
  19088. ws::WebSocketClient client(url());
  19089. client.enable_server_certificate_verification(false);
  19090. ASSERT_TRUE(client.connect());
  19091. ASSERT_TRUE(client.send("hello"));
  19092. std::string msg;
  19093. EXPECT_EQ(ws::Text, client.read(msg));
  19094. EXPECT_EQ("hello", msg);
  19095. client.close();
  19096. }
  19097. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  19098. protected:
  19099. void SetUp() override {
  19100. server_ = httplib::detail::make_unique<SSLServer>(
  19101. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19102. ASSERT_TRUE(server_->is_valid());
  19103. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19104. std::string msg;
  19105. while (ws.read(msg)) {
  19106. ws.send(msg);
  19107. }
  19108. });
  19109. port_ = server_->bind_to_any_port("localhost");
  19110. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19111. server_->wait_until_ready();
  19112. }
  19113. void TearDown() override {
  19114. server_->stop();
  19115. if (server_thread_.joinable()) { server_thread_.join(); }
  19116. }
  19117. std::string url() const {
  19118. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  19119. }
  19120. void ConnectWithClientCert(const std::string &client_cert_file,
  19121. const std::string &client_private_key_file,
  19122. const char *private_key_password) {
  19123. std::string cert_pem, key_pem;
  19124. read_file(client_cert_file, cert_pem);
  19125. read_file(client_private_key_file, key_pem);
  19126. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  19127. key_pem.c_str(), key_pem.size(),
  19128. private_key_password};
  19129. ws::WebSocketClient client(url(), pem);
  19130. ASSERT_TRUE(client.is_valid());
  19131. client.enable_server_certificate_verification(false);
  19132. ASSERT_TRUE(client.connect());
  19133. ASSERT_TRUE(client.send("hello"));
  19134. std::string msg;
  19135. EXPECT_EQ(ws::Text, client.read(msg));
  19136. EXPECT_EQ("hello", msg);
  19137. client.close();
  19138. }
  19139. std::unique_ptr<SSLServer> server_;
  19140. std::thread server_thread_;
  19141. int port_ = 0;
  19142. };
  19143. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  19144. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  19145. }
  19146. // Control for the tests above: the fixture's server really does require a
  19147. // client certificate, so it is the PEM the constructor installed that decides
  19148. // the outcome.
  19149. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  19150. ws::WebSocketClient client(url());
  19151. ASSERT_TRUE(client.is_valid());
  19152. client.enable_server_certificate_verification(false);
  19153. EXPECT_FALSE(client.connect());
  19154. }
  19155. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  19156. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  19157. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  19158. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  19159. }
  19160. #endif
  19161. #if !defined(_WIN32)
  19162. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  19163. auto secret_dir = std::string("./symlink_test_secret");
  19164. auto served_dir = std::string("./symlink_test_served");
  19165. auto secret_file = secret_dir + "/secret.txt";
  19166. auto symlink_path = served_dir + "/escape";
  19167. // Setup: create directories and files
  19168. mkdir(secret_dir.c_str(), 0755);
  19169. mkdir(served_dir.c_str(), 0755);
  19170. {
  19171. std::ofstream ofs(secret_file);
  19172. ofs << "SECRET_DATA";
  19173. }
  19174. // Create symlink using absolute path so it resolves correctly
  19175. #ifdef PATH_MAX
  19176. char abs_secret[PATH_MAX];
  19177. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  19178. #else
  19179. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  19180. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  19181. ASSERT_NE(nullptr, abs_secret);
  19182. #endif
  19183. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  19184. auto se = detail::scope_exit([&] {
  19185. unlink(symlink_path.c_str());
  19186. unlink(secret_file.c_str());
  19187. rmdir(served_dir.c_str());
  19188. rmdir(secret_dir.c_str());
  19189. });
  19190. Server svr;
  19191. svr.set_mount_point("/", served_dir);
  19192. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19193. auto se2 = detail::scope_exit([&] {
  19194. svr.stop();
  19195. listen_thread.join();
  19196. });
  19197. svr.wait_until_ready();
  19198. Client cli("localhost", PORT);
  19199. // Symlink pointing outside base dir should be blocked
  19200. auto res = cli.Get("/escape/secret.txt");
  19201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19202. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19203. }
  19204. #endif
  19205. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  19206. // A GET request with Content-Length to a static file handler must have its
  19207. // body drained before the keep-alive connection is reused. Otherwise the
  19208. // unread body bytes are interpreted as the next HTTP request.
  19209. //
  19210. // The body is sent AFTER receiving the first response (as in the original
  19211. // PoC) so that the stream_line_reader cannot buffer it together with the
  19212. // headers of the first request.
  19213. Server svr;
  19214. svr.set_mount_point("/", "./www");
  19215. std::atomic<int> smuggled_count(0);
  19216. svr.Get("/smuggled", [&](const Request &, Response &res) {
  19217. smuggled_count++;
  19218. res.set_content("oops", "text/plain");
  19219. });
  19220. auto port = svr.bind_to_any_port("localhost");
  19221. thread t = thread([&] { svr.listen_after_bind(); });
  19222. auto se = detail::scope_exit([&] {
  19223. svr.stop();
  19224. t.join();
  19225. });
  19226. svr.wait_until_ready();
  19227. auto error = Error::Success;
  19228. auto sock = detail::create_client_socket(
  19229. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  19230. /*connection_timeout_sec=*/2, 0,
  19231. /*read_timeout_sec=*/2, 0,
  19232. /*write_timeout_sec=*/2, 0, std::string(), error);
  19233. ASSERT_NE(INVALID_SOCKET, sock);
  19234. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19235. // The "smuggled" request will be sent as the body of the outer GET
  19236. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  19237. "Host: localhost\r\n"
  19238. "Connection: close\r\n"
  19239. "\r\n";
  19240. // Step 1: Send only the outer request headers (no body yet)
  19241. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  19242. "Host: localhost\r\n"
  19243. "Content-Length: " +
  19244. std::to_string(smuggled.size()) +
  19245. "\r\n"
  19246. "\r\n";
  19247. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  19248. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  19249. // Step 2: Read the first response (server serves file without reading body)
  19250. std::string first_response;
  19251. char buf[4096];
  19252. for (;;) {
  19253. auto n = recv(sock, buf, sizeof(buf), 0);
  19254. if (n <= 0) break;
  19255. first_response.append(buf, static_cast<size_t>(n));
  19256. // Stop once we have a complete response (headers + body)
  19257. auto hdr_end = first_response.find("\r\n\r\n");
  19258. if (hdr_end != std::string::npos) {
  19259. // Check for Content-Length to know when the body is complete
  19260. auto cl_pos = first_response.find("Content-Length:");
  19261. if (cl_pos != std::string::npos) {
  19262. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  19263. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  19264. auto cl = std::stoul(
  19265. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  19266. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  19267. } else {
  19268. break; // No Content-Length, assume headers-only response
  19269. }
  19270. }
  19271. }
  19272. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  19273. // Step 3: Now send the body, which looks like a new HTTP request.
  19274. // On a vulnerable server the keep-alive loop reads this as a second request.
  19275. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  19276. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  19277. // Step 4: Try to read a second response (should NOT exist after fix)
  19278. std::string second_response;
  19279. for (;;) {
  19280. auto n = recv(sock, buf, sizeof(buf), 0);
  19281. if (n <= 0) break;
  19282. second_response.append(buf, static_cast<size_t>(n));
  19283. }
  19284. // The smuggled request must NOT have been processed
  19285. EXPECT_EQ(0, smuggled_count.load());
  19286. }
  19287. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19288. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  19289. // must be rejected with 400 Bad Request.
  19290. Server svr;
  19291. svr.Post("/test", [&](const Request &, Response &res) {
  19292. res.set_content("ok", "text/plain");
  19293. });
  19294. thread t = thread([&] { svr.listen(HOST, PORT); });
  19295. auto se = detail::scope_exit([&] {
  19296. svr.stop();
  19297. t.join();
  19298. ASSERT_FALSE(svr.is_running());
  19299. });
  19300. svr.wait_until_ready();
  19301. // Exact "chunked"
  19302. {
  19303. auto req = "POST /test HTTP/1.1\r\n"
  19304. "Host: localhost\r\n"
  19305. "Content-Length: 5\r\n"
  19306. "Transfer-Encoding: chunked\r\n"
  19307. "Connection: close\r\n"
  19308. "\r\n"
  19309. "hello";
  19310. std::string response;
  19311. ASSERT_TRUE(send_request(1, req, &response));
  19312. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19313. response.substr(0, response.find("\r\n")));
  19314. }
  19315. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  19316. {
  19317. auto req = "POST /test HTTP/1.1\r\n"
  19318. "Host: localhost\r\n"
  19319. "Content-Length: 5\r\n"
  19320. "Transfer-Encoding: gzip, chunked\r\n"
  19321. "Connection: close\r\n"
  19322. "\r\n"
  19323. "hello";
  19324. std::string response;
  19325. ASSERT_TRUE(send_request(1, req, &response));
  19326. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19327. response.substr(0, response.find("\r\n")));
  19328. }
  19329. }
  19330. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  19331. Server svr;
  19332. svr.Post("/test", [&](const Request &, Response &res) {
  19333. res.set_content("ok", "text/plain");
  19334. });
  19335. thread t = thread([&] { svr.listen(HOST, PORT); });
  19336. auto se = detail::scope_exit([&] {
  19337. svr.stop();
  19338. t.join();
  19339. ASSERT_FALSE(svr.is_running());
  19340. });
  19341. svr.wait_until_ready();
  19342. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  19343. // length cannot be determined, so the server must answer 400 and close
  19344. // rather than treat the request as bodyless and leave the body in the
  19345. // socket for the next request to pick up.
  19346. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  19347. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  19348. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  19349. std::string response;
  19350. ASSERT_TRUE(send_request(1, req, &response));
  19351. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19352. response.substr(0, response.find("\r\n")))
  19353. << transfer_encoding;
  19354. }
  19355. // RFC 9110 5.3: the codings may also be split across several
  19356. // Transfer-Encoding lines, which combine in the order they were received.
  19357. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  19358. // just like the single-line "chunked, gzip" above.
  19359. {
  19360. auto req = "POST /test HTTP/1.1\r\n"
  19361. "Host: localhost\r\n"
  19362. "Transfer-Encoding: chunked\r\n"
  19363. "Transfer-Encoding: gzip\r\n"
  19364. "\r\n"
  19365. "0\r\n\r\n";
  19366. std::string response;
  19367. ASSERT_TRUE(send_request(1, req, &response));
  19368. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19369. response.substr(0, response.find("\r\n")));
  19370. }
  19371. // A sequence ending in chunked stays valid.
  19372. auto req = "POST /test HTTP/1.1\r\n"
  19373. "Host: localhost\r\n"
  19374. "Transfer-Encoding: gzip, chunked\r\n"
  19375. "Connection: close\r\n"
  19376. "\r\n"
  19377. "0\r\n\r\n";
  19378. std::string response;
  19379. ASSERT_TRUE(send_request(1, req, &response));
  19380. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19381. // ...including when it is spread over several lines.
  19382. auto split_req = "POST /test HTTP/1.1\r\n"
  19383. "Host: localhost\r\n"
  19384. "Transfer-Encoding: gzip\r\n"
  19385. "Transfer-Encoding: chunked\r\n"
  19386. "Connection: close\r\n"
  19387. "\r\n"
  19388. "0\r\n\r\n";
  19389. std::string split_response;
  19390. ASSERT_TRUE(send_request(1, split_req, &split_response));
  19391. EXPECT_EQ("HTTP/1.1 200 OK",
  19392. split_response.substr(0, split_response.find("\r\n")));
  19393. }
  19394. // Regression for issue #2450: a DELETE without Content-Length on a
  19395. // keep-alive connection must not let the post-response drain consume the
  19396. // next request's bytes.
  19397. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  19398. Server svr;
  19399. std::atomic<int> delete_count(0);
  19400. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  19401. delete_count++;
  19402. res.status = StatusCode::NoContent_204;
  19403. });
  19404. auto port = svr.bind_to_any_port(HOST);
  19405. thread t = thread([&] { svr.listen_after_bind(); });
  19406. auto se = detail::scope_exit([&] {
  19407. svr.stop();
  19408. t.join();
  19409. });
  19410. svr.wait_until_ready();
  19411. auto error = Error::Success;
  19412. auto sock = detail::create_client_socket(
  19413. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19414. /*connection_timeout_sec=*/2, 0,
  19415. /*read_timeout_sec=*/2, 0,
  19416. /*write_timeout_sec=*/2, 0, std::string(), error);
  19417. ASSERT_NE(INVALID_SOCKET, sock);
  19418. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19419. auto send_request_and_read_response = [&](const std::string &req,
  19420. std::string &out) -> bool {
  19421. auto sent = send(sock, req.data(), req.size(), 0);
  19422. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  19423. char buf[4096];
  19424. for (;;) {
  19425. auto n = recv(sock, buf, sizeof(buf), 0);
  19426. if (n <= 0) { return !out.empty(); }
  19427. out.append(buf, static_cast<size_t>(n));
  19428. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  19429. }
  19430. };
  19431. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  19432. "Host: localhost\r\n"
  19433. "\r\n";
  19434. std::string resp1;
  19435. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  19436. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  19437. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  19438. "Host: localhost\r\n"
  19439. "Connection: close\r\n"
  19440. "\r\n";
  19441. std::string resp2;
  19442. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  19443. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  19444. EXPECT_EQ(2, delete_count.load());
  19445. }
  19446. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  19447. Server svr;
  19448. svr.Post("/ingest", [&](const Request &, Response &res,
  19449. const ContentReader &content_reader) {
  19450. auto consumed = content_reader([](const char *, size_t) { return false; });
  19451. EXPECT_FALSE(consumed);
  19452. res.status = StatusCode::Conflict_409;
  19453. res.set_header("Connection", "close");
  19454. });
  19455. auto port = svr.bind_to_any_port(HOST);
  19456. thread t = thread([&] { svr.listen_after_bind(); });
  19457. auto se = detail::scope_exit([&] {
  19458. svr.stop();
  19459. t.join();
  19460. });
  19461. svr.wait_until_ready();
  19462. auto error = Error::Success;
  19463. auto sock = detail::create_client_socket(
  19464. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19465. /*connection_timeout_sec=*/2, 0,
  19466. /*read_timeout_sec=*/1, 0,
  19467. /*write_timeout_sec=*/2, 0, std::string(), error);
  19468. ASSERT_NE(INVALID_SOCKET, sock);
  19469. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19470. std::string request = "POST /ingest HTTP/1.1\r\n"
  19471. "Host: localhost\r\n"
  19472. "Transfer-Encoding: chunked\r\n"
  19473. "\r\n"
  19474. "4\r\n"
  19475. "data\r\n";
  19476. auto sent = send(sock, request.data(), request.size(), 0);
  19477. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  19478. std::string response;
  19479. ssize_t received = 0;
  19480. do {
  19481. char buf[4096];
  19482. received = recv(sock, buf, sizeof(buf), 0);
  19483. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  19484. } while (received > 0);
  19485. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  19486. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  19487. EXPECT_EQ(0, received);
  19488. }
  19489. namespace no_proxy_test {
  19490. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  19491. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  19492. // calling listen().
  19493. class ScopedServer {
  19494. public:
  19495. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  19496. ~ScopedServer() {
  19497. svr_.stop();
  19498. if (th_.joinable()) { th_.join(); }
  19499. }
  19500. Server &svr() { return svr_; }
  19501. int port() const { return port_; }
  19502. void listen() {
  19503. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19504. svr_.wait_until_ready();
  19505. }
  19506. private:
  19507. Server svr_;
  19508. std::thread th_;
  19509. int port_ = 0;
  19510. };
  19511. class ProxyAndTargetServers {
  19512. public:
  19513. ProxyAndTargetServers() {
  19514. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  19515. proxy_hits_++;
  19516. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19517. res.set_content("via-proxy", "text/plain");
  19518. });
  19519. target_.Get(".*", [this](const Request &req, Response &res) {
  19520. target_hits_++;
  19521. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19522. res.set_content("direct", "text/plain");
  19523. });
  19524. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  19525. target_port_ = target_.bind_to_any_port("127.0.0.1");
  19526. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  19527. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  19528. proxy_mock_.wait_until_ready();
  19529. target_.wait_until_ready();
  19530. }
  19531. ~ProxyAndTargetServers() {
  19532. proxy_mock_.stop();
  19533. target_.stop();
  19534. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  19535. if (target_thread_.joinable()) { target_thread_.join(); }
  19536. }
  19537. Server &proxy_mock() { return proxy_mock_; }
  19538. Server &target() { return target_; }
  19539. int proxy_port() const { return proxy_port_; }
  19540. int target_port() const { return target_port_; }
  19541. int proxy_hits() const { return proxy_hits_.load(); }
  19542. int target_hits() const { return target_hits_.load(); }
  19543. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  19544. void reset_counters() {
  19545. proxy_hits_ = 0;
  19546. target_hits_ = 0;
  19547. last_had_proxy_authz_ = false;
  19548. }
  19549. private:
  19550. Server proxy_mock_;
  19551. Server target_;
  19552. std::thread proxy_thread_;
  19553. std::thread target_thread_;
  19554. int proxy_port_ = 0;
  19555. int target_port_ = 0;
  19556. std::atomic<int> proxy_hits_{0};
  19557. std::atomic<int> target_hits_{0};
  19558. std::atomic<bool> last_had_proxy_authz_{false};
  19559. };
  19560. inline std::unique_ptr<Client> make_client(const std::string &host,
  19561. ProxyAndTargetServers &s) {
  19562. auto cli = detail::make_unique<Client>(host, s.target_port());
  19563. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  19564. cli->set_proxy("127.0.0.1", s.proxy_port());
  19565. return cli;
  19566. }
  19567. } // namespace no_proxy_test
  19568. using no_proxy_test::make_client;
  19569. using no_proxy_test::ProxyAndTargetServers;
  19570. TEST(NoProxyTest, ExactHostnameBypasses) {
  19571. ProxyAndTargetServers s;
  19572. auto cli = make_client("example.com", s);
  19573. cli->set_no_proxy({"example.com"});
  19574. auto res = cli->Get("/");
  19575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19576. EXPECT_EQ(0, s.proxy_hits());
  19577. EXPECT_EQ(1, s.target_hits());
  19578. }
  19579. TEST(NoProxyTest, SubdomainBypasses) {
  19580. ProxyAndTargetServers s;
  19581. auto cli = make_client("foo.example.com", s);
  19582. cli->set_no_proxy({"example.com"});
  19583. auto res = cli->Get("/");
  19584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19585. EXPECT_EQ(0, s.proxy_hits());
  19586. EXPECT_EQ(1, s.target_hits());
  19587. }
  19588. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  19589. // Regression guard: "evilexample.com" must not be considered a subdomain
  19590. // of "example.com". Without the dot-boundary rule, a naive endsWith
  19591. // check would let traffic bypass the proxy and leak credentials direct
  19592. // to the attacker host.
  19593. ProxyAndTargetServers s;
  19594. auto cli = make_client("evilexample.com", s);
  19595. cli->set_no_proxy({"example.com"});
  19596. auto res = cli->Get("/");
  19597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19598. EXPECT_GE(s.proxy_hits(), 1);
  19599. EXPECT_EQ(0, s.target_hits());
  19600. }
  19601. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  19602. ProxyAndTargetServers s;
  19603. auto cli = make_client("example.com.evil.com", s);
  19604. cli->set_no_proxy({"example.com"});
  19605. auto res = cli->Get("/");
  19606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19607. EXPECT_GE(s.proxy_hits(), 1);
  19608. EXPECT_EQ(0, s.target_hits());
  19609. }
  19610. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  19611. ProxyAndTargetServers s;
  19612. auto cli = make_client("example.com", s);
  19613. cli->set_no_proxy({".example.com"});
  19614. auto res = cli->Get("/");
  19615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19616. EXPECT_EQ(0, s.proxy_hits());
  19617. EXPECT_EQ(1, s.target_hits());
  19618. }
  19619. TEST(NoProxyTest, CaseInsensitiveHostname) {
  19620. ProxyAndTargetServers s;
  19621. auto cli = make_client("Example.COM", s);
  19622. cli->set_no_proxy({"EXAMPLE.com"});
  19623. auto res = cli->Get("/");
  19624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19625. EXPECT_EQ(0, s.proxy_hits());
  19626. EXPECT_EQ(1, s.target_hits());
  19627. }
  19628. TEST(NoProxyTest, TrailingDotIsNormalized) {
  19629. ProxyAndTargetServers s;
  19630. auto cli = make_client("example.com.", s);
  19631. cli->set_no_proxy({"example.com"});
  19632. auto res = cli->Get("/");
  19633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19634. EXPECT_EQ(0, s.proxy_hits());
  19635. EXPECT_EQ(1, s.target_hits());
  19636. }
  19637. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  19638. // Trailing dots must be normalized on BOTH sides — host and entry.
  19639. // An implementation that only strips the host-side trailing dot would
  19640. // fail to match host "example.com" against entry "example.com." because
  19641. // a literal substring search would compare 11 chars against 12.
  19642. ProxyAndTargetServers s;
  19643. auto cli = make_client("example.com", s);
  19644. cli->set_no_proxy({"example.com."});
  19645. auto res = cli->Get("/");
  19646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19647. EXPECT_EQ(0, s.proxy_hits());
  19648. EXPECT_EQ(1, s.target_hits());
  19649. }
  19650. TEST(NoProxyTest, WildcardBypassesEverything) {
  19651. ProxyAndTargetServers s;
  19652. auto cli = make_client("anything.invalid.test", s);
  19653. cli->set_no_proxy({"*"});
  19654. auto res = cli->Get("/");
  19655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19656. EXPECT_EQ(0, s.proxy_hits());
  19657. EXPECT_EQ(1, s.target_hits());
  19658. }
  19659. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  19660. ProxyAndTargetServers s;
  19661. Client cli("127.0.0.1", s.target_port());
  19662. cli.set_proxy("127.0.0.1", s.proxy_port());
  19663. cli.set_no_proxy({"127.0.0.1"});
  19664. auto res = cli.Get("/");
  19665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19666. EXPECT_EQ(0, s.proxy_hits());
  19667. EXPECT_EQ(1, s.target_hits());
  19668. }
  19669. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  19670. ProxyAndTargetServers s;
  19671. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  19672. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  19673. cli.set_proxy("127.0.0.1", s.proxy_port());
  19674. cli.set_no_proxy({"::1"});
  19675. auto res = cli.Get("/");
  19676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19677. EXPECT_EQ(0, s.proxy_hits());
  19678. EXPECT_EQ(1, s.target_hits());
  19679. }
  19680. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  19681. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  19682. // must still be recognized as IPv6 for CIDR matching. Implementations
  19683. // that detect IPv6 only when the host begins with '[' would parse the
  19684. // host as a hostname and miss the match.
  19685. ProxyAndTargetServers s;
  19686. Client cli("fe80::1", s.target_port());
  19687. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19688. cli.set_proxy("127.0.0.1", s.proxy_port());
  19689. cli.set_no_proxy({"fe80::/10"});
  19690. auto res = cli.Get("/");
  19691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19692. EXPECT_EQ(0, s.proxy_hits());
  19693. EXPECT_EQ(1, s.target_hits());
  19694. }
  19695. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  19696. ProxyAndTargetServers s;
  19697. Client cli("::1", s.target_port());
  19698. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  19699. cli.set_proxy("127.0.0.1", s.proxy_port());
  19700. cli.set_no_proxy({"[::1]"});
  19701. auto res = cli.Get("/");
  19702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19703. EXPECT_EQ(0, s.proxy_hits());
  19704. EXPECT_EQ(1, s.target_hits());
  19705. }
  19706. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  19707. ProxyAndTargetServers s;
  19708. Client cli("fe80::1", s.target_port());
  19709. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19710. cli.set_proxy("127.0.0.1", s.proxy_port());
  19711. cli.set_no_proxy({"[fe80::]/10"});
  19712. auto res = cli.Get("/");
  19713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19714. EXPECT_EQ(0, s.proxy_hits());
  19715. EXPECT_EQ(1, s.target_hits());
  19716. }
  19717. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  19718. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  19719. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  19720. // tricks via address-family conversion.
  19721. ProxyAndTargetServers s;
  19722. Client cli("::ffff:127.0.0.1", s.target_port());
  19723. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  19724. cli.set_proxy("127.0.0.1", s.proxy_port());
  19725. cli.set_no_proxy({"127.0.0.1"});
  19726. auto res = cli.Get("/");
  19727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19728. EXPECT_GE(s.proxy_hits(), 1);
  19729. EXPECT_EQ(0, s.target_hits());
  19730. }
  19731. TEST(NoProxyTest, IPv4CidrMatch) {
  19732. ProxyAndTargetServers s;
  19733. Client cli("127.0.0.1", s.target_port());
  19734. cli.set_proxy("127.0.0.1", s.proxy_port());
  19735. cli.set_no_proxy({"127.0.0.0/8"});
  19736. auto res = cli.Get("/");
  19737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19738. EXPECT_EQ(0, s.proxy_hits());
  19739. EXPECT_EQ(1, s.target_hits());
  19740. }
  19741. TEST(NoProxyTest, IPv4CidrNonMatch) {
  19742. ProxyAndTargetServers s;
  19743. Client cli("127.0.0.1", s.target_port());
  19744. cli.set_proxy("127.0.0.1", s.proxy_port());
  19745. cli.set_no_proxy({"10.0.0.0/8"});
  19746. auto res = cli.Get("/");
  19747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19748. EXPECT_GE(s.proxy_hits(), 1);
  19749. EXPECT_EQ(0, s.target_hits());
  19750. }
  19751. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  19752. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  19753. // IPv4 target matches.
  19754. ProxyAndTargetServers s;
  19755. Client cli("127.0.0.1", s.target_port());
  19756. cli.set_proxy("127.0.0.1", s.proxy_port());
  19757. cli.set_no_proxy({"0.0.0.0/0"});
  19758. auto res = cli.Get("/");
  19759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19760. EXPECT_EQ(0, s.proxy_hits());
  19761. EXPECT_EQ(1, s.target_hits());
  19762. }
  19763. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  19764. ProxyAndTargetServers s;
  19765. Client cli("127.0.0.1", s.target_port());
  19766. cli.set_proxy("127.0.0.1", s.proxy_port());
  19767. cli.set_no_proxy({"127.0.0.1"});
  19768. auto res = cli.Get("/");
  19769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19770. EXPECT_EQ(0, s.proxy_hits());
  19771. EXPECT_EQ(1, s.target_hits());
  19772. }
  19773. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  19774. ProxyAndTargetServers s;
  19775. Client cli("127.0.0.1", s.target_port());
  19776. cli.set_proxy("127.0.0.1", s.proxy_port());
  19777. cli.set_no_proxy({"127.0.0.0/33"});
  19778. auto res = cli.Get("/");
  19779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19780. EXPECT_GE(s.proxy_hits(), 1);
  19781. EXPECT_EQ(0, s.target_hits());
  19782. }
  19783. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  19784. // Empty prefix after the slash must be rejected, not silently treated as /32.
  19785. ProxyAndTargetServers s;
  19786. Client cli("127.0.0.1", s.target_port());
  19787. cli.set_proxy("127.0.0.1", s.proxy_port());
  19788. cli.set_no_proxy({"127.0.0.1/"});
  19789. auto res = cli.Get("/");
  19790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19791. EXPECT_GE(s.proxy_hits(), 1);
  19792. EXPECT_EQ(0, s.target_hits());
  19793. }
  19794. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  19795. ProxyAndTargetServers s;
  19796. auto cli = make_client("internal.corp", s);
  19797. cli->set_proxy_basic_auth("u", "p");
  19798. cli->set_no_proxy({"internal.corp"});
  19799. auto res = cli->Get("/");
  19800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19801. EXPECT_EQ(1, s.target_hits());
  19802. EXPECT_EQ(0, s.proxy_hits());
  19803. EXPECT_FALSE(s.last_had_proxy_authz())
  19804. << "Proxy-Authorization must not be sent direct to the target";
  19805. }
  19806. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  19807. ProxyAndTargetServers s;
  19808. auto cli = make_client("public.example", s);
  19809. cli->set_proxy_basic_auth("u", "p");
  19810. cli->set_no_proxy({"internal.corp"}); // does not match
  19811. auto res = cli->Get("/");
  19812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19813. EXPECT_GE(s.proxy_hits(), 1);
  19814. EXPECT_TRUE(s.last_had_proxy_authz());
  19815. }
  19816. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  19817. ProxyAndTargetServers s;
  19818. auto cli = make_client("anything.test", s);
  19819. auto res = cli->Get("/");
  19820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19821. EXPECT_GE(s.proxy_hits(), 1);
  19822. EXPECT_EQ(0, s.target_hits());
  19823. }
  19824. TEST(NoProxyTest, PortSpecificEntryRejected) {
  19825. ProxyAndTargetServers s;
  19826. auto cli = make_client("example.com", s);
  19827. cli->set_no_proxy({"example.com:8080"});
  19828. auto res = cli->Get("/");
  19829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19830. EXPECT_GE(s.proxy_hits(), 1);
  19831. EXPECT_EQ(0, s.target_hits());
  19832. }
  19833. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  19834. ProxyAndTargetServers s;
  19835. auto cli = make_client("anything.test", s);
  19836. cli->set_no_proxy({"", " ", "\t"});
  19837. auto res = cli->Get("/");
  19838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19839. EXPECT_GE(s.proxy_hits(), 1);
  19840. EXPECT_EQ(0, s.target_hits());
  19841. }
  19842. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  19843. // An entry with leading/trailing whitespace must still match — env-style
  19844. // values are commonly pasted with stray spaces and an implementation
  19845. // that feeds the raw token directly to inet_pton would fail to match
  19846. // valid CIDRs because of the spaces.
  19847. ProxyAndTargetServers s;
  19848. Client cli("127.0.0.1", s.target_port());
  19849. cli.set_proxy("127.0.0.1", s.proxy_port());
  19850. cli.set_no_proxy({" 127.0.0.0/8 "});
  19851. auto res = cli.Get("/");
  19852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19853. EXPECT_EQ(0, s.proxy_hits());
  19854. EXPECT_EQ(1, s.target_hits());
  19855. }
  19856. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  19857. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  19858. // go direct and must NOT carry Proxy-Authorization.
  19859. std::atomic<int> proxy_hits{0};
  19860. std::atomic<int> target_hits{0};
  19861. std::atomic<bool> target_saw_authz{false};
  19862. no_proxy_test::ScopedServer proxy_mock, target;
  19863. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19864. proxy_hits++;
  19865. res.status = 302;
  19866. res.set_header("Location", "http://127.0.0.1:" +
  19867. std::to_string(target.port()) + "/landed");
  19868. });
  19869. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19870. target_hits++;
  19871. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  19872. res.set_content("direct", "text/plain");
  19873. });
  19874. proxy_mock.listen();
  19875. target.listen();
  19876. Client cli("public.example", target.port());
  19877. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19878. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19879. cli.set_proxy_basic_auth("u", "p");
  19880. cli.set_no_proxy({"127.0.0.1"});
  19881. cli.set_follow_location(true);
  19882. auto res = cli.Get("/redir");
  19883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19884. EXPECT_GE(proxy_hits.load(), 1);
  19885. EXPECT_GE(target_hits.load(), 1);
  19886. EXPECT_FALSE(target_saw_authz.load());
  19887. }
  19888. #ifdef CPPHTTPLIB_SSL_ENABLED
  19889. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  19890. // Direct origin replying 407 must not trigger the digest retry; otherwise
  19891. // proxy creds would be sent to the (possibly hostile) origin.
  19892. std::atomic<int> target_hits{0};
  19893. std::atomic<bool> target_saw_proxy_authz{false};
  19894. no_proxy_test::ScopedServer target;
  19895. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19896. target_hits++;
  19897. if (req.has_header("Proxy-Authorization")) {
  19898. target_saw_proxy_authz = true;
  19899. }
  19900. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19901. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  19902. "nonce=\"abc\", algorithm=MD5");
  19903. });
  19904. target.listen();
  19905. // The proxy address is set to the target's port: the bypass MUST kick in;
  19906. // if it doesn't, the test still routes "via proxy" to the same server and
  19907. // the Proxy-Authorization assertion below catches the leak.
  19908. Client cli("evil.example", target.port());
  19909. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  19910. cli.set_proxy("127.0.0.1", target.port());
  19911. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19912. cli.set_no_proxy({"evil.example"});
  19913. auto res = cli.Get("/x");
  19914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19915. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19916. EXPECT_EQ(1, target_hits.load());
  19917. EXPECT_FALSE(target_saw_proxy_authz.load());
  19918. }
  19919. #endif
  19920. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  19921. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  19922. std::atomic<int> proxy_hits{0};
  19923. std::atomic<int> bypass_hits{0};
  19924. std::atomic<bool> proxy_saw_c_url{false};
  19925. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  19926. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  19927. proxy_hits++;
  19928. if (req.path.find("/start") != std::string::npos) {
  19929. res.status = 302;
  19930. res.set_header("Location", "http://127.0.0.1:" +
  19931. std::to_string(bypass_server.port()) +
  19932. "/middle");
  19933. return;
  19934. }
  19935. if (req.path.find("/end") != std::string::npos) {
  19936. proxy_saw_c_url = true;
  19937. res.set_content("c-via-proxy", "text/plain");
  19938. return;
  19939. }
  19940. res.set_content("unexpected", "text/plain");
  19941. });
  19942. // public.example's "advertised" port is arbitrary (the request never lands
  19943. // there — it goes through the proxy), but use a dynamic value to stay
  19944. // friendly with sharded parallel runs.
  19945. int public_port = bypass_server.port();
  19946. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  19947. bypass_hits++;
  19948. res.status = 302;
  19949. res.set_header("Location", "http://public.example:" +
  19950. std::to_string(public_port) + "/end");
  19951. });
  19952. proxy_mock.listen();
  19953. bypass_server.listen();
  19954. Client cli("public.example", public_port);
  19955. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19956. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19957. cli.set_no_proxy({"127.0.0.1"});
  19958. cli.set_follow_location(true);
  19959. auto res = cli.Get("/start");
  19960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19961. EXPECT_EQ(StatusCode::OK_200, res->status);
  19962. EXPECT_EQ("c-via-proxy", res->body);
  19963. EXPECT_GE(proxy_hits.load(), 2);
  19964. EXPECT_GE(bypass_hits.load(), 1);
  19965. EXPECT_TRUE(proxy_saw_c_url.load());
  19966. }
  19967. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  19968. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  19969. // request reconnects to the correct endpoint.
  19970. std::atomic<int> proxy_hits{0};
  19971. std::atomic<int> target_hits{0};
  19972. no_proxy_test::ScopedServer proxy_mock, target;
  19973. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19974. proxy_hits++;
  19975. res.set_content("via-proxy", "text/plain");
  19976. });
  19977. target.svr().Get(".*", [&](const Request &, Response &res) {
  19978. target_hits++;
  19979. res.set_content("direct", "text/plain");
  19980. });
  19981. proxy_mock.listen();
  19982. target.listen();
  19983. Client cli("public.example", target.port());
  19984. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19985. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19986. cli.set_keep_alive(true);
  19987. auto res1 = cli.Get("/a");
  19988. ASSERT_TRUE(res1);
  19989. EXPECT_EQ("via-proxy", res1->body);
  19990. EXPECT_EQ(1, proxy_hits.load());
  19991. EXPECT_EQ(0, target_hits.load());
  19992. cli.set_no_proxy({"public.example"});
  19993. auto res2 = cli.Get("/b");
  19994. ASSERT_TRUE(res2);
  19995. EXPECT_EQ("direct", res2->body);
  19996. EXPECT_EQ(1, proxy_hits.load());
  19997. EXPECT_EQ(1, target_hits.load());
  19998. }
  19999. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  20000. namespace proxy_tunnel_test {
  20001. // SSLServer counterpart to no_proxy_test::ScopedServer.
  20002. class ScopedSSLServer {
  20003. public:
  20004. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  20005. port_ = svr_.bind_to_any_port("127.0.0.1");
  20006. }
  20007. ~ScopedSSLServer() {
  20008. svr_.stop();
  20009. if (th_.joinable()) { th_.join(); }
  20010. }
  20011. SSLServer &svr() { return svr_; }
  20012. int port() const { return port_; }
  20013. void listen() {
  20014. th_ = std::thread([this] { svr_.listen_after_bind(); });
  20015. svr_.wait_until_ready();
  20016. }
  20017. private:
  20018. SSLServer svr_;
  20019. std::thread th_;
  20020. int port_ = 0;
  20021. };
  20022. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  20023. class ScopedConnectProxy {
  20024. public:
  20025. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  20026. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  20027. if (listen_fd_ < 0) { return; }
  20028. int yes = 1;
  20029. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  20030. sockaddr_in a{};
  20031. a.sin_family = AF_INET;
  20032. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20033. a.sin_port = 0;
  20034. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  20035. return;
  20036. }
  20037. socklen_t alen = sizeof(a);
  20038. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  20039. 0) {
  20040. return;
  20041. }
  20042. port_ = ntohs(a.sin_port);
  20043. if (::listen(listen_fd_, 1) != 0) { return; }
  20044. th_ = std::thread([this] { run(); });
  20045. }
  20046. ~ScopedConnectProxy() {
  20047. stop_ = true;
  20048. if (listen_fd_ >= 0) {
  20049. ::shutdown(listen_fd_, SHUT_RDWR);
  20050. ::close(listen_fd_);
  20051. }
  20052. if (th_.joinable()) { th_.join(); }
  20053. }
  20054. int port() const { return port_; }
  20055. int connect_hits() const { return connect_hits_.load(); }
  20056. private:
  20057. void run() {
  20058. while (!stop_.load()) {
  20059. fd_set rfds;
  20060. FD_ZERO(&rfds);
  20061. FD_SET(listen_fd_, &rfds);
  20062. timeval tv{0, 100 * 1000};
  20063. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  20064. if (sel <= 0) { continue; }
  20065. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  20066. if (client_fd < 0) { continue; }
  20067. std::string req;
  20068. char buf[2048];
  20069. while (req.find("\r\n\r\n") == std::string::npos) {
  20070. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  20071. if (n <= 0) { break; }
  20072. req.append(buf, static_cast<size_t>(n));
  20073. }
  20074. if (req.compare(0, 7, "CONNECT") != 0) {
  20075. ::close(client_fd);
  20076. continue;
  20077. }
  20078. connect_hits_++;
  20079. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  20080. ::send(client_fd, ok, std::strlen(ok), 0);
  20081. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  20082. sockaddr_in o{};
  20083. o.sin_family = AF_INET;
  20084. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20085. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  20086. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  20087. 0) {
  20088. ::close(client_fd);
  20089. ::close(origin_fd);
  20090. continue;
  20091. }
  20092. auto forward = [](int from, int to) {
  20093. char b[8192];
  20094. for (;;) {
  20095. ssize_t n = ::recv(from, b, sizeof(b), 0);
  20096. if (n <= 0) { break; }
  20097. ssize_t off = 0;
  20098. while (off < n) {
  20099. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  20100. if (s <= 0) {
  20101. off = n;
  20102. break;
  20103. }
  20104. off += s;
  20105. }
  20106. }
  20107. ::shutdown(to, SHUT_WR);
  20108. };
  20109. std::thread t1([&] { forward(client_fd, origin_fd); });
  20110. std::thread t2([&] { forward(origin_fd, client_fd); });
  20111. t1.join();
  20112. t2.join();
  20113. ::close(client_fd);
  20114. ::close(origin_fd);
  20115. }
  20116. }
  20117. int forward_port_ = -1;
  20118. int listen_fd_ = -1;
  20119. int port_ = 0;
  20120. std::thread th_;
  20121. std::atomic<bool> stop_{false};
  20122. std::atomic<int> connect_hits_{0};
  20123. };
  20124. } // namespace proxy_tunnel_test
  20125. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  20126. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  20127. // retry; otherwise proxy creds would be sent to the origin.
  20128. std::atomic<int> origin_hits{0};
  20129. std::atomic<bool> origin_saw_proxy_authz{false};
  20130. proxy_tunnel_test::ScopedSSLServer origin;
  20131. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  20132. origin_hits++;
  20133. if (req.has_header("Proxy-Authorization")) {
  20134. origin_saw_proxy_authz = true;
  20135. }
  20136. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20137. res.set_header("Proxy-Authenticate",
  20138. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  20139. "algorithm=MD5");
  20140. });
  20141. origin.listen();
  20142. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  20143. ASSERT_NE(0, proxy.port());
  20144. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  20145. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  20146. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  20147. // and answer with its own status, making this test flaky.
  20148. SSLClient cli("127.0.0.1", origin.port());
  20149. cli.enable_server_certificate_verification(false);
  20150. cli.set_proxy("127.0.0.1", proxy.port());
  20151. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20152. auto res = cli.Get("/x");
  20153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20154. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20155. EXPECT_EQ(1, origin_hits.load());
  20156. EXPECT_FALSE(origin_saw_proxy_authz.load());
  20157. EXPECT_EQ(1, proxy.connect_hits());
  20158. }
  20159. #endif