test.cc 748 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354
  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(GetHeaderValueTest, DefaultValue) {
  1267. Headers headers = {{"Dummy", "Dummy"}};
  1268. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1269. EXPECT_STREQ("text/plain", val);
  1270. }
  1271. TEST(GetHeaderValueTest, DefaultValueInt) {
  1272. Headers headers = {{"Dummy", "Dummy"}};
  1273. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1274. EXPECT_EQ(100ull, val);
  1275. }
  1276. TEST(GetHeaderValueTest, RegularValue) {
  1277. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1278. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1279. EXPECT_STREQ("text/html", val);
  1280. }
  1281. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1282. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1283. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1284. EXPECT_STREQ("text/html", val);
  1285. }
  1286. TEST(GetHeaderValueTest, SetContent) {
  1287. Response res;
  1288. res.set_content("html", "text/html");
  1289. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1290. res.set_content("text", "text/plain");
  1291. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1292. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1293. }
  1294. TEST(GetHeaderValueTest, RegularValueInt) {
  1295. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1296. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1297. EXPECT_EQ(100ull, val);
  1298. }
  1299. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1300. Headers headers = {{"Content-Length", "x"}};
  1301. auto is_invalid_value = false;
  1302. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1303. is_invalid_value);
  1304. EXPECT_EQ(0ull, val);
  1305. EXPECT_TRUE(is_invalid_value);
  1306. }
  1307. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1308. // An all-digit value that overflows size_t must be reported as invalid, not
  1309. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1310. // a large length to a small one on 32-bit builds, leaving the framing length
  1311. // wrong while is_invalid_value stayed false.
  1312. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1313. auto is_invalid_value = false;
  1314. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1315. is_invalid_value);
  1316. EXPECT_TRUE(is_invalid_value);
  1317. // A well-formed length is unaffected.
  1318. Headers ok = {{"Content-Length", "1234"}};
  1319. is_invalid_value = false;
  1320. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1321. is_invalid_value);
  1322. EXPECT_EQ(1234ull, val);
  1323. EXPECT_FALSE(is_invalid_value);
  1324. }
  1325. TEST(GetHeaderValueTest, Range) {
  1326. {
  1327. Headers headers = {make_range_header({{1, -1}})};
  1328. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1329. EXPECT_STREQ("bytes=1-", val);
  1330. }
  1331. {
  1332. Headers headers = {make_range_header({{-1, 1}})};
  1333. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1334. EXPECT_STREQ("bytes=-1", val);
  1335. }
  1336. {
  1337. Headers headers = {make_range_header({{1, 10}})};
  1338. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1339. EXPECT_STREQ("bytes=1-10", val);
  1340. }
  1341. {
  1342. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1343. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1344. EXPECT_STREQ("bytes=1-10, 100-", val);
  1345. }
  1346. {
  1347. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1348. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1349. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1350. }
  1351. {
  1352. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1353. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1354. EXPECT_STREQ("bytes=0-0, -1", val);
  1355. }
  1356. }
  1357. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1358. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1359. // to depend on the standard library (libstdc++ handed back duplicates in
  1360. // reverse insertion order, libc++ in insertion order).
  1361. Request req;
  1362. req.set_header("Accept-Encoding", "gzip");
  1363. req.set_header("Accept-Encoding", "deflate");
  1364. req.set_header("Accept-Encoding", "br");
  1365. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1366. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1367. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1368. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1369. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1370. }
  1371. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1372. Request req;
  1373. req.set_header("X-Test", "only");
  1374. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1375. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1376. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1377. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1378. }
  1379. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1380. Headers headers;
  1381. headers.emplace("Host", "example.com");
  1382. headers.emplace("Accept-Encoding", "gzip");
  1383. headers.emplace("User-Agent", "test");
  1384. headers.emplace("Accept-Encoding", "deflate");
  1385. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1386. "Accept-Encoding=deflate ",
  1387. entries_to_string(headers));
  1388. }
  1389. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1390. Headers headers = {{"Content-Type", "text/html"},
  1391. {"CONTENT-TYPE", "text/xml"}};
  1392. EXPECT_EQ(2U, headers.count("content-type"));
  1393. auto it = headers.find("content-type");
  1394. ASSERT_TRUE(it != headers.end());
  1395. EXPECT_EQ("text/html", it->second);
  1396. }
  1397. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1398. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1399. // drop only those fields and leave everything positioned between them.
  1400. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1401. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1402. auto rng = headers.equal_range("a");
  1403. headers.erase(rng.first, rng.second);
  1404. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1405. }
  1406. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1407. Headers headers = {
  1408. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1409. EXPECT_EQ(3U, headers.erase("A"));
  1410. EXPECT_EQ(0U, headers.count("A"));
  1411. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1412. }
  1413. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1414. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1415. headers.emplace_front("Host", "example.com");
  1416. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1417. entries_to_string(headers));
  1418. }
  1419. TEST(ParseHeaderValueTest, Range) {
  1420. {
  1421. Ranges ranges;
  1422. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1423. EXPECT_TRUE(ret);
  1424. EXPECT_EQ(1u, ranges.size());
  1425. EXPECT_EQ(1u, ranges[0].first);
  1426. EXPECT_EQ(-1, ranges[0].second);
  1427. }
  1428. {
  1429. Ranges ranges;
  1430. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1431. EXPECT_TRUE(ret);
  1432. EXPECT_EQ(1u, ranges.size());
  1433. EXPECT_EQ(-1, ranges[0].first);
  1434. EXPECT_EQ(1u, ranges[0].second);
  1435. }
  1436. {
  1437. Ranges ranges;
  1438. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1439. EXPECT_TRUE(ret);
  1440. EXPECT_EQ(1u, ranges.size());
  1441. EXPECT_EQ(1u, ranges[0].first);
  1442. EXPECT_EQ(10u, ranges[0].second);
  1443. }
  1444. {
  1445. Ranges ranges;
  1446. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1447. EXPECT_FALSE(ret);
  1448. }
  1449. {
  1450. Ranges ranges;
  1451. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1452. EXPECT_TRUE(ret);
  1453. EXPECT_EQ(2u, ranges.size());
  1454. EXPECT_EQ(1u, ranges[0].first);
  1455. EXPECT_EQ(10u, ranges[0].second);
  1456. EXPECT_EQ(100u, ranges[1].first);
  1457. EXPECT_EQ(-1, ranges[1].second);
  1458. }
  1459. {
  1460. Ranges ranges;
  1461. auto ret =
  1462. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1463. EXPECT_TRUE(ret);
  1464. EXPECT_EQ(3u, ranges.size());
  1465. EXPECT_EQ(1u, ranges[0].first);
  1466. EXPECT_EQ(10u, ranges[0].second);
  1467. EXPECT_EQ(100u, ranges[1].first);
  1468. EXPECT_EQ(200u, ranges[1].second);
  1469. EXPECT_EQ(300u, ranges[2].first);
  1470. EXPECT_EQ(400u, ranges[2].second);
  1471. }
  1472. {
  1473. Ranges ranges;
  1474. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1475. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1476. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1477. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1478. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1479. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1480. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1481. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1482. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1483. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1484. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1485. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1486. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1487. EXPECT_TRUE(ranges.empty());
  1488. }
  1489. }
  1490. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1491. Request req;
  1492. req.set_header("Accept-Encoding", "gzip");
  1493. Response res;
  1494. res.set_header("Content-Type", "text/plain");
  1495. auto ret = detail::encoding_type(req, res);
  1496. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1497. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1498. #else
  1499. EXPECT_TRUE(ret == detail::EncodingType::None);
  1500. #endif
  1501. }
  1502. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1503. Request req;
  1504. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1505. Response res;
  1506. res.set_header("Content-Type", "text/plain");
  1507. auto ret = detail::encoding_type(req, res);
  1508. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1509. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1510. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1511. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1512. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1513. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1514. #else
  1515. EXPECT_TRUE(ret == detail::EncodingType::None);
  1516. #endif
  1517. }
  1518. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1519. Request req;
  1520. req.set_header("Accept-Encoding",
  1521. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1522. Response res;
  1523. res.set_header("Content-Type", "text/plain");
  1524. auto ret = detail::encoding_type(req, res);
  1525. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1526. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1527. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1528. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1529. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1530. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1531. #else
  1532. EXPECT_TRUE(ret == detail::EncodingType::None);
  1533. #endif
  1534. }
  1535. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1536. // All supported encodings rejected with q=0 should return None
  1537. Request req;
  1538. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1539. Response res;
  1540. res.set_header("Content-Type", "text/plain");
  1541. auto ret = detail::encoding_type(req, res);
  1542. EXPECT_TRUE(ret == detail::EncodingType::None);
  1543. }
  1544. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1545. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1546. Request req;
  1547. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1548. Response res;
  1549. res.set_header("Content-Type", "text/plain");
  1550. auto ret = detail::encoding_type(req, res);
  1551. EXPECT_TRUE(ret == detail::EncodingType::None);
  1552. }
  1553. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1554. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1555. Request req;
  1556. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1557. Response res;
  1558. res.set_header("Content-Type", "text/plain");
  1559. auto ret = detail::encoding_type(req, res);
  1560. EXPECT_TRUE(ret == detail::EncodingType::None);
  1561. }
  1562. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1563. // RFC 7231: Accept-Encoding values are case-insensitive
  1564. Request req;
  1565. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1566. Response res;
  1567. res.set_header("Content-Type", "text/plain");
  1568. auto ret = detail::encoding_type(req, res);
  1569. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1570. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1571. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1572. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1573. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1574. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1575. #else
  1576. EXPECT_TRUE(ret == detail::EncodingType::None);
  1577. #endif
  1578. }
  1579. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1580. // q value should determine priority, not hardcoded order
  1581. Request req;
  1582. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1583. Response res;
  1584. res.set_header("Content-Type", "text/plain");
  1585. auto ret = detail::encoding_type(req, res);
  1586. // gzip has highest q=1.0, so it should be selected even though
  1587. // br and zstd are also supported
  1588. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1589. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1590. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1591. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1592. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1593. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1594. #else
  1595. EXPECT_TRUE(ret == detail::EncodingType::None);
  1596. #endif
  1597. }
  1598. TEST(BufferStreamTest, read) {
  1599. detail::BufferStream strm1;
  1600. Stream &strm = strm1;
  1601. EXPECT_EQ(5, strm.write("hello"));
  1602. char buf[512];
  1603. EXPECT_EQ(2, strm.read(buf, 2));
  1604. EXPECT_EQ('h', buf[0]);
  1605. EXPECT_EQ('e', buf[1]);
  1606. EXPECT_EQ(2, strm.read(buf, 2));
  1607. EXPECT_EQ('l', buf[0]);
  1608. EXPECT_EQ('l', buf[1]);
  1609. EXPECT_EQ(1, strm.read(buf, 1));
  1610. EXPECT_EQ('o', buf[0]);
  1611. EXPECT_EQ(0, strm.read(buf, 1));
  1612. }
  1613. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1614. auto host = "www.httpwatch.com";
  1615. auto ip = hosted_at(host);
  1616. EXPECT_EQ("23.96.13.243", ip);
  1617. std::vector<std::string> addrs;
  1618. hosted_at(host, addrs);
  1619. EXPECT_EQ(1u, addrs.size());
  1620. }
  1621. #if 0 // It depends on each test environment...
  1622. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1623. auto host = "www.youtube.com";
  1624. std::vector<std::string> addrs;
  1625. hosted_at(host, addrs);
  1626. EXPECT_EQ(20u, addrs.size());
  1627. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1628. EXPECT_TRUE(it != addrs.end());
  1629. }
  1630. #endif
  1631. class ChunkedEncodingTest : public ::testing::Test {
  1632. protected:
  1633. ChunkedEncodingTest()
  1634. : cli_(HOST, PORT)
  1635. #ifdef CPPHTTPLIB_SSL_ENABLED
  1636. ,
  1637. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1638. #endif
  1639. {
  1640. cli_.set_connection_timeout(2);
  1641. #ifdef CPPHTTPLIB_SSL_ENABLED
  1642. cli_.enable_server_certificate_verification(false);
  1643. #endif
  1644. }
  1645. virtual void SetUp() {
  1646. read_file("./image.jpg", image_data_);
  1647. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1648. res.set_content("Hello World!", "text/plain");
  1649. });
  1650. svr_.Get(
  1651. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1652. res.set_chunked_content_provider(
  1653. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1654. size_t remaining = image_data_.size() - offset;
  1655. if (remaining == 0) {
  1656. sink.done();
  1657. } else {
  1658. constexpr size_t CHUNK_SIZE = 1024;
  1659. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1660. sink.write(&image_data_[offset], send_size);
  1661. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1662. }
  1663. return true;
  1664. });
  1665. });
  1666. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1667. svr_.wait_until_ready();
  1668. }
  1669. virtual void TearDown() {
  1670. svr_.stop();
  1671. if (!request_threads_.empty()) {
  1672. std::this_thread::sleep_for(std::chrono::seconds(1));
  1673. for (auto &t : request_threads_) {
  1674. t.join();
  1675. }
  1676. }
  1677. t_.join();
  1678. }
  1679. #ifdef CPPHTTPLIB_SSL_ENABLED
  1680. SSLClient cli_;
  1681. SSLServer svr_;
  1682. #else
  1683. Client cli_;
  1684. Server svr_;
  1685. #endif
  1686. thread t_;
  1687. std::vector<thread> request_threads_;
  1688. std::string image_data_;
  1689. };
  1690. TEST_F(ChunkedEncodingTest, NormalGet) {
  1691. auto res = cli_.Get("/chunked");
  1692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1693. std::string out;
  1694. read_file("./image.jpg", out);
  1695. EXPECT_EQ(StatusCode::OK_200, res->status);
  1696. EXPECT_EQ(out, res->body);
  1697. }
  1698. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1699. std::string body;
  1700. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1701. body.append(data, data_length);
  1702. return true;
  1703. });
  1704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1705. std::string out;
  1706. read_file("./image.jpg", out);
  1707. EXPECT_EQ(StatusCode::OK_200, res->status);
  1708. EXPECT_EQ(out, body);
  1709. }
  1710. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1711. std::string body;
  1712. auto res = cli_.Get(
  1713. "/chunked",
  1714. [&](const Response &response) {
  1715. EXPECT_EQ(StatusCode::OK_200, response.status);
  1716. return true;
  1717. },
  1718. [&](const char *data, size_t data_length) {
  1719. body.append(data, data_length);
  1720. return true;
  1721. });
  1722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1723. std::string out;
  1724. read_file("./image.jpg", out);
  1725. EXPECT_EQ(StatusCode::OK_200, res->status);
  1726. EXPECT_EQ(out, body);
  1727. }
  1728. TEST(RangeTest, FromHTTPBin_Online) {
  1729. auto host = "httpbingo.org";
  1730. auto path = std::string{"/range/32"};
  1731. #ifdef CPPHTTPLIB_SSL_ENABLED
  1732. auto port = 443;
  1733. SSLClient cli(host, port);
  1734. #else
  1735. auto port = 80;
  1736. Client cli(host, port);
  1737. #endif
  1738. cli.set_connection_timeout(5);
  1739. {
  1740. auto res = cli.Get(path);
  1741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1742. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1743. EXPECT_EQ(StatusCode::OK_200, res->status);
  1744. }
  1745. {
  1746. Headers headers = {make_range_header({{1, -1}})};
  1747. auto res = cli.Get(path, headers);
  1748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1749. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1750. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1751. }
  1752. {
  1753. Headers headers = {make_range_header({{1, 10}})};
  1754. auto res = cli.Get(path, headers);
  1755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1756. EXPECT_EQ("bcdefghijk", res->body);
  1757. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1758. }
  1759. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1760. // entire resource, while the original httpbin returned 200. Both are
  1761. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1762. {
  1763. Headers headers = {make_range_header({{0, 31}})};
  1764. auto res = cli.Get(path, headers);
  1765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1766. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1767. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1768. res->status == StatusCode::PartialContent_206);
  1769. }
  1770. {
  1771. Headers headers = {make_range_header({{0, -1}})};
  1772. auto res = cli.Get(path, headers);
  1773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1774. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1775. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1776. res->status == StatusCode::PartialContent_206);
  1777. }
  1778. // go-httpbin returns 206 with clamped range for over-range requests,
  1779. // while the original httpbin returned 416. Both behaviors are observed
  1780. // in real servers, so we only verify the request succeeds.
  1781. {
  1782. Headers headers = {make_range_header({{0, 32}})};
  1783. auto res = cli.Get(path, headers);
  1784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1785. }
  1786. }
  1787. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1788. auto host = "unresolvableaddress.local";
  1789. auto path = std::string{"/"};
  1790. #ifdef CPPHTTPLIB_SSL_ENABLED
  1791. auto port = 443;
  1792. SSLClient cli(host, port);
  1793. #else
  1794. auto port = 80;
  1795. Client cli(host, port);
  1796. #endif
  1797. cli.set_connection_timeout(1);
  1798. {
  1799. auto res = cli.Get(path);
  1800. ASSERT_FALSE(res);
  1801. }
  1802. std::this_thread::sleep_for(std::chrono::seconds(8));
  1803. }
  1804. #if defined(__linux__) && defined(__GLIBC__) && \
  1805. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1806. // Forward declaration: in split builds split.py strips `inline` and moves the
  1807. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1808. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1809. // against the symbol in both header-only and split builds.
  1810. namespace httplib {
  1811. namespace detail {
  1812. int getaddrinfo_with_timeout(const char *node, const char *service,
  1813. const struct addrinfo *hints,
  1814. struct addrinfo **res, time_t timeout_sec);
  1815. } // namespace detail
  1816. } // namespace httplib
  1817. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1818. //
  1819. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1820. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1821. // gai_suspend() call hits the connection timeout the function calls
  1822. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1823. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1824. // still alive and still references the now-destroyed stack frame.
  1825. //
  1826. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1827. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1828. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1829. // and runs them in a container.
  1830. namespace {
  1831. bool should_run_issue_2431_tests() {
  1832. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1833. return v && *v && std::string(v) != "0";
  1834. }
  1835. std::string unique_unresolvable_host(int n) {
  1836. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1837. // glibc still asks the configured nameserver — which is exactly the path
  1838. // we want to exercise. A unique label per call avoids the resolver cache.
  1839. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1840. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1841. std::to_string(n) + ".invalid";
  1842. }
  1843. } // namespace
  1844. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1845. if (!should_run_issue_2431_tests()) {
  1846. GTEST_SKIP()
  1847. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1848. }
  1849. for (int i = 0; i < 8; ++i) {
  1850. struct addrinfo hints;
  1851. memset(&hints, 0, sizeof(hints));
  1852. hints.ai_family = AF_UNSPEC;
  1853. hints.ai_socktype = SOCK_STREAM;
  1854. auto host = unique_unresolvable_host(i);
  1855. struct addrinfo *result = nullptr;
  1856. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1857. &result, /*timeout_sec=*/1);
  1858. if (rc == 0 && result) { freeaddrinfo(result); }
  1859. }
  1860. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1861. // stack region they still believe holds their gaicb.
  1862. std::this_thread::sleep_for(std::chrono::seconds(3));
  1863. }
  1864. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1865. if (!should_run_issue_2431_tests()) {
  1866. GTEST_SKIP()
  1867. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1868. }
  1869. std::atomic<bool> stop{false};
  1870. std::vector<std::thread> threads;
  1871. for (int t = 0; t < 8; ++t) {
  1872. threads.emplace_back([t, &stop] {
  1873. int i = 0;
  1874. while (!stop.load(std::memory_order_relaxed)) {
  1875. struct addrinfo hints;
  1876. memset(&hints, 0, sizeof(hints));
  1877. hints.ai_family = AF_UNSPEC;
  1878. hints.ai_socktype = SOCK_STREAM;
  1879. auto host = unique_unresolvable_host(t * 100000 + i++);
  1880. struct addrinfo *result = nullptr;
  1881. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1882. &result, /*timeout_sec=*/1);
  1883. if (rc == 0 && result) { freeaddrinfo(result); }
  1884. }
  1885. });
  1886. }
  1887. std::this_thread::sleep_for(std::chrono::seconds(8));
  1888. stop.store(true, std::memory_order_relaxed);
  1889. for (auto &th : threads) {
  1890. th.join();
  1891. }
  1892. std::this_thread::sleep_for(std::chrono::seconds(3));
  1893. }
  1894. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1895. if (!should_run_issue_2431_tests()) {
  1896. GTEST_SKIP()
  1897. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1898. }
  1899. std::atomic<bool> stop{false};
  1900. std::vector<std::thread> threads;
  1901. for (int t = 0; t < 8; ++t) {
  1902. threads.emplace_back([t, &stop] {
  1903. int i = 0;
  1904. while (!stop.load(std::memory_order_relaxed)) {
  1905. auto host = unique_unresolvable_host(t * 100000 + i++);
  1906. Client cli(host, 80);
  1907. cli.set_connection_timeout(1, 0);
  1908. cli.set_read_timeout(1, 0);
  1909. cli.set_write_timeout(1, 0);
  1910. (void)cli.Get("/");
  1911. }
  1912. });
  1913. }
  1914. std::this_thread::sleep_for(std::chrono::seconds(8));
  1915. stop.store(true, std::memory_order_relaxed);
  1916. for (auto &th : threads) {
  1917. th.join();
  1918. }
  1919. std::this_thread::sleep_for(std::chrono::seconds(3));
  1920. }
  1921. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1922. TEST(ConnectionErrorTest, InvalidHost) {
  1923. auto host = "-abcde.com";
  1924. #ifdef CPPHTTPLIB_SSL_ENABLED
  1925. auto port = 443;
  1926. SSLClient cli(host, port);
  1927. #else
  1928. auto port = 80;
  1929. Client cli(host, port);
  1930. #endif
  1931. cli.set_connection_timeout(std::chrono::seconds(2));
  1932. auto res = cli.Get("/");
  1933. ASSERT_TRUE(!res);
  1934. EXPECT_EQ(Error::Connection, res.error());
  1935. }
  1936. TEST(ConnectionErrorTest, InvalidHost2) {
  1937. auto host = "httpcan.org/";
  1938. #ifdef CPPHTTPLIB_SSL_ENABLED
  1939. SSLClient cli(host);
  1940. #else
  1941. Client cli(host);
  1942. #endif
  1943. cli.set_connection_timeout(std::chrono::seconds(2));
  1944. auto res = cli.Get("/");
  1945. ASSERT_TRUE(!res);
  1946. EXPECT_EQ(Error::Connection, res.error());
  1947. }
  1948. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1949. auto host = "httpcan.org/";
  1950. #ifdef CPPHTTPLIB_SSL_ENABLED
  1951. SSLClient cli(host);
  1952. #else
  1953. Client cli(host);
  1954. #endif
  1955. cli.set_connection_timeout(std::chrono::seconds(2));
  1956. auto res = cli.Get("/");
  1957. ASSERT_TRUE(!res);
  1958. stringstream s;
  1959. s << "error code: " << res.error();
  1960. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1961. }
  1962. TEST(ConnectionErrorTest, InvalidPort) {
  1963. auto host = "localhost";
  1964. auto port = 44380;
  1965. #ifdef CPPHTTPLIB_SSL_ENABLED
  1966. SSLClient cli(host, port);
  1967. #else
  1968. Client cli(host, port);
  1969. #endif
  1970. cli.set_connection_timeout(std::chrono::seconds(2));
  1971. auto res = cli.Get("/");
  1972. ASSERT_TRUE(!res);
  1973. EXPECT_TRUE(Error::Connection == res.error() ||
  1974. Error::ConnectionTimeout == res.error());
  1975. }
  1976. TEST(ConnectionErrorTest, Timeout_Online) {
  1977. auto host = "google.com";
  1978. #ifdef CPPHTTPLIB_SSL_ENABLED
  1979. auto port = 44380;
  1980. SSLClient cli(host, port);
  1981. #else
  1982. auto port = 8080;
  1983. Client cli(host, port);
  1984. #endif
  1985. cli.set_connection_timeout(std::chrono::seconds(2));
  1986. // only probe one address type so that the error reason
  1987. // correlates to the timed-out IPv4, not the unsupported
  1988. // IPv6 connection attempt
  1989. cli.set_address_family(AF_INET);
  1990. auto res = cli.Get("/");
  1991. ASSERT_TRUE(!res);
  1992. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1993. }
  1994. TEST(CancelTest, NoCancel_Online) {
  1995. auto host = "httpbingo.org";
  1996. auto path = std::string{"/range/32"};
  1997. #ifdef CPPHTTPLIB_SSL_ENABLED
  1998. auto port = 443;
  1999. SSLClient cli(host, port);
  2000. #else
  2001. auto port = 80;
  2002. Client cli(host, port);
  2003. #endif
  2004. cli.set_connection_timeout(std::chrono::seconds(5));
  2005. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2007. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2008. EXPECT_EQ(StatusCode::OK_200, res->status);
  2009. }
  2010. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2011. // Use /bytes with a large payload so that the DownloadProgress callback
  2012. // (which only fires for Content-Length responses) is invoked before the
  2013. // entire body is received, giving cancellation a chance to fire.
  2014. auto host = "httpbingo.org";
  2015. auto path = std::string{"/bytes/524288"};
  2016. #ifdef CPPHTTPLIB_SSL_ENABLED
  2017. auto port = 443;
  2018. SSLClient cli(host, port);
  2019. #else
  2020. auto port = 80;
  2021. Client cli(host, port);
  2022. #endif
  2023. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2024. cli.set_connection_timeout(std::chrono::seconds(5));
  2025. ASSERT_TRUE(!res);
  2026. EXPECT_EQ(Error::Canceled, res.error());
  2027. }
  2028. TEST(CancelTest, WithCancelLargePayload_Online) {
  2029. auto host = "httpbingo.org";
  2030. auto path = std::string{"/bytes/524288"};
  2031. #ifdef CPPHTTPLIB_SSL_ENABLED
  2032. auto port = 443;
  2033. SSLClient cli(host, port);
  2034. #else
  2035. auto port = 80;
  2036. Client cli(host, port);
  2037. #endif
  2038. cli.set_connection_timeout(std::chrono::seconds(5));
  2039. uint32_t count = 0;
  2040. auto res =
  2041. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2042. ASSERT_TRUE(!res);
  2043. EXPECT_EQ(Error::Canceled, res.error());
  2044. }
  2045. TEST(CancelTest, NoCancelPost) {
  2046. Server svr;
  2047. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2048. res.set_content("Hello World!", "text/plain");
  2049. });
  2050. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2051. auto se = detail::scope_exit([&] {
  2052. svr.stop();
  2053. thread.join();
  2054. ASSERT_FALSE(svr.is_running());
  2055. });
  2056. svr.wait_until_ready();
  2057. Client cli(HOST, PORT);
  2058. cli.set_connection_timeout(std::chrono::seconds(5));
  2059. auto res =
  2060. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2061. "application/json", [](uint64_t, uint64_t) { return true; });
  2062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2063. EXPECT_EQ("Hello World!", res->body);
  2064. EXPECT_EQ(StatusCode::OK_200, res->status);
  2065. }
  2066. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2067. Server svr;
  2068. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2069. res.set_content("Hello World!", "text/plain");
  2070. });
  2071. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2072. auto se = detail::scope_exit([&] {
  2073. svr.stop();
  2074. thread.join();
  2075. ASSERT_FALSE(svr.is_running());
  2076. });
  2077. svr.wait_until_ready();
  2078. Client cli(HOST, PORT);
  2079. cli.set_connection_timeout(std::chrono::seconds(5));
  2080. auto res =
  2081. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2082. "application/json", [](uint64_t, uint64_t) { return false; });
  2083. ASSERT_TRUE(!res);
  2084. EXPECT_EQ(Error::Canceled, res.error());
  2085. }
  2086. TEST(CancelTest, WithCancelLargePayloadPost) {
  2087. Server svr;
  2088. svr.set_payload_max_length(200 * 1024 * 1024);
  2089. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2090. res.set_content(LARGE_DATA, "text/plain");
  2091. });
  2092. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2093. auto se = detail::scope_exit([&] {
  2094. svr.stop();
  2095. thread.join();
  2096. ASSERT_FALSE(svr.is_running());
  2097. });
  2098. svr.wait_until_ready();
  2099. Client cli(HOST, PORT);
  2100. cli.set_payload_max_length(200 * 1024 * 1024);
  2101. cli.set_connection_timeout(std::chrono::seconds(5));
  2102. auto res =
  2103. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2104. "application/json", [](uint64_t, uint64_t) { return false; });
  2105. ASSERT_TRUE(!res);
  2106. EXPECT_EQ(Error::Canceled, res.error());
  2107. }
  2108. TEST(CancelTest, NoCancelPut) {
  2109. Server svr;
  2110. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2111. res.set_content("Hello World!", "text/plain");
  2112. });
  2113. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2114. auto se = detail::scope_exit([&] {
  2115. svr.stop();
  2116. thread.join();
  2117. ASSERT_FALSE(svr.is_running());
  2118. });
  2119. svr.wait_until_ready();
  2120. Client cli(HOST, PORT);
  2121. cli.set_connection_timeout(std::chrono::seconds(5));
  2122. auto res =
  2123. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2124. "application/json", [](uint64_t, uint64_t) { return true; });
  2125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2126. EXPECT_EQ("Hello World!", res->body);
  2127. EXPECT_EQ(StatusCode::OK_200, res->status);
  2128. }
  2129. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2130. Server svr;
  2131. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2132. res.set_content("Hello World!", "text/plain");
  2133. });
  2134. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2135. auto se = detail::scope_exit([&] {
  2136. svr.stop();
  2137. thread.join();
  2138. ASSERT_FALSE(svr.is_running());
  2139. });
  2140. svr.wait_until_ready();
  2141. Client cli(HOST, PORT);
  2142. cli.set_connection_timeout(std::chrono::seconds(5));
  2143. auto res =
  2144. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2145. "application/json", [](uint64_t, uint64_t) { return false; });
  2146. ASSERT_TRUE(!res);
  2147. EXPECT_EQ(Error::Canceled, res.error());
  2148. }
  2149. TEST(CancelTest, WithCancelLargePayloadPut) {
  2150. Server svr;
  2151. svr.set_payload_max_length(200 * 1024 * 1024);
  2152. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2153. res.set_content(LARGE_DATA, "text/plain");
  2154. });
  2155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2156. auto se = detail::scope_exit([&] {
  2157. svr.stop();
  2158. thread.join();
  2159. ASSERT_FALSE(svr.is_running());
  2160. });
  2161. svr.wait_until_ready();
  2162. Client cli(HOST, PORT);
  2163. cli.set_payload_max_length(200 * 1024 * 1024);
  2164. cli.set_connection_timeout(std::chrono::seconds(5));
  2165. auto res =
  2166. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2167. "application/json", [](uint64_t, uint64_t) { return false; });
  2168. ASSERT_TRUE(!res);
  2169. EXPECT_EQ(Error::Canceled, res.error());
  2170. }
  2171. TEST(CancelTest, NoCancelPatch) {
  2172. Server svr;
  2173. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2174. res.set_content("Hello World!", "text/plain");
  2175. });
  2176. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2177. auto se = detail::scope_exit([&] {
  2178. svr.stop();
  2179. thread.join();
  2180. ASSERT_FALSE(svr.is_running());
  2181. });
  2182. svr.wait_until_ready();
  2183. Client cli(HOST, PORT);
  2184. cli.set_connection_timeout(std::chrono::seconds(5));
  2185. auto res =
  2186. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2187. "application/json", [](uint64_t, uint64_t) { return true; });
  2188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2189. EXPECT_EQ("Hello World!", res->body);
  2190. EXPECT_EQ(StatusCode::OK_200, res->status);
  2191. }
  2192. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2193. Server svr;
  2194. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2195. res.set_content("Hello World!", "text/plain");
  2196. });
  2197. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2198. auto se = detail::scope_exit([&] {
  2199. svr.stop();
  2200. thread.join();
  2201. ASSERT_FALSE(svr.is_running());
  2202. });
  2203. svr.wait_until_ready();
  2204. Client cli(HOST, PORT);
  2205. cli.set_connection_timeout(std::chrono::seconds(5));
  2206. auto res =
  2207. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2208. "application/json", [](uint64_t, uint64_t) { return false; });
  2209. ASSERT_TRUE(!res);
  2210. EXPECT_EQ(Error::Canceled, res.error());
  2211. }
  2212. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2213. Server svr;
  2214. svr.set_payload_max_length(200 * 1024 * 1024);
  2215. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2216. res.set_content(LARGE_DATA, "text/plain");
  2217. });
  2218. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2219. auto se = detail::scope_exit([&] {
  2220. svr.stop();
  2221. thread.join();
  2222. ASSERT_FALSE(svr.is_running());
  2223. });
  2224. svr.wait_until_ready();
  2225. Client cli(HOST, PORT);
  2226. cli.set_payload_max_length(200 * 1024 * 1024);
  2227. cli.set_connection_timeout(std::chrono::seconds(5));
  2228. auto res =
  2229. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2230. "application/json", [](uint64_t, uint64_t) { return false; });
  2231. ASSERT_TRUE(!res);
  2232. EXPECT_EQ(Error::Canceled, res.error());
  2233. }
  2234. TEST(CancelTest, NoCancelDelete) {
  2235. Server svr;
  2236. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2237. res.set_content("Hello World!", "text/plain");
  2238. });
  2239. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2240. auto se = detail::scope_exit([&] {
  2241. svr.stop();
  2242. thread.join();
  2243. ASSERT_FALSE(svr.is_running());
  2244. });
  2245. svr.wait_until_ready();
  2246. Client cli(HOST, PORT);
  2247. cli.set_connection_timeout(std::chrono::seconds(5));
  2248. auto res =
  2249. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2250. "application/json", [](uint64_t, uint64_t) { return true; });
  2251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2252. EXPECT_EQ("Hello World!", res->body);
  2253. EXPECT_EQ(StatusCode::OK_200, res->status);
  2254. }
  2255. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2256. Server svr;
  2257. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2258. res.set_content("Hello World!", "text/plain");
  2259. });
  2260. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2261. auto se = detail::scope_exit([&] {
  2262. svr.stop();
  2263. thread.join();
  2264. ASSERT_FALSE(svr.is_running());
  2265. });
  2266. svr.wait_until_ready();
  2267. Client cli(HOST, PORT);
  2268. cli.set_connection_timeout(std::chrono::seconds(5));
  2269. auto res =
  2270. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2271. "application/json", [](uint64_t, uint64_t) { return false; });
  2272. ASSERT_TRUE(!res);
  2273. EXPECT_EQ(Error::Canceled, res.error());
  2274. }
  2275. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2276. Server svr;
  2277. svr.set_payload_max_length(200 * 1024 * 1024);
  2278. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2279. res.set_content(LARGE_DATA, "text/plain");
  2280. });
  2281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2282. auto se = detail::scope_exit([&] {
  2283. svr.stop();
  2284. thread.join();
  2285. ASSERT_FALSE(svr.is_running());
  2286. });
  2287. svr.wait_until_ready();
  2288. Client cli(HOST, PORT);
  2289. cli.set_payload_max_length(200 * 1024 * 1024);
  2290. cli.set_connection_timeout(std::chrono::seconds(5));
  2291. auto res =
  2292. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2293. "application/json", [](uint64_t, uint64_t) { return false; });
  2294. ASSERT_TRUE(!res);
  2295. EXPECT_EQ(Error::Canceled, res.error());
  2296. }
  2297. static std::string remove_whitespace(const std::string &input) {
  2298. std::string output;
  2299. output.reserve(input.size());
  2300. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2301. [](unsigned char c) { return !std::isspace(c); });
  2302. return output;
  2303. }
  2304. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2305. auto host = "httpbingo.org";
  2306. auto path = std::string{"/basic-auth/hello/world"};
  2307. #ifdef CPPHTTPLIB_SSL_ENABLED
  2308. auto port = 443;
  2309. SSLClient cli(host, port);
  2310. #else
  2311. auto port = 80;
  2312. Client cli(host, port);
  2313. #endif
  2314. {
  2315. auto res = cli.Get(path);
  2316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2317. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2318. }
  2319. {
  2320. auto res = cli.Get(
  2321. path, Headers{make_basic_authentication_header("hello", "world")});
  2322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2323. auto body = remove_whitespace(res->body);
  2324. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2325. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2326. EXPECT_EQ(StatusCode::OK_200, res->status);
  2327. }
  2328. {
  2329. cli.set_basic_auth("hello", "world");
  2330. auto res = cli.Get(path);
  2331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2332. auto body = remove_whitespace(res->body);
  2333. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2334. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2335. EXPECT_EQ(StatusCode::OK_200, res->status);
  2336. }
  2337. {
  2338. cli.set_basic_auth("hello", "bad");
  2339. auto res = cli.Get(path);
  2340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2341. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2342. }
  2343. {
  2344. cli.set_basic_auth("bad", "world");
  2345. auto res = cli.Get(path);
  2346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2347. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2348. }
  2349. }
  2350. #ifdef CPPHTTPLIB_SSL_ENABLED
  2351. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2352. auto host = "httpbingo.org";
  2353. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2354. auto paths = std::vector<std::string>{
  2355. "/digest-auth/auth/hello/world/MD5",
  2356. "/digest-auth/auth/hello/world/SHA-256",
  2357. };
  2358. auto port = 443;
  2359. SSLClient cli(host, port);
  2360. {
  2361. auto res = cli.Get(unauth_path);
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2364. }
  2365. {
  2366. cli.set_digest_auth("hello", "world");
  2367. for (const auto &path : paths) {
  2368. auto res = cli.Get(path.c_str());
  2369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2370. auto body = remove_whitespace(res->body);
  2371. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2372. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2373. EXPECT_EQ(StatusCode::OK_200, res->status);
  2374. }
  2375. cli.set_digest_auth("hello", "bad");
  2376. for (const auto &path : paths) {
  2377. auto res = cli.Get(path.c_str());
  2378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2379. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2380. }
  2381. }
  2382. }
  2383. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2384. // comma-separated list of challenges, and each challenge may itself carry a
  2385. // comma-separated auth-param list, so a server can legally offer Basic
  2386. // before Digest, either as two field lines or packed into one. Runs one 401
  2387. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2388. // value() joins them in receipt order) and checks that the retry carries a
  2389. // well-formed Digest Authorization header naming expected_realm.
  2390. static void
  2391. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2392. const std::string &expected_realm) {
  2393. std::atomic<int> hits{0};
  2394. Server svr;
  2395. svr.Get("/x", [&](const Request &req, Response &res) {
  2396. if (++hits == 1) {
  2397. res.status = StatusCode::Unauthorized_401;
  2398. for (const auto &challenge : challenges) {
  2399. res.set_header("WWW-Authenticate", challenge);
  2400. }
  2401. } else {
  2402. auto authorization = req.get_header_value("Authorization");
  2403. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2404. EXPECT_NE(std::string::npos,
  2405. authorization.find("realm=\"" + expected_realm + "\""));
  2406. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2407. res.set_content("ok", "text/plain");
  2408. }
  2409. });
  2410. auto port = svr.bind_to_any_port(HOST);
  2411. std::thread t([&]() { svr.listen_after_bind(); });
  2412. auto se = detail::scope_exit([&] {
  2413. svr.stop();
  2414. t.join();
  2415. });
  2416. svr.wait_until_ready();
  2417. Client cli(HOST, port);
  2418. cli.set_digest_auth("hello", "world");
  2419. auto res = cli.Get("/x");
  2420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2421. EXPECT_EQ(2, hits.load());
  2422. }
  2423. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2424. static const char *kDigestChallenge =
  2425. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2426. "algorithm=MD5";
  2427. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2428. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2429. "testrealm");
  2430. }
  2431. // Same challenge list with the schemes in the opposite order, to make sure
  2432. // the fix above didn't just special-case "Basic first".
  2433. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2434. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2435. "testrealm");
  2436. }
  2437. // A comma inside a quoted auth-param value must not be mistaken for the
  2438. // separator between two challenges (or two auth-params).
  2439. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2440. run_digest_challenge_list_test(
  2441. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2442. "algorithm=MD5"},
  2443. "test,realm");
  2444. }
  2445. #endif
  2446. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2447. auto host = "google.com";
  2448. auto another_host = "example.com";
  2449. auto wrong_ip = "0.0.0.0";
  2450. #ifdef CPPHTTPLIB_SSL_ENABLED
  2451. SSLClient cli(host);
  2452. #else
  2453. Client cli(host);
  2454. #endif
  2455. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2456. auto res = cli.Get("/");
  2457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2458. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2459. }
  2460. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2461. auto host = "google.com";
  2462. auto wrong_ip = "0.0.0.0";
  2463. #ifdef CPPHTTPLIB_SSL_ENABLED
  2464. SSLClient cli(host);
  2465. #else
  2466. Client cli(host);
  2467. #endif
  2468. cli.set_hostname_addr_map({{host, wrong_ip}});
  2469. auto res = cli.Get("/");
  2470. ASSERT_TRUE(!res);
  2471. EXPECT_EQ(Error::Connection, res.error());
  2472. }
  2473. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2474. // A mapped value that is not an IP literal must be resolved. "localhost"
  2475. // resolves from the hosts file, so this test needs no external DNS.
  2476. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2477. auto host = "target.invalid";
  2478. Server svr;
  2479. std::string received_host;
  2480. svr.Get("/hi", [&](const Request &req, Response &res) {
  2481. received_host = req.get_header_value("Host");
  2482. res.set_content("Hello World!", "text/plain");
  2483. });
  2484. auto port = svr.bind_to_any_port(HOST);
  2485. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2486. auto se = detail::scope_exit([&] {
  2487. svr.stop();
  2488. thread.join();
  2489. ASSERT_FALSE(svr.is_running());
  2490. });
  2491. svr.wait_until_ready();
  2492. Client cli(host, port);
  2493. cli.set_hostname_addr_map({{host, HOST}});
  2494. auto res = cli.Get("/hi");
  2495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2496. EXPECT_EQ(StatusCode::OK_200, res->status);
  2497. // The mapping only redirects the connection; the identity stays host_.
  2498. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2499. }
  2500. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2501. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2502. auto host = "target.invalid";
  2503. Server svr;
  2504. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2505. res.set_content("Hello World!", "text/plain");
  2506. });
  2507. auto port = svr.bind_to_any_port("127.0.0.1");
  2508. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2509. auto se = detail::scope_exit([&] {
  2510. svr.stop();
  2511. thread.join();
  2512. ASSERT_FALSE(svr.is_running());
  2513. });
  2514. svr.wait_until_ready();
  2515. Client cli(host, port);
  2516. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2517. auto res = cli.Get("/hi");
  2518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2519. EXPECT_EQ(StatusCode::OK_200, res->status);
  2520. }
  2521. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2522. // An empty mapped value must leave host_ as the connection target. Without
  2523. // that guard the empty value would become the host argument, getaddrinfo
  2524. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2525. // loopback - silently connecting somewhere the caller never asked for.
  2526. // The server listens on loopback, so such a fallback would succeed and is
  2527. // therefore observable as a failure of this test.
  2528. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2529. Server svr;
  2530. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2531. res.set_content("Hello World!", "text/plain");
  2532. });
  2533. auto port = svr.bind_to_any_port(HOST);
  2534. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2535. auto se = detail::scope_exit([&] {
  2536. svr.stop();
  2537. thread.join();
  2538. ASSERT_FALSE(svr.is_running());
  2539. });
  2540. svr.wait_until_ready();
  2541. Client cli(blackhole, port);
  2542. cli.set_hostname_addr_map({{blackhole, ""}});
  2543. cli.set_connection_timeout(1);
  2544. auto res = cli.Get("/hi");
  2545. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2546. }
  2547. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2548. auto host = "httpbingo.org";
  2549. auto path = std::string{"/absolute-redirect/3"};
  2550. #ifdef CPPHTTPLIB_SSL_ENABLED
  2551. SSLClient cli(host);
  2552. #else
  2553. Client cli(host);
  2554. #endif
  2555. cli.set_follow_location(true);
  2556. auto res = cli.Get(path);
  2557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2558. EXPECT_EQ(StatusCode::OK_200, res->status);
  2559. }
  2560. TEST(RedirectTest, Redirect_Online) {
  2561. auto host = "httpbingo.org";
  2562. auto path = std::string{"/redirect/3"};
  2563. #ifdef CPPHTTPLIB_SSL_ENABLED
  2564. SSLClient cli(host);
  2565. #else
  2566. Client cli(host);
  2567. #endif
  2568. cli.set_follow_location(true);
  2569. auto res = cli.Get(path);
  2570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2571. EXPECT_EQ(StatusCode::OK_200, res->status);
  2572. }
  2573. TEST(RelativeRedirectTest, Redirect_Online) {
  2574. auto host = "httpbingo.org";
  2575. auto path = std::string{"/relative-redirect/3"};
  2576. #ifdef CPPHTTPLIB_SSL_ENABLED
  2577. SSLClient cli(host);
  2578. #else
  2579. Client cli(host);
  2580. #endif
  2581. cli.set_follow_location(true);
  2582. auto res = cli.Get(path);
  2583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2584. EXPECT_EQ(StatusCode::OK_200, res->status);
  2585. }
  2586. TEST(TooManyRedirectTest, Redirect_Online) {
  2587. auto host = "httpbingo.org";
  2588. auto path = std::string{"/redirect/21"};
  2589. #ifdef CPPHTTPLIB_SSL_ENABLED
  2590. SSLClient cli(host);
  2591. #else
  2592. Client cli(host);
  2593. #endif
  2594. cli.set_follow_location(true);
  2595. auto res = cli.Get(path);
  2596. ASSERT_TRUE(!res);
  2597. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2598. }
  2599. #ifdef CPPHTTPLIB_SSL_ENABLED
  2600. TEST(YahooRedirectTest, Redirect_Online) {
  2601. Client cli("yahoo.com");
  2602. auto res = cli.Get("/");
  2603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2604. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2605. cli.set_follow_location(true);
  2606. res = cli.Get("/");
  2607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2608. EXPECT_EQ(StatusCode::OK_200, res->status);
  2609. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2610. }
  2611. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2612. #define REDIR_HOST "httpbingo.org"
  2613. #define REDIR_PATH "/redirect-to"
  2614. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2615. SSLClient cli(REDIR_HOST);
  2616. cli.set_follow_location(true);
  2617. auto res =
  2618. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2620. EXPECT_EQ(StatusCode::OK_200, res->status);
  2621. }
  2622. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2623. SSLClient cli(REDIR_HOST);
  2624. cli.set_follow_location(true);
  2625. Params params;
  2626. params.emplace("url", "http://example.com");
  2627. params.emplace("status_code", "302");
  2628. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2630. EXPECT_EQ(StatusCode::OK_200, res->status);
  2631. }
  2632. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2633. SSLClient cli(REDIR_HOST);
  2634. cli.set_follow_location(true);
  2635. Params params;
  2636. params.emplace("url", "http://example.com");
  2637. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2639. EXPECT_EQ(StatusCode::OK_200, res->status);
  2640. }
  2641. TEST(UrlWithSpace, Redirect_Online) {
  2642. SSLClient cli("edge.forgecdn.net");
  2643. cli.set_follow_location(true);
  2644. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2646. EXPECT_EQ(StatusCode::OK_200, res->status);
  2647. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2648. }
  2649. #endif
  2650. #if !defined(_WIN32) && !defined(_WIN64)
  2651. TEST(ReceiveSignals, Signal) {
  2652. auto setupSignalHandlers = []() {
  2653. struct sigaction act;
  2654. sigemptyset(&act.sa_mask);
  2655. act.sa_flags = SA_SIGINFO;
  2656. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2657. switch (sig) {
  2658. case SIGINT:
  2659. default: break;
  2660. }
  2661. };
  2662. ::sigaction(SIGINT, &act, nullptr);
  2663. };
  2664. Server svr;
  2665. int port = 0;
  2666. auto thread = std::thread([&]() {
  2667. setupSignalHandlers();
  2668. port = svr.bind_to_any_port(HOST);
  2669. svr.listen_after_bind();
  2670. });
  2671. auto se = detail::scope_exit([&] {
  2672. svr.stop();
  2673. thread.join();
  2674. ASSERT_FALSE(svr.is_running());
  2675. });
  2676. svr.wait_until_ready();
  2677. ASSERT_TRUE(svr.is_running());
  2678. pthread_kill(thread.native_handle(), SIGINT);
  2679. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2680. ASSERT_TRUE(svr.is_running());
  2681. }
  2682. #endif
  2683. TEST(RedirectToDifferentPort, Redirect) {
  2684. Server svr1;
  2685. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2686. res.set_content("Hello World!", "text/plain");
  2687. });
  2688. int svr1_port = 0;
  2689. auto thread1 = std::thread([&]() {
  2690. svr1_port = svr1.bind_to_any_port(HOST);
  2691. svr1.listen_after_bind();
  2692. });
  2693. Server svr2;
  2694. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2695. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2696. });
  2697. int svr2_port = 0;
  2698. auto thread2 = std::thread([&]() {
  2699. svr2_port = svr2.bind_to_any_port(HOST);
  2700. svr2.listen_after_bind();
  2701. });
  2702. auto se = detail::scope_exit([&] {
  2703. svr2.stop();
  2704. thread2.join();
  2705. svr1.stop();
  2706. thread1.join();
  2707. ASSERT_FALSE(svr2.is_running());
  2708. ASSERT_FALSE(svr1.is_running());
  2709. });
  2710. svr1.wait_until_ready();
  2711. svr2.wait_until_ready();
  2712. Client cli("localhost", svr2_port);
  2713. cli.set_follow_location(true);
  2714. auto res = cli.Get("/2");
  2715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2716. EXPECT_EQ(StatusCode::OK_200, res->status);
  2717. EXPECT_EQ("Hello World!", res->body);
  2718. }
  2719. static void
  2720. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2721. Server svr1;
  2722. std::string captured_authorization;
  2723. svr1.Get("/target", [&](const Request &req, Response &res) {
  2724. captured_authorization = req.get_header_value("Authorization");
  2725. res.set_content("OK", "text/plain");
  2726. });
  2727. int svr1_port = 0;
  2728. auto thread1 = std::thread([&]() {
  2729. svr1_port = svr1.bind_to_any_port(HOST);
  2730. svr1.listen_after_bind();
  2731. });
  2732. Server svr2;
  2733. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2734. res.set_redirect(
  2735. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2736. });
  2737. int svr2_port = 0;
  2738. auto thread2 = std::thread([&]() {
  2739. svr2_port = svr2.bind_to_any_port(HOST);
  2740. svr2.listen_after_bind();
  2741. });
  2742. auto se = detail::scope_exit([&] {
  2743. svr2.stop();
  2744. thread2.join();
  2745. svr1.stop();
  2746. thread1.join();
  2747. ASSERT_FALSE(svr2.is_running());
  2748. ASSERT_FALSE(svr1.is_running());
  2749. });
  2750. svr1.wait_until_ready();
  2751. svr2.wait_until_ready();
  2752. Client cli("localhost", svr2_port);
  2753. cli.set_follow_location(true);
  2754. set_auth(cli);
  2755. auto res = cli.Get("/redir");
  2756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2757. EXPECT_EQ(StatusCode::OK_200, res->status);
  2758. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2759. EXPECT_TRUE(captured_authorization.empty());
  2760. }
  2761. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2762. TestDoNotForwardCredentialsOnRedirect(
  2763. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2764. }
  2765. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2766. TestDoNotForwardCredentialsOnRedirect(
  2767. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2768. }
  2769. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2770. Server svr1;
  2771. std::string captured_cookie;
  2772. bool target_hit = false;
  2773. svr1.Get("/target", [&](const Request &req, Response &res) {
  2774. captured_cookie = req.get_header_value("Cookie");
  2775. target_hit = true;
  2776. res.set_content("OK", "text/plain");
  2777. });
  2778. int svr1_port = 0;
  2779. auto thread1 = std::thread([&]() {
  2780. svr1_port = svr1.bind_to_any_port(HOST);
  2781. svr1.listen_after_bind();
  2782. });
  2783. Server svr2;
  2784. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2785. res.set_redirect(
  2786. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2787. });
  2788. int svr2_port = 0;
  2789. auto thread2 = std::thread([&]() {
  2790. svr2_port = svr2.bind_to_any_port(HOST);
  2791. svr2.listen_after_bind();
  2792. });
  2793. auto se = detail::scope_exit([&] {
  2794. svr2.stop();
  2795. thread2.join();
  2796. svr1.stop();
  2797. thread1.join();
  2798. ASSERT_FALSE(svr2.is_running());
  2799. ASSERT_FALSE(svr1.is_running());
  2800. });
  2801. svr1.wait_until_ready();
  2802. svr2.wait_until_ready();
  2803. Client cli("localhost", svr2_port);
  2804. cli.set_follow_location(true);
  2805. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2806. auto res = cli.Get("/redir", headers);
  2807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2808. EXPECT_EQ(StatusCode::OK_200, res->status);
  2809. EXPECT_TRUE(target_hit);
  2810. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2811. EXPECT_TRUE(captured_cookie.empty());
  2812. }
  2813. TEST(RedirectToSamePort, ForwardCookie) {
  2814. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2815. // header so that ordinary session flows keep working.
  2816. Server svr;
  2817. std::string captured_cookie;
  2818. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2819. res.set_redirect("/target", 302);
  2820. });
  2821. svr.Get("/target", [&](const Request &req, Response &res) {
  2822. captured_cookie = req.get_header_value("Cookie");
  2823. res.set_content("OK", "text/plain");
  2824. });
  2825. auto port = svr.bind_to_any_port(HOST);
  2826. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2827. auto se = detail::scope_exit([&] {
  2828. svr.stop();
  2829. thread.join();
  2830. ASSERT_FALSE(svr.is_running());
  2831. });
  2832. svr.wait_until_ready();
  2833. Client cli(HOST, port);
  2834. cli.set_follow_location(true);
  2835. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2836. auto res = cli.Get("/redir", headers);
  2837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2838. EXPECT_EQ(StatusCode::OK_200, res->status);
  2839. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2840. }
  2841. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2842. Server svr;
  2843. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2844. // Port number that overflows int — should not crash
  2845. res.set_redirect("http://localhost:99999999999999999999/target");
  2846. });
  2847. auto port = svr.bind_to_any_port(HOST);
  2848. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2849. auto se = detail::scope_exit([&] {
  2850. svr.stop();
  2851. thread.join();
  2852. ASSERT_FALSE(svr.is_running());
  2853. });
  2854. svr.wait_until_ready();
  2855. Client cli(HOST, port);
  2856. cli.set_follow_location(true);
  2857. auto res = cli.Get("/redir");
  2858. // Should fail gracefully, not crash (no valid response due to bad port)
  2859. EXPECT_FALSE(res);
  2860. }
  2861. TEST(RedirectFromPageWithContent, Redirect) {
  2862. Server svr;
  2863. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2864. res.set_content("___", "text/plain");
  2865. res.set_redirect("/2");
  2866. });
  2867. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2868. res.set_content("Hello World!", "text/plain");
  2869. });
  2870. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2871. auto se = detail::scope_exit([&] {
  2872. svr.stop();
  2873. th.join();
  2874. ASSERT_FALSE(svr.is_running());
  2875. });
  2876. svr.wait_until_ready();
  2877. {
  2878. Client cli("localhost", PORT);
  2879. cli.set_follow_location(true);
  2880. std::string body;
  2881. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2882. body.append(data, data_length);
  2883. return true;
  2884. });
  2885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2886. EXPECT_EQ(StatusCode::OK_200, res->status);
  2887. EXPECT_EQ("Hello World!", body);
  2888. }
  2889. {
  2890. Client cli("localhost", PORT);
  2891. std::string body;
  2892. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2893. body.append(data, data_length);
  2894. return true;
  2895. });
  2896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2897. EXPECT_EQ(StatusCode::Found_302, res->status);
  2898. EXPECT_EQ("___", body);
  2899. }
  2900. }
  2901. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2902. Server svr;
  2903. auto port_str = std::to_string(PORT);
  2904. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2905. auto expected_host = "[::1]:" + port_str;
  2906. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2907. res.set_content("___", "text/plain");
  2908. // res.set_redirect("/2");
  2909. res.set_redirect(redirect_url);
  2910. });
  2911. svr.Get("/2", [&](const Request &req, Response &res) {
  2912. auto host_header = req.headers.find("Host");
  2913. ASSERT_TRUE(host_header != req.headers.end());
  2914. EXPECT_EQ(expected_host, host_header->second);
  2915. res.set_content("Hello World!", "text/plain");
  2916. });
  2917. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2918. auto se = detail::scope_exit([&] {
  2919. svr.stop();
  2920. th.join();
  2921. ASSERT_FALSE(svr.is_running());
  2922. });
  2923. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2924. // actually starts anything, so the condition !svr.is_running() will
  2925. // always remain true, and the loop never stops.
  2926. // This basically counts how many milliseconds have passed since the
  2927. // call to svr.listen(), and if after 5 seconds nothing started yet
  2928. // aborts the test.
  2929. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2930. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2931. ASSERT_LT(milliseconds, 5000U);
  2932. }
  2933. {
  2934. Client cli("::1", PORT);
  2935. cli.set_follow_location(true);
  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::OK_200, res->status);
  2943. EXPECT_EQ("Hello World!", body);
  2944. }
  2945. {
  2946. Client cli("::1", PORT);
  2947. std::string body;
  2948. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2949. body.append(data, data_length);
  2950. return true;
  2951. });
  2952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2953. EXPECT_EQ(StatusCode::Found_302, res->status);
  2954. EXPECT_EQ("___", body);
  2955. }
  2956. }
  2957. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2958. Server svr;
  2959. svr.Get("/foo", [](const Request &req, Response &res) {
  2960. auto a = req.params.find("a");
  2961. if (a != req.params.end()) {
  2962. res.set_content((*a).second, "text/plain");
  2963. res.status = StatusCode::OK_200;
  2964. } else {
  2965. res.status = StatusCode::BadRequest_400;
  2966. }
  2967. });
  2968. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2969. auto se = detail::scope_exit([&] {
  2970. svr.stop();
  2971. thread.join();
  2972. ASSERT_FALSE(svr.is_running());
  2973. });
  2974. svr.wait_until_ready();
  2975. {
  2976. Client cli(HOST, PORT);
  2977. cli.set_path_encode(false);
  2978. auto res = cli.Get("/foo?a=explicitly+encoded");
  2979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2980. EXPECT_EQ(StatusCode::OK_200, res->status);
  2981. // This expects it back with a space, as the `+` won't have been
  2982. // url-encoded, and server-side the params get decoded turning `+`
  2983. // into spaces.
  2984. EXPECT_EQ("explicitly encoded", res->body);
  2985. }
  2986. }
  2987. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2988. // When path encoding is disabled the client must transmit the supplied
  2989. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2990. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2991. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2992. // than a space (0x20). Assert on the raw wire target to catch this.
  2993. Server svr;
  2994. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2995. svr.Get("/foo", [&](const Request &req, Response &res) {
  2996. EXPECT_EQ(expected_target, req.target);
  2997. res.status = StatusCode::OK_200;
  2998. });
  2999. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3000. auto se = detail::scope_exit([&] {
  3001. svr.stop();
  3002. thread.join();
  3003. ASSERT_FALSE(svr.is_running());
  3004. });
  3005. svr.wait_until_ready();
  3006. {
  3007. Client cli(HOST, PORT);
  3008. cli.set_path_encode(false);
  3009. auto res = cli.Get(expected_target.c_str());
  3010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3011. EXPECT_EQ(StatusCode::OK_200, res->status);
  3012. }
  3013. }
  3014. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3015. // `open_stream()` used to skip the path encoding that the buffered send
  3016. // path applies, so the same `path` produced different bytes in the request
  3017. // line depending on which API was used. Assert the two agree.
  3018. Server svr;
  3019. std::string target;
  3020. svr.Get(".*", [&](const Request &req, Response &res) {
  3021. target = req.target;
  3022. res.status = StatusCode::OK_200;
  3023. });
  3024. auto port = svr.bind_to_any_port(HOST);
  3025. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3026. auto se = detail::scope_exit([&] {
  3027. svr.stop();
  3028. thread.join();
  3029. ASSERT_FALSE(svr.is_running());
  3030. });
  3031. svr.wait_until_ready();
  3032. struct {
  3033. const char *path;
  3034. const char *expected;
  3035. } cases[] = {
  3036. {"/a b?x=1", "/a%20b?x=1"},
  3037. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3038. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3039. };
  3040. for (const auto &c : cases) {
  3041. Client cli(HOST, port);
  3042. target.clear();
  3043. auto res = cli.Get(c.path);
  3044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3045. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3046. auto buffered_target = target;
  3047. target.clear();
  3048. auto handle = cli.open_stream("GET", c.path);
  3049. EXPECT_TRUE(handle.is_valid())
  3050. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3051. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3052. }
  3053. }
  3054. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3055. // The `set_path_encode(false)` contract — transmit the supplied target
  3056. // verbatim — must hold for the streaming API too.
  3057. Server svr;
  3058. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3059. std::string target;
  3060. svr.Get("/foo", [&](const Request &req, Response &res) {
  3061. target = req.target;
  3062. res.status = StatusCode::OK_200;
  3063. });
  3064. auto port = svr.bind_to_any_port(HOST);
  3065. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3066. auto se = detail::scope_exit([&] {
  3067. svr.stop();
  3068. thread.join();
  3069. ASSERT_FALSE(svr.is_running());
  3070. });
  3071. svr.wait_until_ready();
  3072. {
  3073. Client cli(HOST, port);
  3074. cli.set_path_encode(false);
  3075. auto handle = cli.open_stream("GET", expected_target);
  3076. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3077. EXPECT_EQ(expected_target, target);
  3078. }
  3079. }
  3080. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3081. // With path encoding enabled a CR/LF in the target is percent-encoded
  3082. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3083. // write_request_line still backstops `set_path_encode(false)`, which is
  3084. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3085. Server svr;
  3086. // Captured before routing: the decoded path contains a newline, which a
  3087. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3088. std::string target;
  3089. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3090. target = req.target;
  3091. res.status = StatusCode::OK_200;
  3092. return Server::HandlerResponse::Handled;
  3093. });
  3094. auto port = svr.bind_to_any_port(HOST);
  3095. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3096. auto se = detail::scope_exit([&] {
  3097. svr.stop();
  3098. thread.join();
  3099. ASSERT_FALSE(svr.is_running());
  3100. });
  3101. svr.wait_until_ready();
  3102. {
  3103. Client cli(HOST, port);
  3104. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3105. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3106. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3107. }
  3108. }
  3109. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3110. // Nothing may reach the wire: a raw CR/LF target would split the request
  3111. // line and inject headers.
  3112. Server svr;
  3113. // Pre-routing so that "not called" means nothing reached the server at all,
  3114. // rather than merely failing to match a handler pattern.
  3115. auto handler_called = false;
  3116. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3117. handler_called = true;
  3118. res.status = StatusCode::OK_200;
  3119. return Server::HandlerResponse::Handled;
  3120. });
  3121. auto port = svr.bind_to_any_port(HOST);
  3122. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3123. auto se = detail::scope_exit([&] {
  3124. svr.stop();
  3125. thread.join();
  3126. ASSERT_FALSE(svr.is_running());
  3127. });
  3128. svr.wait_until_ready();
  3129. {
  3130. Client cli(HOST, port);
  3131. cli.set_path_encode(false);
  3132. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3133. EXPECT_FALSE(handle.is_valid());
  3134. EXPECT_EQ(Error::Write, handle.error);
  3135. EXPECT_FALSE(handler_called);
  3136. }
  3137. }
  3138. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3139. // Which of the two branches runs is decided by whether the query component
  3140. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3141. // an empty query and must still fall back to building one from
  3142. // `req.params`, while a non-empty query must win over `req.params`.
  3143. Server svr;
  3144. std::string target;
  3145. svr.Get("/foo", [&](const Request &req, Response &res) {
  3146. target = req.target;
  3147. res.status = StatusCode::OK_200;
  3148. });
  3149. auto port = svr.bind_to_any_port(HOST);
  3150. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3151. auto se = detail::scope_exit([&] {
  3152. svr.stop();
  3153. thread.join();
  3154. ASSERT_FALSE(svr.is_running());
  3155. });
  3156. svr.wait_until_ready();
  3157. {
  3158. // Trailing `?` -> empty query component -> `req.params` is used.
  3159. Client cli(HOST, port);
  3160. Request req;
  3161. req.method = "GET";
  3162. req.path = "/foo?";
  3163. req.params.emplace("a", "1");
  3164. target.clear();
  3165. auto res = cli.send(req);
  3166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3167. EXPECT_EQ("/foo?a=1", target);
  3168. }
  3169. {
  3170. // Non-empty query in `req.path` -> `req.params` is not appended.
  3171. Client cli(HOST, port);
  3172. Request req;
  3173. req.method = "GET";
  3174. req.path = "/foo?b=2";
  3175. req.params.emplace("a", "1");
  3176. target.clear();
  3177. auto res = cli.send(req);
  3178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3179. EXPECT_EQ("/foo?b=2", target);
  3180. }
  3181. }
  3182. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3183. Server svr;
  3184. svr.Get("/", [](const Request &req, Response &) {
  3185. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3186. });
  3187. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3188. auto se = detail::scope_exit([&] {
  3189. svr.stop();
  3190. thread.join();
  3191. ASSERT_FALSE(svr.is_running());
  3192. });
  3193. svr.wait_until_ready();
  3194. {
  3195. Client cli(HOST, PORT);
  3196. cli.set_path_encode(false);
  3197. auto res = cli.Get("/?something=%0A");
  3198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3199. EXPECT_EQ(StatusCode::OK_200, res->status);
  3200. }
  3201. }
  3202. TEST(BindServerTest, BindDualStack) {
  3203. Server svr;
  3204. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3205. res.set_content("Hello World!", "text/plain");
  3206. });
  3207. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3208. auto se = detail::scope_exit([&] {
  3209. svr.stop();
  3210. thread.join();
  3211. ASSERT_FALSE(svr.is_running());
  3212. });
  3213. svr.wait_until_ready();
  3214. {
  3215. Client cli("127.0.0.1", PORT);
  3216. auto res = cli.Get("/1");
  3217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3218. EXPECT_EQ(StatusCode::OK_200, res->status);
  3219. EXPECT_EQ("Hello World!", res->body);
  3220. }
  3221. {
  3222. Client cli("::1", PORT);
  3223. auto res = cli.Get("/1");
  3224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3225. EXPECT_EQ(StatusCode::OK_200, res->status);
  3226. EXPECT_EQ("Hello World!", res->body);
  3227. }
  3228. }
  3229. TEST(BindServerTest, BindAndListenSeparately) {
  3230. Server svr;
  3231. int port = svr.bind_to_any_port("0.0.0.0");
  3232. ASSERT_TRUE(svr.is_valid());
  3233. ASSERT_TRUE(port > 0);
  3234. svr.stop();
  3235. }
  3236. // Reports whether anything is still listening on a loopback port. A plain
  3237. // connect() is used instead of a Client request because a socket left bound by
  3238. // mistake accepts the connection into its backlog and never answers, which
  3239. // would hang the test instead of failing it.
  3240. static bool is_loopback_port_accepting(int port) {
  3241. sockaddr_in addr{};
  3242. addr.sin_family = AF_INET;
  3243. addr.sin_port = htons(static_cast<uint16_t>(port));
  3244. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3245. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3246. EXPECT_NE(sock, INVALID_SOCKET);
  3247. if (sock == INVALID_SOCKET) { return false; }
  3248. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3249. static_cast<socklen_t>(sizeof(addr)));
  3250. detail::close_socket(sock);
  3251. return ret == 0;
  3252. }
  3253. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3254. Server svr;
  3255. auto port = svr.bind_to_any_port("127.0.0.1");
  3256. ASSERT_TRUE(port > 0);
  3257. svr.stop();
  3258. // bind_to_any_port() already called listen(2), so until stop() closed the
  3259. // descriptor the port kept accepting connections into the backlog. ASSERT
  3260. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3261. // below blocks forever in the accept loop.
  3262. ASSERT_FALSE(is_loopback_port_accepting(port));
  3263. // Nothing is left to accept on, so listen_after_bind() must report failure
  3264. // instead of returning success without ever serving.
  3265. EXPECT_FALSE(svr.listen_after_bind());
  3266. // The failed listen marks the server decommissioned, so a waiter returns
  3267. // instead of spinning forever.
  3268. svr.wait_until_ready();
  3269. }
  3270. #ifdef CPPHTTPLIB_SSL_ENABLED
  3271. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3272. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3273. CLIENT_CA_CERT_DIR);
  3274. int port = svr.bind_to_any_port("0.0.0.0");
  3275. ASSERT_TRUE(svr.is_valid());
  3276. ASSERT_TRUE(port > 0);
  3277. svr.stop();
  3278. }
  3279. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3280. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3281. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3282. int port = svr.bind_to_any_port("0.0.0.0");
  3283. ASSERT_TRUE(svr.is_valid());
  3284. ASSERT_TRUE(port > 0);
  3285. svr.stop();
  3286. }
  3287. TEST(BindServerTest, UpdateCertsPem) {
  3288. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3289. int port = svr.bind_to_any_port("0.0.0.0");
  3290. ASSERT_TRUE(svr.is_valid());
  3291. ASSERT_TRUE(port > 0);
  3292. // Read PEM files
  3293. std::string cert_pem, key_pem, ca_pem;
  3294. read_file(SERVER_CERT_FILE, cert_pem);
  3295. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3296. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3297. // Update server certificates using PEM API
  3298. ASSERT_TRUE(
  3299. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3300. ASSERT_TRUE(svr.is_valid());
  3301. svr.stop();
  3302. }
  3303. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3304. // Start server with client CA (enables client auth)
  3305. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3306. ASSERT_TRUE(svr.is_valid());
  3307. bool handler_called = false;
  3308. svr.Get("/test", [&](const Request &req, Response &res) {
  3309. handler_called = true;
  3310. // Verify client certificate is present
  3311. auto cert = req.peer_cert();
  3312. EXPECT_TRUE(static_cast<bool>(cert));
  3313. res.set_content("ok", "text/plain");
  3314. });
  3315. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3316. auto se = detail::scope_exit([&] {
  3317. svr.stop();
  3318. t.join();
  3319. ASSERT_FALSE(svr.is_running());
  3320. });
  3321. svr.wait_until_ready();
  3322. // Read PEM files
  3323. std::string cert_pem, key_pem, ca_pem;
  3324. read_file(SERVER_CERT_FILE, cert_pem);
  3325. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3326. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3327. // Update server certificates and client CA using PEM API while server running
  3328. ASSERT_TRUE(
  3329. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3330. // Connect with client certificate
  3331. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3332. cli.enable_server_certificate_verification(false);
  3333. cli.set_connection_timeout(30);
  3334. auto res = cli.Get("/test");
  3335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3336. ASSERT_EQ(StatusCode::OK_200, res->status);
  3337. ASSERT_TRUE(handler_called);
  3338. EXPECT_EQ("ok", res->body);
  3339. }
  3340. #endif
  3341. TEST(ErrorHandlerTest, ContentLength) {
  3342. Server svr;
  3343. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3344. res.status = StatusCode::OK_200;
  3345. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3346. "text/html"); // <= Content-Length still 13
  3347. });
  3348. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3349. res.set_content("Hello World!\n", "text/plain");
  3350. res.status = 524;
  3351. });
  3352. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3353. auto se = detail::scope_exit([&] {
  3354. svr.stop();
  3355. thread.join();
  3356. ASSERT_FALSE(svr.is_running());
  3357. });
  3358. svr.wait_until_ready();
  3359. {
  3360. Client cli(HOST, PORT);
  3361. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3363. EXPECT_EQ(StatusCode::OK_200, res->status);
  3364. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3365. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3366. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3367. }
  3368. }
  3369. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3370. TEST(ExceptionTest, WithoutExceptionHandler) {
  3371. Server svr;
  3372. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3373. throw std::runtime_error("exception...");
  3374. });
  3375. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3376. throw std::runtime_error("exception\r\n...");
  3377. });
  3378. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3379. auto se = detail::scope_exit([&] {
  3380. svr.stop();
  3381. listen_thread.join();
  3382. ASSERT_FALSE(svr.is_running());
  3383. });
  3384. svr.wait_until_ready();
  3385. Client cli("localhost", PORT);
  3386. {
  3387. auto res = cli.Get("/exception");
  3388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3389. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3390. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3391. }
  3392. {
  3393. auto res = cli.Get("/unknown");
  3394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3395. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3396. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3397. }
  3398. }
  3399. TEST(ExceptionTest, WithExceptionHandler) {
  3400. Server svr;
  3401. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3402. std::exception_ptr ep) {
  3403. EXPECT_FALSE(ep == nullptr);
  3404. try {
  3405. std::rethrow_exception(ep);
  3406. } catch (std::exception &e) {
  3407. EXPECT_EQ("abc", std::string(e.what()));
  3408. } catch (...) {}
  3409. res.status = StatusCode::InternalServerError_500;
  3410. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3411. "text/html"); // <= Content-Length still 13 at this point
  3412. });
  3413. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3414. res.set_content("Hello World!\n", "text/plain");
  3415. throw std::runtime_error("abc");
  3416. });
  3417. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3418. auto se = detail::scope_exit([&] {
  3419. svr.stop();
  3420. thread.join();
  3421. ASSERT_FALSE(svr.is_running());
  3422. });
  3423. svr.wait_until_ready();
  3424. for (size_t i = 0; i < 10; i++) {
  3425. Client cli(HOST, PORT);
  3426. for (size_t j = 0; j < 100; j++) {
  3427. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3429. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3430. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3431. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3432. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3433. }
  3434. cli.set_keep_alive(true);
  3435. for (size_t j = 0; j < 100; j++) {
  3436. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3438. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3439. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3440. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3441. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3442. }
  3443. }
  3444. }
  3445. TEST(ExceptionTest, AndErrorHandler) {
  3446. Server svr;
  3447. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3448. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3449. });
  3450. svr.set_exception_handler(
  3451. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3452. EXPECT_FALSE(ep == nullptr);
  3453. try {
  3454. std::rethrow_exception(ep);
  3455. } catch (std::exception &e) {
  3456. res.set_content(e.what(), "text/html");
  3457. } catch (...) {}
  3458. res.status = StatusCode::InternalServerError_500;
  3459. });
  3460. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3461. throw std::runtime_error("EXCEPTION");
  3462. });
  3463. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3464. res.set_content("ERROR", "text/html");
  3465. res.status = StatusCode::InternalServerError_500;
  3466. });
  3467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3468. auto se = detail::scope_exit([&] {
  3469. svr.stop();
  3470. thread.join();
  3471. ASSERT_FALSE(svr.is_running());
  3472. });
  3473. svr.wait_until_ready();
  3474. Client cli(HOST, PORT);
  3475. {
  3476. auto res = cli.Get("/exception");
  3477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3478. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3479. EXPECT_EQ("EXCEPTION", res->body);
  3480. }
  3481. {
  3482. auto res = cli.Get("/error");
  3483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3484. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3485. EXPECT_EQ("ERROR", res->body);
  3486. }
  3487. {
  3488. auto res = cli.Get("/invalid");
  3489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3490. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3491. EXPECT_EQ("NOT_FOUND", res->body);
  3492. }
  3493. }
  3494. #endif
  3495. TEST(NoContentTest, ContentLength) {
  3496. Server svr;
  3497. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3498. res.status = StatusCode::NoContent_204;
  3499. });
  3500. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3501. auto se = detail::scope_exit([&] {
  3502. svr.stop();
  3503. thread.join();
  3504. ASSERT_FALSE(svr.is_running());
  3505. });
  3506. svr.wait_until_ready();
  3507. {
  3508. Client cli(HOST, PORT);
  3509. auto res = cli.Get("/hi");
  3510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3511. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3512. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3513. }
  3514. }
  3515. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3516. #ifdef CPPHTTPLIB_SSL_ENABLED
  3517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3518. ASSERT_TRUE(svr.is_valid());
  3519. #else
  3520. Server svr;
  3521. #endif
  3522. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3523. if (req.path == "/routing_handler") {
  3524. res.set_header("PRE_ROUTING", "on");
  3525. res.set_content("Routing Handler", "text/plain");
  3526. return httplib::Server::HandlerResponse::Handled;
  3527. }
  3528. return httplib::Server::HandlerResponse::Unhandled;
  3529. });
  3530. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3531. res.set_content("Error", "text/html");
  3532. });
  3533. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3534. if (req.path == "/routing_handler") {
  3535. res.set_header("POST_ROUTING", "on");
  3536. }
  3537. });
  3538. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3539. res.set_content("Hello World!\n", "text/plain");
  3540. });
  3541. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3542. auto se = detail::scope_exit([&] {
  3543. svr.stop();
  3544. thread.join();
  3545. ASSERT_FALSE(svr.is_running());
  3546. });
  3547. svr.wait_until_ready();
  3548. {
  3549. #ifdef CPPHTTPLIB_SSL_ENABLED
  3550. SSLClient cli(HOST, PORT);
  3551. cli.enable_server_certificate_verification(false);
  3552. #else
  3553. Client cli(HOST, PORT);
  3554. #endif
  3555. auto res = cli.Get("/routing_handler");
  3556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3557. EXPECT_EQ(StatusCode::OK_200, res->status);
  3558. EXPECT_EQ("Routing Handler", res->body);
  3559. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3560. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3561. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3562. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3563. }
  3564. {
  3565. #ifdef CPPHTTPLIB_SSL_ENABLED
  3566. SSLClient cli(HOST, PORT);
  3567. cli.enable_server_certificate_verification(false);
  3568. #else
  3569. Client cli(HOST, PORT);
  3570. #endif
  3571. auto res = cli.Get("/hi");
  3572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3573. EXPECT_EQ(StatusCode::OK_200, res->status);
  3574. EXPECT_EQ("Hello World!\n", res->body);
  3575. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3576. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3577. }
  3578. {
  3579. #ifdef CPPHTTPLIB_SSL_ENABLED
  3580. SSLClient cli(HOST, PORT);
  3581. cli.enable_server_certificate_verification(false);
  3582. #else
  3583. Client cli(HOST, PORT);
  3584. #endif
  3585. auto res = cli.Get("/aaa");
  3586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3588. EXPECT_EQ("Error", res->body);
  3589. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3590. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3591. }
  3592. }
  3593. TEST(RequestHandlerTest, PreRequestHandler) {
  3594. auto route_path = "/user/:user";
  3595. Server svr;
  3596. svr.Get("/hi", [](const Request &, Response &res) {
  3597. res.set_content("hi", "text/plain");
  3598. });
  3599. svr.Get(route_path, [](const Request &req, Response &res) {
  3600. res.set_content(req.path_params.at("user"), "text/plain");
  3601. });
  3602. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3603. if (req.matched_route == route_path) {
  3604. auto user = req.path_params.at("user");
  3605. if (user != "john") {
  3606. res.status = StatusCode::Forbidden_403;
  3607. res.set_content("error", "text/html");
  3608. return Server::HandlerResponse::Handled;
  3609. }
  3610. }
  3611. return Server::HandlerResponse::Unhandled;
  3612. });
  3613. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3614. auto se = detail::scope_exit([&] {
  3615. svr.stop();
  3616. thread.join();
  3617. ASSERT_FALSE(svr.is_running());
  3618. });
  3619. svr.wait_until_ready();
  3620. Client cli(HOST, PORT);
  3621. {
  3622. auto res = cli.Get("/hi");
  3623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3624. EXPECT_EQ(StatusCode::OK_200, res->status);
  3625. EXPECT_EQ("hi", res->body);
  3626. }
  3627. {
  3628. auto res = cli.Get("/user/john");
  3629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3630. EXPECT_EQ(StatusCode::OK_200, res->status);
  3631. EXPECT_EQ("john", res->body);
  3632. }
  3633. {
  3634. auto res = cli.Get("/user/invalid-user");
  3635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3636. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3637. EXPECT_EQ("error", res->body);
  3638. }
  3639. }
  3640. // The pre-request handler must run before the request body is read, so a
  3641. // rejected request never forces the server to buffer a (potentially large)
  3642. // body. Here the posted body is larger than the payload limit: if the body
  3643. // were read first the server would answer 413, but because the pre-request
  3644. // handler runs first it answers 403 and the body is never read.
  3645. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3646. Server svr;
  3647. svr.set_payload_max_length(8);
  3648. auto handler_ran = false;
  3649. svr.Post("/reject", [&](const Request &req, Response &res) {
  3650. handler_ran = true;
  3651. res.set_content(req.body, "text/plain");
  3652. });
  3653. svr.Post("/accept", [](const Request &req, Response &res) {
  3654. res.set_content(req.body, "text/plain");
  3655. });
  3656. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3657. if (req.matched_route == "/reject") {
  3658. res.status = StatusCode::Forbidden_403;
  3659. res.set_content("denied", "text/plain");
  3660. return Server::HandlerResponse::Handled;
  3661. }
  3662. return Server::HandlerResponse::Unhandled;
  3663. });
  3664. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3665. auto se = detail::scope_exit([&] {
  3666. svr.stop();
  3667. thread.join();
  3668. ASSERT_FALSE(svr.is_running());
  3669. });
  3670. svr.wait_until_ready();
  3671. Client cli(HOST, PORT);
  3672. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3673. // rejects with 403 before the body is read, so 413 is never reached.
  3674. {
  3675. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3677. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3678. EXPECT_EQ("denied", res->body);
  3679. EXPECT_FALSE(handler_ran);
  3680. }
  3681. // An approved route still reads the body and enforces the payload limit.
  3682. {
  3683. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3685. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3686. }
  3687. }
  3688. TEST(UserDataTest, BasicOperations) {
  3689. httplib::UserData ud;
  3690. // Initially empty
  3691. EXPECT_FALSE(ud.has("key"));
  3692. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3693. // set and get
  3694. ud.set("key", 42);
  3695. EXPECT_TRUE(ud.has("key"));
  3696. auto *p = ud.get<int>("key");
  3697. ASSERT_NE(nullptr, p);
  3698. EXPECT_EQ(42, *p);
  3699. // Type mismatch → nullptr
  3700. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3701. // Overwrite with different type
  3702. ud.set("key", std::string("hello"));
  3703. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3704. auto *s = ud.get<std::string>("key");
  3705. ASSERT_NE(nullptr, s);
  3706. EXPECT_EQ("hello", *s);
  3707. // erase
  3708. ud.erase("key");
  3709. EXPECT_FALSE(ud.has("key"));
  3710. // clear
  3711. ud.set("a", 1);
  3712. ud.set("b", 2);
  3713. ud.clear();
  3714. EXPECT_FALSE(ud.has("a"));
  3715. EXPECT_FALSE(ud.has("b"));
  3716. }
  3717. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3718. struct AuthCtx {
  3719. std::string user_id;
  3720. };
  3721. Server svr;
  3722. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3723. res.user_data.set("auth", AuthCtx{"alice"});
  3724. return Server::HandlerResponse::Unhandled;
  3725. });
  3726. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3727. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3728. ASSERT_NE(nullptr, ctx);
  3729. res.set_content("Hello " + ctx->user_id, "text/plain");
  3730. });
  3731. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3732. auto se = detail::scope_exit([&] {
  3733. svr.stop();
  3734. thread.join();
  3735. ASSERT_FALSE(svr.is_running());
  3736. });
  3737. svr.wait_until_ready();
  3738. Client cli(HOST, PORT);
  3739. auto res = cli.Get("/me");
  3740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3741. EXPECT_EQ(StatusCode::OK_200, res->status);
  3742. EXPECT_EQ("Hello alice", res->body);
  3743. }
  3744. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3745. struct RoleCtx {
  3746. std::string role;
  3747. };
  3748. Server svr;
  3749. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3750. res.user_data.set("role", RoleCtx{"admin"});
  3751. return Server::HandlerResponse::Unhandled;
  3752. });
  3753. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3754. auto *ctx = res.user_data.get<RoleCtx>("role");
  3755. ASSERT_NE(nullptr, ctx);
  3756. res.set_content(ctx->role, "text/plain");
  3757. });
  3758. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3759. auto se = detail::scope_exit([&] {
  3760. svr.stop();
  3761. thread.join();
  3762. ASSERT_FALSE(svr.is_running());
  3763. });
  3764. svr.wait_until_ready();
  3765. Client cli(HOST, PORT);
  3766. auto res = cli.Get("/role");
  3767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3768. EXPECT_EQ(StatusCode::OK_200, res->status);
  3769. EXPECT_EQ("admin", res->body);
  3770. }
  3771. TEST(InvalidFormatTest, StatusCode) {
  3772. Server svr;
  3773. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3774. res.set_content("Hello World!\n", "text/plain");
  3775. res.status = 9999; // Status should be a three-digit code...
  3776. });
  3777. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3778. auto se = detail::scope_exit([&] {
  3779. svr.stop();
  3780. thread.join();
  3781. ASSERT_FALSE(svr.is_running());
  3782. });
  3783. svr.wait_until_ready();
  3784. {
  3785. Client cli(HOST, PORT);
  3786. auto res = cli.Get("/hi");
  3787. ASSERT_FALSE(res);
  3788. }
  3789. }
  3790. TEST(URLFragmentTest, WithFragment) {
  3791. Server svr;
  3792. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3793. EXPECT_TRUE(req.target == "/hi");
  3794. });
  3795. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3796. auto se = detail::scope_exit([&] {
  3797. svr.stop();
  3798. thread.join();
  3799. ASSERT_FALSE(svr.is_running());
  3800. });
  3801. svr.wait_until_ready();
  3802. {
  3803. Client cli(HOST, PORT);
  3804. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3805. EXPECT_TRUE(res);
  3806. EXPECT_EQ(StatusCode::OK_200, res->status);
  3807. res = cli.Get("/hi%23key1=val1=key2=val2");
  3808. EXPECT_TRUE(res);
  3809. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3810. }
  3811. }
  3812. TEST(HeaderWriter, SetHeaderWriter) {
  3813. Server svr;
  3814. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3815. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3816. return detail::write_headers(strm, hdrs);
  3817. });
  3818. svr.Get("/hi", [](const Request &req, Response &res) {
  3819. auto it = req.headers.find("CustomClientHeader");
  3820. EXPECT_TRUE(it != req.headers.end());
  3821. EXPECT_EQ(it->second, "CustomClientValue");
  3822. res.set_content("Hello World!\n", "text/plain");
  3823. });
  3824. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3825. auto se = detail::scope_exit([&] {
  3826. svr.stop();
  3827. thread.join();
  3828. ASSERT_FALSE(svr.is_running());
  3829. });
  3830. svr.wait_until_ready();
  3831. {
  3832. Client cli(HOST, PORT);
  3833. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3834. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3835. return detail::write_headers(strm, hdrs);
  3836. });
  3837. auto res = cli.Get("/hi");
  3838. EXPECT_TRUE(res);
  3839. EXPECT_EQ(StatusCode::OK_200, res->status);
  3840. auto it = res->headers.find("CustomServerHeader");
  3841. EXPECT_TRUE(it != res->headers.end());
  3842. EXPECT_EQ(it->second, "CustomServerValue");
  3843. }
  3844. }
  3845. class ServerTest : public ::testing::Test {
  3846. protected:
  3847. ServerTest()
  3848. : cli_(HOST, PORT)
  3849. #ifdef CPPHTTPLIB_SSL_ENABLED
  3850. ,
  3851. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3852. #endif
  3853. {
  3854. #ifdef CPPHTTPLIB_SSL_ENABLED
  3855. cli_.enable_server_certificate_verification(false);
  3856. #endif
  3857. // Allow LARGE_DATA (100MB) responses
  3858. cli_.set_payload_max_length(200 * 1024 * 1024);
  3859. }
  3860. virtual void SetUp() {
  3861. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3862. svr_.set_payload_max_length(200 * 1024 * 1024);
  3863. svr_.set_mount_point("/", "./www");
  3864. svr_.set_mount_point("/mount", "./www2");
  3865. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3866. svr_.Get("/hi",
  3867. [&](const Request & /*req*/, Response &res) {
  3868. res.set_content("Hello World!", "text/plain");
  3869. })
  3870. .Get("/file_content",
  3871. [&](const Request & /*req*/, Response &res) {
  3872. res.set_file_content("./www/dir/test.html");
  3873. })
  3874. .Get("/file_content_with_content_type",
  3875. [&](const Request & /*req*/, Response &res) {
  3876. res.set_file_content("./www/file", "text/plain");
  3877. })
  3878. .Get("/invalid_file_content",
  3879. [&](const Request & /*req*/, Response &res) {
  3880. res.set_file_content("./www/dir/invalid_file_path");
  3881. })
  3882. .Get("/http_response_splitting",
  3883. [&](const Request & /*req*/, Response &res) {
  3884. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3885. EXPECT_EQ(0U, res.headers.size());
  3886. EXPECT_FALSE(res.has_header("a"));
  3887. res.set_header("a", "1\nSet-Cookie: a=1");
  3888. EXPECT_EQ(0U, res.headers.size());
  3889. EXPECT_FALSE(res.has_header("a"));
  3890. res.set_header("a", "1\rSet-Cookie: a=1");
  3891. EXPECT_EQ(0U, res.headers.size());
  3892. EXPECT_FALSE(res.has_header("a"));
  3893. res.set_header("a\r\nb", "0");
  3894. EXPECT_EQ(0U, res.headers.size());
  3895. EXPECT_FALSE(res.has_header("a"));
  3896. res.set_header("a\rb", "0");
  3897. EXPECT_EQ(0U, res.headers.size());
  3898. EXPECT_FALSE(res.has_header("a"));
  3899. res.set_header("a\nb", "0");
  3900. EXPECT_EQ(0U, res.headers.size());
  3901. EXPECT_FALSE(res.has_header("a"));
  3902. res.set_redirect("1\r\nSet-Cookie: a=1");
  3903. EXPECT_EQ(0U, res.headers.size());
  3904. EXPECT_FALSE(res.has_header("Location"));
  3905. })
  3906. .Get("/slow",
  3907. [&](const Request & /*req*/, Response &res) {
  3908. std::this_thread::sleep_for(std::chrono::seconds(4));
  3909. res.set_content("slow", "text/plain");
  3910. })
  3911. #if 0
  3912. .Post("/slowpost",
  3913. [&](const Request & /*req*/, Response &res) {
  3914. std::this_thread::sleep_for(std::chrono::seconds(2));
  3915. res.set_content("slow", "text/plain");
  3916. })
  3917. #endif
  3918. .Get("/remote_addr",
  3919. [&](const Request &req, Response &res) {
  3920. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3921. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3922. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3923. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3924. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3925. #endif
  3926. res.set_content(req.remote_addr, "text/plain");
  3927. })
  3928. .Get("/local_addr",
  3929. [&](const Request &req, Response &res) {
  3930. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3931. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3932. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3933. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3934. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3935. #endif
  3936. auto local_addr = req.local_addr;
  3937. auto local_port = std::to_string(req.local_port);
  3938. res.set_content(local_addr.append(":").append(local_port),
  3939. "text/plain");
  3940. })
  3941. .Get("/endwith%",
  3942. [&](const Request & /*req*/, Response &res) {
  3943. res.set_content("Hello World!", "text/plain");
  3944. })
  3945. .Get("/a\\+\\+b",
  3946. [&](const Request &req, Response &res) {
  3947. ASSERT_TRUE(req.has_param("a +b"));
  3948. auto val = req.get_param_value("a +b");
  3949. res.set_content(val, "text/plain");
  3950. })
  3951. .Get("/", [&](const Request & /*req*/,
  3952. Response &res) { res.set_redirect("/hi"); })
  3953. .Post("/1",
  3954. [](const Request & /*req*/, Response &res) {
  3955. res.set_redirect("/2", StatusCode::SeeOther_303);
  3956. })
  3957. .Get("/2",
  3958. [](const Request & /*req*/, Response &res) {
  3959. res.set_content("redirected.", "text/plain");
  3960. res.status = StatusCode::OK_200;
  3961. })
  3962. .Post("/person",
  3963. [&](const Request &req, Response &res) {
  3964. if (req.has_param("name") && req.has_param("note")) {
  3965. persons_[req.get_param_value("name")] =
  3966. req.get_param_value("note");
  3967. } else {
  3968. res.status = StatusCode::BadRequest_400;
  3969. }
  3970. })
  3971. .Put("/person",
  3972. [&](const Request &req, Response &res) {
  3973. if (req.has_param("name") && req.has_param("note")) {
  3974. persons_[req.get_param_value("name")] =
  3975. req.get_param_value("note");
  3976. } else {
  3977. res.status = StatusCode::BadRequest_400;
  3978. }
  3979. })
  3980. .Get("/person/(.*)",
  3981. [&](const Request &req, Response &res) {
  3982. string name = req.matches[1];
  3983. if (persons_.find(name) != persons_.end()) {
  3984. auto note = persons_[name];
  3985. res.set_content(note, "text/plain");
  3986. } else {
  3987. res.status = StatusCode::NotFound_404;
  3988. }
  3989. })
  3990. .Delete("/person",
  3991. [&](const Request &req, Response &res) {
  3992. if (req.has_param("name")) {
  3993. string name = req.get_param_value("name");
  3994. if (persons_.find(name) != persons_.end()) {
  3995. persons_.erase(name);
  3996. res.set_content("DELETED", "text/plain");
  3997. } else {
  3998. res.status = StatusCode::NotFound_404;
  3999. }
  4000. } else {
  4001. res.status = StatusCode::BadRequest_400;
  4002. }
  4003. })
  4004. .Post("/x-www-form-urlencoded-json",
  4005. [&](const Request &req, Response &res) {
  4006. auto json = req.get_param_value("json");
  4007. ASSERT_EQ(JSON_DATA, json);
  4008. res.set_content(json, "appliation/json");
  4009. res.status = StatusCode::OK_200;
  4010. })
  4011. .Get("/streamed-chunked",
  4012. [&](const Request & /*req*/, Response &res) {
  4013. res.set_chunked_content_provider(
  4014. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4015. sink.os << "123";
  4016. sink.os << "456";
  4017. sink.os << "789";
  4018. sink.done();
  4019. return true;
  4020. });
  4021. })
  4022. .Get("/streamed-chunked-with-prohibited-trailer",
  4023. [&](const Request & /*req*/, Response &res) {
  4024. auto i = new int(0);
  4025. // Declare both a prohibited trailer (Content-Length) and an
  4026. // allowed one
  4027. res.set_header("Trailer", "Content-Length, X-Allowed");
  4028. res.set_chunked_content_provider(
  4029. "text/plain",
  4030. [i](size_t /*offset*/, DataSink &sink) {
  4031. switch (*i) {
  4032. case 0: sink.os << "123"; break;
  4033. case 1: sink.os << "456"; break;
  4034. case 2: sink.os << "789"; break;
  4035. case 3: {
  4036. sink.done_with_trailer(
  4037. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4038. } break;
  4039. }
  4040. (*i)++;
  4041. return true;
  4042. },
  4043. [i](bool success) {
  4044. EXPECT_TRUE(success);
  4045. delete i;
  4046. });
  4047. })
  4048. .Get("/streamed-chunked2",
  4049. [&](const Request & /*req*/, Response &res) {
  4050. auto i = new int(0);
  4051. res.set_chunked_content_provider(
  4052. "text/plain",
  4053. [i](size_t /*offset*/, DataSink &sink) {
  4054. switch (*i) {
  4055. case 0: sink.os << "123"; break;
  4056. case 1: sink.os << "456"; break;
  4057. case 2: sink.os << "789"; break;
  4058. case 3: sink.done(); break;
  4059. }
  4060. (*i)++;
  4061. return true;
  4062. },
  4063. [i](bool success) {
  4064. EXPECT_TRUE(success);
  4065. delete i;
  4066. });
  4067. })
  4068. .Get("/streamed-chunked-with-trailer",
  4069. [&](const Request & /*req*/, Response &res) {
  4070. auto i = new int(0);
  4071. res.set_header("Trailer", "Dummy1, Dummy2");
  4072. res.set_chunked_content_provider(
  4073. "text/plain",
  4074. [i](size_t /*offset*/, DataSink &sink) {
  4075. switch (*i) {
  4076. case 0: sink.os << "123"; break;
  4077. case 1: sink.os << "456"; break;
  4078. case 2: sink.os << "789"; break;
  4079. case 3: {
  4080. sink.done_with_trailer(
  4081. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4082. } break;
  4083. }
  4084. (*i)++;
  4085. return true;
  4086. },
  4087. [i](bool success) {
  4088. EXPECT_TRUE(success);
  4089. delete i;
  4090. });
  4091. })
  4092. .Get("/streamed",
  4093. [&](const Request & /*req*/, Response &res) {
  4094. res.set_content_provider(
  4095. 6, "text/plain",
  4096. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4097. sink.os << (offset < 3 ? "a" : "b");
  4098. return true;
  4099. });
  4100. })
  4101. .Get("/streamed-without-length",
  4102. [&](const Request & /*req*/, Response &res) {
  4103. auto data = new std::string("abcdefg");
  4104. res.set_content_provider(
  4105. "text/plain",
  4106. [data](size_t offset, DataSink &sink) {
  4107. if (offset < data->size()) {
  4108. sink.os << data->substr(offset);
  4109. }
  4110. sink.done();
  4111. return true;
  4112. },
  4113. [data](bool success) {
  4114. EXPECT_TRUE(success);
  4115. delete data;
  4116. });
  4117. })
  4118. .Get("/streamed-with-range",
  4119. [&](const Request &req, Response &res) {
  4120. auto data = new std::string("abcdefg");
  4121. // An explicit status keeps the server from picking the 206 it
  4122. // would otherwise choose for a ranged request, so the response
  4123. // is not a partial representation.
  4124. auto status = req.get_param_value("status");
  4125. if (status == "200") {
  4126. res.status = StatusCode::OK_200;
  4127. } else if (status == "403") {
  4128. res.status = StatusCode::Forbidden_403;
  4129. }
  4130. res.set_content_provider(
  4131. data->size(), "text/plain",
  4132. [data](size_t offset, size_t length, DataSink &sink) {
  4133. size_t DATA_CHUNK_SIZE = 4;
  4134. const auto &d = *data;
  4135. auto out_len =
  4136. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4137. auto ret =
  4138. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4139. EXPECT_TRUE(ret);
  4140. return true;
  4141. },
  4142. [data, &req](bool success) {
  4143. EXPECT_EQ(success, !req.has_param("error"));
  4144. delete data;
  4145. });
  4146. })
  4147. .Get("/streamed-cancel",
  4148. [&](const Request & /*req*/, Response &res) {
  4149. res.set_content_provider(
  4150. size_t(-1), "text/plain",
  4151. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4152. sink.os << "data_chunk";
  4153. return true;
  4154. });
  4155. })
  4156. .Get("/regex-with-delimiter",
  4157. [&](const Request &req, Response & /*res*/) {
  4158. ASSERT_TRUE(req.has_param("key"));
  4159. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4160. })
  4161. .Get("/with-range",
  4162. [&](const Request & /*req*/, Response &res) {
  4163. res.set_content("abcdefg", "text/plain");
  4164. })
  4165. .Get("/test-start-time",
  4166. [&](const Request &req, Response & /*res*/) {
  4167. EXPECT_NE(req.start_time_,
  4168. std::chrono::steady_clock::time_point::min());
  4169. })
  4170. .Get("/with-range-customized-response",
  4171. [&](const Request & /*req*/, Response &res) {
  4172. res.status = StatusCode::BadRequest_400;
  4173. res.set_content(JSON_DATA, "application/json");
  4174. })
  4175. .Post("/chunked",
  4176. [&](const Request &req, Response & /*res*/) {
  4177. EXPECT_EQ(req.body, "dechunked post body");
  4178. })
  4179. .Post("/large-chunked",
  4180. [&](const Request &req, Response & /*res*/) {
  4181. std::string expected(6 * 30 * 1024u, 'a');
  4182. EXPECT_EQ(req.body, expected);
  4183. })
  4184. .Post("/multipart",
  4185. [&](const Request &req, Response & /*res*/) {
  4186. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4187. req.form.get_field_count("text2") +
  4188. req.form.get_field_count("file3") +
  4189. req.form.get_field_count("file4"));
  4190. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4191. req.form.get_file_count("file2"));
  4192. ASSERT_TRUE(!req.form.has_file("???"));
  4193. ASSERT_TRUE(!req.form.has_field("???"));
  4194. ASSERT_TRUE(req.body.empty());
  4195. {
  4196. const auto &text = req.form.get_field("text1");
  4197. EXPECT_EQ("text default", text);
  4198. }
  4199. {
  4200. const auto &text = req.form.get_field("text2");
  4201. EXPECT_EQ("aωb", text);
  4202. }
  4203. {
  4204. const auto &file = req.form.get_file("file1");
  4205. EXPECT_EQ("hello.txt", file.filename);
  4206. EXPECT_EQ("text/plain", file.content_type);
  4207. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4208. }
  4209. {
  4210. const auto &file = req.form.get_file("file2");
  4211. EXPECT_EQ("world.json", file.filename);
  4212. EXPECT_EQ("application/json", file.content_type);
  4213. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4214. }
  4215. {
  4216. const auto &text = req.form.get_field("file3");
  4217. EXPECT_EQ(0u, text.size());
  4218. }
  4219. {
  4220. const auto &text = req.form.get_field("file4");
  4221. EXPECT_EQ(0u, text.size());
  4222. }
  4223. })
  4224. .Post("/multipart/multi_file_values",
  4225. [&](const Request &req, Response & /*res*/) {
  4226. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4227. req.form.get_field_count("multi_text1"));
  4228. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4229. ASSERT_TRUE(!req.form.has_file("???"));
  4230. ASSERT_TRUE(!req.form.has_field("???"));
  4231. ASSERT_TRUE(req.body.empty());
  4232. {
  4233. const auto &text = req.form.get_field("text");
  4234. EXPECT_EQ("default text", text);
  4235. }
  4236. {
  4237. const auto &text1_values = req.form.get_fields("multi_text1");
  4238. EXPECT_EQ(2u, text1_values.size());
  4239. EXPECT_EQ("aaaaa", text1_values[0]);
  4240. EXPECT_EQ("bbbbb", text1_values[1]);
  4241. }
  4242. {
  4243. const auto &file1_values = req.form.get_files("multi_file1");
  4244. EXPECT_EQ(2u, file1_values.size());
  4245. auto file1 = file1_values[0];
  4246. EXPECT_EQ(file1.filename, "hello.txt");
  4247. EXPECT_EQ(file1.content_type, "text/plain");
  4248. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4249. auto file2 = file1_values[1];
  4250. EXPECT_EQ(file2.filename, "world.json");
  4251. EXPECT_EQ(file2.content_type, "application/json");
  4252. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4253. }
  4254. })
  4255. .Post("/empty",
  4256. [&](const Request &req, Response &res) {
  4257. EXPECT_EQ(req.body, "");
  4258. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4259. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4260. res.set_content("empty", "text/plain");
  4261. })
  4262. .Post("/empty-no-content-type",
  4263. [&](const Request &req, Response &res) {
  4264. EXPECT_EQ(req.body, "");
  4265. EXPECT_FALSE(req.has_header("Content-Type"));
  4266. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4267. res.set_content("empty-no-content-type", "text/plain");
  4268. })
  4269. .Post("/path-only",
  4270. [&](const Request &req, Response &res) {
  4271. EXPECT_EQ(req.body, "");
  4272. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4273. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4274. res.set_content("path-only", "text/plain");
  4275. })
  4276. .Post("/path-headers-only",
  4277. [&](const Request &req, Response &res) {
  4278. EXPECT_EQ(req.body, "");
  4279. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4280. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4281. EXPECT_EQ("world", req.get_header_value("hello"));
  4282. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4283. res.set_content("path-headers-only", "text/plain");
  4284. })
  4285. .Post("/post-large",
  4286. [&](const Request &req, Response &res) {
  4287. EXPECT_EQ(req.body, LARGE_DATA);
  4288. res.set_content(req.body, "text/plain");
  4289. })
  4290. .Post("/post-loopback",
  4291. [&](const Request &, Response &res,
  4292. ContentReader const &content_reader) {
  4293. std::string body;
  4294. content_reader([&](const char *data, size_t data_length) {
  4295. body.append(data, data_length);
  4296. return true;
  4297. });
  4298. res.set_content(body, "text/plain");
  4299. })
  4300. .Put("/put-loopback",
  4301. [&](const Request &, Response &res,
  4302. ContentReader const &content_reader) {
  4303. std::string body;
  4304. content_reader([&](const char *data, size_t data_length) {
  4305. body.append(data, data_length);
  4306. return true;
  4307. });
  4308. res.set_content(body, "text/plain");
  4309. })
  4310. .Patch("/patch-loopback",
  4311. [&](const Request &, Response &res,
  4312. ContentReader const &content_reader) {
  4313. std::string body;
  4314. content_reader([&](const char *data, size_t data_length) {
  4315. body.append(data, data_length);
  4316. return true;
  4317. });
  4318. res.set_content(body, "text/plain");
  4319. })
  4320. .Put("/empty-no-content-type",
  4321. [&](const Request &req, Response &res) {
  4322. EXPECT_EQ(req.body, "");
  4323. EXPECT_FALSE(req.has_header("Content-Type"));
  4324. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4325. res.set_content("empty-no-content-type", "text/plain");
  4326. })
  4327. .Put("/put",
  4328. [&](const Request &req, Response &res) {
  4329. EXPECT_EQ(req.body, "PUT");
  4330. res.set_content(req.body, "text/plain");
  4331. })
  4332. .Put("/put-large",
  4333. [&](const Request &req, Response &res) {
  4334. EXPECT_EQ(req.body, LARGE_DATA);
  4335. res.set_content(req.body, "text/plain");
  4336. })
  4337. .Patch("/patch",
  4338. [&](const Request &req, Response &res) {
  4339. EXPECT_EQ(req.body, "PATCH");
  4340. res.set_content(req.body, "text/plain");
  4341. })
  4342. .Delete("/delete",
  4343. [&](const Request & /*req*/, Response &res) {
  4344. res.set_content("DELETE", "text/plain");
  4345. })
  4346. .Delete("/delete-body",
  4347. [&](const Request &req, Response &res) {
  4348. EXPECT_EQ(req.body, "content");
  4349. res.set_content(req.body, "text/plain");
  4350. })
  4351. .Options(R"(\*)",
  4352. [&](const Request & /*req*/, Response &res) {
  4353. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4354. })
  4355. .Get("/request-target",
  4356. [&](const Request &req, Response & /*res*/) {
  4357. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4358. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4359. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4360. })
  4361. .Get("/long-query-value",
  4362. [&](const Request &req, Response & /*res*/) {
  4363. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4364. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4365. })
  4366. .Get("/too-long-query-value",
  4367. [&](const Request &req, Response & /*res*/) {
  4368. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4369. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4370. })
  4371. .Get("/array-param",
  4372. [&](const Request &req, Response & /*res*/) {
  4373. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4374. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4375. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4376. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4377. })
  4378. .Get("/array-param-values",
  4379. [&](const Request &req, Response & /*res*/) {
  4380. auto values = req.get_param_values("array");
  4381. EXPECT_EQ(3u, values.size());
  4382. EXPECT_EQ("value1", values[0]);
  4383. EXPECT_EQ("value2", values[1]);
  4384. EXPECT_EQ("value3", values[2]);
  4385. auto empty = req.get_param_values("nonexistent");
  4386. EXPECT_TRUE(empty.empty());
  4387. })
  4388. .Post("/validate-no-multiple-headers",
  4389. [&](const Request &req, Response & /*res*/) {
  4390. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4391. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4392. })
  4393. .Post("/content_receiver",
  4394. [&](const Request &req, Response &res,
  4395. const ContentReader &content_reader) {
  4396. if (req.is_multipart_form_data()) {
  4397. std::vector<FormData> items;
  4398. content_reader(
  4399. [&](const FormData &file) {
  4400. items.push_back(file);
  4401. return true;
  4402. },
  4403. [&](const char *data, size_t data_length) {
  4404. items.back().content.append(data, data_length);
  4405. return true;
  4406. });
  4407. EXPECT_EQ(5u, items.size());
  4408. {
  4409. const auto &file = get_file_value(items, "text1");
  4410. EXPECT_TRUE(file.filename.empty());
  4411. EXPECT_EQ("text default", file.content);
  4412. }
  4413. {
  4414. const auto &file = get_file_value(items, "text2");
  4415. EXPECT_TRUE(file.filename.empty());
  4416. EXPECT_EQ("aωb", file.content);
  4417. }
  4418. {
  4419. const auto &file = get_file_value(items, "file1");
  4420. EXPECT_EQ("hello.txt", file.filename);
  4421. EXPECT_EQ("text/plain", file.content_type);
  4422. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4423. }
  4424. {
  4425. const auto &file = get_file_value(items, "file2");
  4426. EXPECT_EQ("world.json", file.filename);
  4427. EXPECT_EQ("application/json", file.content_type);
  4428. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4429. }
  4430. {
  4431. const auto &file = get_file_value(items, "file3");
  4432. EXPECT_TRUE(file.filename.empty());
  4433. EXPECT_EQ("application/octet-stream", file.content_type);
  4434. EXPECT_EQ(0u, file.content.size());
  4435. }
  4436. } else {
  4437. std::string body;
  4438. content_reader([&](const char *data, size_t data_length) {
  4439. EXPECT_EQ(7U, data_length);
  4440. body.append(data, data_length);
  4441. return true;
  4442. });
  4443. EXPECT_EQ(body, "content");
  4444. res.set_content(body, "text/plain");
  4445. }
  4446. })
  4447. .Put("/content_receiver",
  4448. [&](const Request & /*req*/, Response &res,
  4449. const ContentReader &content_reader) {
  4450. std::string body;
  4451. content_reader([&](const char *data, size_t data_length) {
  4452. body.append(data, data_length);
  4453. return true;
  4454. });
  4455. EXPECT_EQ(body, "content");
  4456. res.set_content(body, "text/plain");
  4457. })
  4458. .Patch("/content_receiver",
  4459. [&](const Request & /*req*/, Response &res,
  4460. const ContentReader &content_reader) {
  4461. std::string body;
  4462. content_reader([&](const char *data, size_t data_length) {
  4463. body.append(data, data_length);
  4464. return true;
  4465. });
  4466. EXPECT_EQ(body, "content");
  4467. res.set_content(body, "text/plain");
  4468. })
  4469. .Post("/query-string-and-body",
  4470. [&](const Request &req, Response & /*res*/) {
  4471. ASSERT_TRUE(req.has_param("key"));
  4472. EXPECT_EQ(req.get_param_value("key"), "value");
  4473. EXPECT_EQ(req.body, "content");
  4474. })
  4475. .Get("/last-request",
  4476. [&](const Request &req, Response & /*res*/) {
  4477. EXPECT_EQ("close", req.get_header_value("Connection"));
  4478. })
  4479. .Get(R"(/redirect/(\d+))",
  4480. [&](const Request &req, Response &res) {
  4481. auto num = std::stoi(req.matches[1]) + 1;
  4482. std::string url = "/redirect/" + std::to_string(num);
  4483. res.set_redirect(url);
  4484. })
  4485. .Post("/binary",
  4486. [&](const Request &req, Response &res) {
  4487. EXPECT_EQ(4U, req.body.size());
  4488. EXPECT_EQ("application/octet-stream",
  4489. req.get_header_value("Content-Type"));
  4490. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4491. res.set_content(req.body, "application/octet-stream");
  4492. })
  4493. .Put("/binary",
  4494. [&](const Request &req, Response &res) {
  4495. EXPECT_EQ(4U, req.body.size());
  4496. EXPECT_EQ("application/octet-stream",
  4497. req.get_header_value("Content-Type"));
  4498. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4499. res.set_content(req.body, "application/octet-stream");
  4500. })
  4501. .Patch("/binary",
  4502. [&](const Request &req, Response &res) {
  4503. EXPECT_EQ(4U, req.body.size());
  4504. EXPECT_EQ("application/octet-stream",
  4505. req.get_header_value("Content-Type"));
  4506. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4507. res.set_content(req.body, "application/octet-stream");
  4508. })
  4509. .Delete("/binary",
  4510. [&](const Request &req, Response &res) {
  4511. EXPECT_EQ(4U, req.body.size());
  4512. EXPECT_EQ("application/octet-stream",
  4513. req.get_header_value("Content-Type"));
  4514. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4515. res.set_content(req.body, "application/octet-stream");
  4516. })
  4517. .Get("/issue1772",
  4518. [&](const Request & /*req*/, Response &res) {
  4519. res.status = 401;
  4520. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4521. })
  4522. .Delete("/issue609",
  4523. [](const httplib::Request &, httplib::Response &res,
  4524. const httplib::ContentReader &) {
  4525. res.set_content("ok", "text/plain");
  4526. })
  4527. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4528. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4529. .Get("/compress",
  4530. [&](const Request & /*req*/, Response &res) {
  4531. res.set_content(
  4532. "12345678901234567890123456789012345678901234567890123456789"
  4533. "01234567890123456789012345678901234567890",
  4534. "text/plain");
  4535. })
  4536. .Get("/compress-with-charset",
  4537. [&](const Request & /*req*/, Response &res) {
  4538. res.set_content(
  4539. "12345678901234567890123456789012345678901234567890123456789"
  4540. "01234567890123456789012345678901234567890",
  4541. "application/json; charset=utf-8");
  4542. })
  4543. .Get("/nocompress",
  4544. [&](const Request & /*req*/, Response &res) {
  4545. res.set_content(
  4546. "12345678901234567890123456789012345678901234567890123456789"
  4547. "01234567890123456789012345678901234567890",
  4548. "application/octet-stream");
  4549. })
  4550. .Post("/compress-multipart",
  4551. [&](const Request &req, Response & /*res*/) {
  4552. EXPECT_EQ(2u, req.form.fields.size());
  4553. ASSERT_TRUE(!req.form.has_field("???"));
  4554. {
  4555. const auto &text = req.form.get_field("key1");
  4556. EXPECT_EQ("test", text);
  4557. }
  4558. {
  4559. const auto &text = req.form.get_field("key2");
  4560. EXPECT_EQ("--abcdefg123", text);
  4561. }
  4562. })
  4563. #endif
  4564. ;
  4565. persons_["john"] = "programmer";
  4566. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4567. svr_.wait_until_ready();
  4568. }
  4569. virtual void TearDown() {
  4570. svr_.stop();
  4571. if (!request_threads_.empty()) {
  4572. std::this_thread::sleep_for(std::chrono::seconds(1));
  4573. for (auto &t : request_threads_) {
  4574. t.join();
  4575. }
  4576. }
  4577. t_.join();
  4578. }
  4579. map<string, string> persons_;
  4580. #ifdef CPPHTTPLIB_SSL_ENABLED
  4581. SSLClient cli_;
  4582. SSLServer svr_;
  4583. #else
  4584. Client cli_;
  4585. Server svr_;
  4586. #endif
  4587. thread t_;
  4588. std::vector<thread> request_threads_;
  4589. };
  4590. TEST_F(ServerTest, GetMethod200) {
  4591. auto res = cli_.Get("/hi");
  4592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4593. EXPECT_EQ("HTTP/1.1", res->version);
  4594. EXPECT_EQ(StatusCode::OK_200, res->status);
  4595. EXPECT_EQ("OK", res->reason);
  4596. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4597. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4598. EXPECT_EQ("Hello World!", res->body);
  4599. }
  4600. TEST_F(ServerTest, GetEmptyFile) {
  4601. auto res = cli_.Get("/empty_file");
  4602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4603. EXPECT_EQ(StatusCode::OK_200, res->status);
  4604. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4605. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4606. EXPECT_EQ("", res->body);
  4607. }
  4608. TEST_F(ServerTest, GetFileContent) {
  4609. auto res = cli_.Get("/file_content");
  4610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4611. EXPECT_EQ(StatusCode::OK_200, res->status);
  4612. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4613. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4614. EXPECT_EQ("test.html", res->body);
  4615. }
  4616. TEST_F(ServerTest, GetFileContentWithRange) {
  4617. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4619. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4620. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4621. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4622. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4623. EXPECT_EQ("est", res->body);
  4624. }
  4625. TEST_F(ServerTest, GetFileContentWithContentType) {
  4626. auto res = cli_.Get("/file_content_with_content_type");
  4627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4628. EXPECT_EQ(StatusCode::OK_200, res->status);
  4629. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4630. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4631. EXPECT_EQ("file\n", res->body);
  4632. }
  4633. TEST_F(ServerTest, GetInvalidFileContent) {
  4634. auto res = cli_.Get("/invalid_file_content");
  4635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4636. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4637. }
  4638. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4639. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4641. EXPECT_EQ("HTTP/1.1", res->version);
  4642. EXPECT_EQ(StatusCode::OK_200, res->status);
  4643. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4644. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4645. EXPECT_EQ("Hello World!", res->body);
  4646. }
  4647. TEST_F(ServerTest, GetMethod302) {
  4648. auto res = cli_.Get("/");
  4649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4650. EXPECT_EQ(StatusCode::Found_302, res->status);
  4651. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4652. }
  4653. TEST_F(ServerTest, GetMethod302Redirect) {
  4654. cli_.set_follow_location(true);
  4655. auto res = cli_.Get("/");
  4656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4657. EXPECT_EQ(StatusCode::OK_200, res->status);
  4658. EXPECT_EQ("Hello World!", res->body);
  4659. EXPECT_EQ("/hi", res->location);
  4660. }
  4661. TEST_F(ServerTest, GetMethod404) {
  4662. auto res = cli_.Get("/invalid");
  4663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4664. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4665. }
  4666. TEST_F(ServerTest, HeadMethod200) {
  4667. auto res = cli_.Head("/hi");
  4668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4669. EXPECT_EQ(StatusCode::OK_200, res->status);
  4670. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4671. EXPECT_TRUE(res->body.empty());
  4672. }
  4673. TEST_F(ServerTest, HeadMethod200Static) {
  4674. auto res = cli_.Head("/mount/dir/index.html");
  4675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4676. EXPECT_EQ(StatusCode::OK_200, res->status);
  4677. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4678. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4679. EXPECT_TRUE(res->body.empty());
  4680. }
  4681. TEST_F(ServerTest, HeadMethod404) {
  4682. auto res = cli_.Head("/invalid");
  4683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4684. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4685. EXPECT_TRUE(res->body.empty());
  4686. }
  4687. TEST_F(ServerTest, GetMethodPersonJohn) {
  4688. auto res = cli_.Get("/person/john");
  4689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4690. EXPECT_EQ(StatusCode::OK_200, res->status);
  4691. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4692. EXPECT_EQ("programmer", res->body);
  4693. }
  4694. TEST_F(ServerTest, PostMethod1) {
  4695. auto res = cli_.Get("/person/john1");
  4696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4697. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4698. res = cli_.Post("/person", "name=john1&note=coder",
  4699. "application/x-www-form-urlencoded");
  4700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4701. ASSERT_EQ(StatusCode::OK_200, res->status);
  4702. res = cli_.Get("/person/john1");
  4703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4704. ASSERT_EQ(StatusCode::OK_200, res->status);
  4705. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4706. ASSERT_EQ("coder", res->body);
  4707. }
  4708. TEST_F(ServerTest, PostMethod2) {
  4709. auto res = cli_.Get("/person/john2");
  4710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4711. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4712. Params params;
  4713. params.emplace("name", "john2");
  4714. params.emplace("note", "coder");
  4715. res = cli_.Post("/person", params);
  4716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4717. ASSERT_EQ(StatusCode::OK_200, res->status);
  4718. res = cli_.Get("/person/john2");
  4719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4720. ASSERT_EQ(StatusCode::OK_200, res->status);
  4721. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4722. ASSERT_EQ("coder", res->body);
  4723. }
  4724. TEST_F(ServerTest, PutMethod3) {
  4725. auto res = cli_.Get("/person/john3");
  4726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4727. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4728. Params params;
  4729. params.emplace("name", "john3");
  4730. params.emplace("note", "coder");
  4731. res = cli_.Put("/person", params);
  4732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4733. ASSERT_EQ(StatusCode::OK_200, res->status);
  4734. res = cli_.Get("/person/john3");
  4735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4736. ASSERT_EQ(StatusCode::OK_200, res->status);
  4737. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4738. ASSERT_EQ("coder", res->body);
  4739. }
  4740. TEST_F(ServerTest, DeleteMethod1) {
  4741. auto res = cli_.Get("/person/john4");
  4742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4743. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4744. Params params;
  4745. params.emplace("name", "john4");
  4746. params.emplace("note", "coder");
  4747. res = cli_.Post("/person", params);
  4748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4749. ASSERT_EQ(StatusCode::OK_200, res->status);
  4750. res = cli_.Get("/person/john4");
  4751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4752. ASSERT_EQ(StatusCode::OK_200, res->status);
  4753. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4754. ASSERT_EQ("coder", res->body);
  4755. Params delete_params;
  4756. delete_params.emplace("name", "john4");
  4757. res = cli_.Delete("/person", delete_params);
  4758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4759. ASSERT_EQ(StatusCode::OK_200, res->status);
  4760. ASSERT_EQ("DELETED", res->body);
  4761. res = cli_.Get("/person/john4");
  4762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4763. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4764. }
  4765. TEST_F(ServerTest, DeleteMethod2) {
  4766. auto res = cli_.Get("/person/john5");
  4767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4768. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4769. Params params;
  4770. params.emplace("name", "john5");
  4771. params.emplace("note", "developer");
  4772. res = cli_.Post("/person", params);
  4773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4774. ASSERT_EQ(StatusCode::OK_200, res->status);
  4775. res = cli_.Get("/person/john5");
  4776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4777. ASSERT_EQ(StatusCode::OK_200, res->status);
  4778. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4779. ASSERT_EQ("developer", res->body);
  4780. Params delete_params;
  4781. delete_params.emplace("name", "john5");
  4782. Headers headers;
  4783. headers.emplace("Custom-Header", "test-value");
  4784. res = cli_.Delete("/person", headers, delete_params);
  4785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4786. ASSERT_EQ(StatusCode::OK_200, res->status);
  4787. ASSERT_EQ("DELETED", res->body);
  4788. res = cli_.Get("/person/john5");
  4789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4790. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4791. }
  4792. TEST_F(ServerTest, DeleteMethod3) {
  4793. auto res = cli_.Get("/person/john6");
  4794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4795. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4796. Params params;
  4797. params.emplace("name", "john6");
  4798. params.emplace("note", "tester");
  4799. res = cli_.Post("/person", params);
  4800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4801. ASSERT_EQ(StatusCode::OK_200, res->status);
  4802. res = cli_.Get("/person/john6");
  4803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4804. ASSERT_EQ(StatusCode::OK_200, res->status);
  4805. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4806. ASSERT_EQ("tester", res->body);
  4807. Params delete_params;
  4808. delete_params.emplace("name", "john6");
  4809. Headers headers;
  4810. headers.emplace("Custom-Header", "test-value");
  4811. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4813. ASSERT_EQ(StatusCode::OK_200, res->status);
  4814. ASSERT_EQ("DELETED", res->body);
  4815. res = cli_.Get("/person/john6");
  4816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4817. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4818. }
  4819. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4820. Params params;
  4821. params.emplace("json", JSON_DATA);
  4822. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4824. ASSERT_EQ(StatusCode::OK_200, res->status);
  4825. ASSERT_EQ(JSON_DATA, res->body);
  4826. }
  4827. TEST_F(ServerTest, PostEmptyContent) {
  4828. auto res = cli_.Post("/empty", "", "text/plain");
  4829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4830. ASSERT_EQ(StatusCode::OK_200, res->status);
  4831. ASSERT_EQ("empty", res->body);
  4832. }
  4833. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4834. auto res = cli_.Post("/empty-no-content-type");
  4835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4836. ASSERT_EQ(StatusCode::OK_200, res->status);
  4837. ASSERT_EQ("empty-no-content-type", res->body);
  4838. }
  4839. TEST_F(ServerTest, PostPathOnly) {
  4840. auto res = cli_.Post("/path-only");
  4841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4842. ASSERT_EQ(StatusCode::OK_200, res->status);
  4843. ASSERT_EQ("path-only", res->body);
  4844. }
  4845. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4846. auto res = cli_.Post("/path-headers-only",
  4847. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4849. ASSERT_EQ(StatusCode::OK_200, res->status);
  4850. ASSERT_EQ("path-headers-only", res->body);
  4851. }
  4852. TEST_F(ServerTest, PostLarge) {
  4853. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4855. ASSERT_EQ(StatusCode::OK_200, res->status);
  4856. EXPECT_EQ(LARGE_DATA, res->body);
  4857. }
  4858. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4859. auto res = cli_.Put("/empty-no-content-type");
  4860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4861. ASSERT_EQ(StatusCode::OK_200, res->status);
  4862. ASSERT_EQ("empty-no-content-type", res->body);
  4863. }
  4864. TEST_F(ServerTest, GetMethodDir) {
  4865. auto res = cli_.Get("/dir/");
  4866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4867. EXPECT_EQ(StatusCode::OK_200, res->status);
  4868. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4869. auto body = R"(<html>
  4870. <head>
  4871. </head>
  4872. <body>
  4873. <a href="/dir/test.html">Test</a>
  4874. <a href="/hi">hi</a>
  4875. </body>
  4876. </html>
  4877. )";
  4878. EXPECT_EQ(body, res->body);
  4879. }
  4880. TEST_F(ServerTest, GetMethodDirTest) {
  4881. auto res = cli_.Get("/dir/test.html");
  4882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4883. EXPECT_EQ(StatusCode::OK_200, res->status);
  4884. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4885. EXPECT_EQ("test.html", res->body);
  4886. }
  4887. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4888. auto res = cli_.Get("/dir/../dir/test.html");
  4889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4890. EXPECT_EQ(StatusCode::OK_200, res->status);
  4891. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4892. EXPECT_EQ("test.html", res->body);
  4893. }
  4894. TEST_F(ServerTest, GetMethodInvalidPath) {
  4895. auto res = cli_.Get("/dir/../test.html");
  4896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4897. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4898. }
  4899. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4900. auto res = cli_.Get("/../www/dir/test.html");
  4901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4902. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4903. }
  4904. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4905. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4907. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4908. }
  4909. TEST_F(ServerTest, GetMethodDirMountTest) {
  4910. auto res = cli_.Get("/mount/dir/test.html");
  4911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4912. EXPECT_EQ(StatusCode::OK_200, res->status);
  4913. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4914. EXPECT_EQ("test.html", res->body);
  4915. }
  4916. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4917. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4919. EXPECT_EQ(StatusCode::OK_200, res->status);
  4920. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4921. EXPECT_EQ("test.html", res->body);
  4922. }
  4923. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4924. auto res = cli_.Get("/mount/dir/../test.html");
  4925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4926. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4927. }
  4928. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4929. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4931. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4932. }
  4933. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4934. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4936. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4937. }
  4938. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4939. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4941. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4942. }
  4943. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4944. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4946. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4947. }
  4948. TEST_F(ServerTest, PostMethod303) {
  4949. auto res = cli_.Post("/1", "body", "text/plain");
  4950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4951. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4952. EXPECT_EQ("/2", res->get_header_value("Location"));
  4953. }
  4954. TEST_F(ServerTest, PostMethod303Redirect) {
  4955. cli_.set_follow_location(true);
  4956. auto res = cli_.Post("/1", "body", "text/plain");
  4957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4958. EXPECT_EQ(StatusCode::OK_200, res->status);
  4959. EXPECT_EQ("redirected.", res->body);
  4960. EXPECT_EQ("/2", res->location);
  4961. }
  4962. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4963. auto res = cli_.Get("/dir/test.abcde");
  4964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4965. EXPECT_EQ(StatusCode::OK_200, res->status);
  4966. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4967. EXPECT_EQ("abcde", res->body);
  4968. }
  4969. TEST_F(ServerTest, StaticFileRange) {
  4970. auto res =
  4971. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4973. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4974. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4975. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4976. EXPECT_EQ(true, res->has_header("Content-Range"));
  4977. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4978. EXPECT_EQ(std::string("cd"), res->body);
  4979. }
  4980. TEST_F(ServerTest, StaticFileRanges) {
  4981. auto res = cli_.Get("/dir/test.abcde",
  4982. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4984. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4985. EXPECT_TRUE(
  4986. res->get_header_value("Content-Type")
  4987. .find(
  4988. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4989. 0);
  4990. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4991. }
  4992. TEST_F(ServerTest, StaticFileRangeHead) {
  4993. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4995. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4996. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4997. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4998. EXPECT_EQ(true, res->has_header("Content-Range"));
  4999. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5000. }
  5001. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5002. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5004. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5005. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5006. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5007. EXPECT_EQ(true, res->has_header("Content-Range"));
  5008. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5009. res->get_header_value("Content-Range"));
  5010. EXPECT_EQ("LAST\n", res->body);
  5011. }
  5012. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5013. auto res =
  5014. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5016. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5017. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5018. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5019. EXPECT_EQ(true, res->has_header("Content-Range"));
  5020. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5021. }
  5022. TEST_F(ServerTest, StaticFileBigFile) {
  5023. auto res = cli_.Get("/dir/1MB.txt");
  5024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5025. EXPECT_EQ(StatusCode::OK_200, res->status);
  5026. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5027. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5028. }
  5029. TEST_F(ServerTest, InvalidBaseDirMount) {
  5030. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5031. }
  5032. TEST_F(ServerTest, Binary) {
  5033. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5034. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5035. "application/octet-stream");
  5036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5037. ASSERT_EQ(StatusCode::OK_200, res->status);
  5038. ASSERT_EQ(4U, res->body.size());
  5039. res = cli_.Put("/binary", binary.data(), binary.size(),
  5040. "application/octet-stream");
  5041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5042. ASSERT_EQ(StatusCode::OK_200, res->status);
  5043. ASSERT_EQ(4U, res->body.size());
  5044. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5045. "application/octet-stream");
  5046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5047. ASSERT_EQ(StatusCode::OK_200, res->status);
  5048. ASSERT_EQ(4U, res->body.size());
  5049. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5050. "application/octet-stream");
  5051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5052. ASSERT_EQ(StatusCode::OK_200, res->status);
  5053. ASSERT_EQ(4U, res->body.size());
  5054. }
  5055. TEST_F(ServerTest, BinaryString) {
  5056. auto binary = std::string("\x00\x01\x02\x03", 4);
  5057. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5059. ASSERT_EQ(StatusCode::OK_200, res->status);
  5060. ASSERT_EQ(4U, res->body.size());
  5061. res = cli_.Put("/binary", binary, "application/octet-stream");
  5062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5063. ASSERT_EQ(StatusCode::OK_200, res->status);
  5064. ASSERT_EQ(4U, res->body.size());
  5065. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5067. ASSERT_EQ(StatusCode::OK_200, res->status);
  5068. ASSERT_EQ(4U, res->body.size());
  5069. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5071. ASSERT_EQ(StatusCode::OK_200, res->status);
  5072. ASSERT_EQ(4U, res->body.size());
  5073. }
  5074. TEST_F(ServerTest, EmptyRequest) {
  5075. auto res = cli_.Get("");
  5076. ASSERT_TRUE(!res);
  5077. EXPECT_EQ(Error::Connection, res.error());
  5078. }
  5079. TEST_F(ServerTest, LongRequest) {
  5080. std::string request;
  5081. for (size_t i = 0; i < 545; i++) {
  5082. request += "/TooLongRequest";
  5083. }
  5084. request += "OK";
  5085. auto res = cli_.Get(request.c_str());
  5086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5087. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5088. }
  5089. TEST_F(ServerTest, TooLongRequest) {
  5090. std::string request;
  5091. for (size_t i = 0; i < 546; i++) {
  5092. request += "/TooLongRequest";
  5093. }
  5094. request += "_NG";
  5095. auto start = std::chrono::high_resolution_clock::now();
  5096. cli_.set_keep_alive(true);
  5097. auto res = cli_.Get(request.c_str());
  5098. auto end = std::chrono::high_resolution_clock::now();
  5099. auto elapsed =
  5100. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5101. .count();
  5102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5103. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5104. EXPECT_LE(elapsed, 1000);
  5105. EXPECT_EQ("close", res->get_header_value("Connection"));
  5106. EXPECT_FALSE(cli_.is_socket_open());
  5107. }
  5108. TEST_F(ServerTest, AlmostTooLongRequest) {
  5109. // test for #2046 - URI length check shouldn't include other content on req
  5110. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5111. // leading /, space, HTTP/1.1)
  5112. std::string request =
  5113. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5114. auto res = cli_.Get(request.c_str());
  5115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5116. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5117. }
  5118. TEST_F(ServerTest, LongHeader) {
  5119. Request req;
  5120. req.method = "GET";
  5121. req.path = "/hi";
  5122. std::string host_and_port;
  5123. host_and_port += HOST;
  5124. host_and_port += ":";
  5125. host_and_port += std::to_string(PORT);
  5126. req.headers.emplace("Host", host_and_port.c_str());
  5127. req.headers.emplace("Accept", "*/*");
  5128. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5129. req.headers.emplace(
  5130. "Header-Name",
  5131. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5132. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5159. "@@@@@@@@@@@@@@@@");
  5160. auto res = std::make_shared<Response>();
  5161. auto error = Error::Success;
  5162. auto ret = cli_.send(req, *res, error);
  5163. ASSERT_TRUE(ret);
  5164. EXPECT_EQ(StatusCode::OK_200, res->status);
  5165. }
  5166. TEST_F(ServerTest, LongQueryValue) {
  5167. auto start = std::chrono::high_resolution_clock::now();
  5168. cli_.set_keep_alive(true);
  5169. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5170. auto end = std::chrono::high_resolution_clock::now();
  5171. auto elapsed =
  5172. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5173. .count();
  5174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5175. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5176. EXPECT_LE(elapsed, 1000);
  5177. EXPECT_EQ("close", res->get_header_value("Connection"));
  5178. EXPECT_FALSE(cli_.is_socket_open());
  5179. }
  5180. TEST_F(ServerTest, TooLongQueryValue) {
  5181. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5182. ASSERT_FALSE(res);
  5183. EXPECT_EQ(Error::Read, res.error());
  5184. }
  5185. TEST_F(ServerTest, TooLongHeader) {
  5186. Request req;
  5187. req.method = "GET";
  5188. req.path = "/hi";
  5189. std::string host_and_port;
  5190. host_and_port += HOST;
  5191. host_and_port += ":";
  5192. host_and_port += std::to_string(PORT);
  5193. req.headers.emplace("Host", host_and_port.c_str());
  5194. req.headers.emplace("Accept", "*/*");
  5195. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5196. req.headers.emplace(
  5197. "Header-Name",
  5198. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5199. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5219. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5220. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5221. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5222. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5223. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5224. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5225. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5226. "@@@@@@@@@@@@@@@@@");
  5227. auto res = std::make_shared<Response>();
  5228. auto error = Error::Success;
  5229. auto ret = cli_.send(req, *res, error);
  5230. ASSERT_TRUE(ret);
  5231. EXPECT_EQ(StatusCode::OK_200, res->status);
  5232. }
  5233. TEST_F(ServerTest, HeaderCountAtLimit) {
  5234. // Test with headers just under the 100 limit
  5235. httplib::Headers headers;
  5236. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5237. // This should keep us just under the 100 header limit
  5238. for (int i = 0; i < 95; i++) {
  5239. std::string name = "X-Test-Header-" + std::to_string(i);
  5240. std::string value = "value" + std::to_string(i);
  5241. headers.emplace(name, value);
  5242. }
  5243. // This should work fine as we're under the limit
  5244. auto res = cli_.Get("/hi", headers);
  5245. EXPECT_TRUE(res);
  5246. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5247. }
  5248. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5249. // Test with many headers to exceed the 100 limit
  5250. httplib::Headers headers;
  5251. // Add 150 headers to definitely exceed the 100 limit
  5252. for (int i = 0; i < 150; i++) {
  5253. std::string name = "X-Test-Header-" + std::to_string(i);
  5254. std::string value = "value" + std::to_string(i);
  5255. headers.emplace(name, value);
  5256. }
  5257. // This should fail due to exceeding header count limit
  5258. cli_.set_keep_alive(true);
  5259. auto res = cli_.Get("/hi", headers);
  5260. // The server should respond with 400 Bad Request
  5261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5262. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5263. EXPECT_EQ("close", res->get_header_value("Connection"));
  5264. EXPECT_FALSE(cli_.is_socket_open());
  5265. }
  5266. TEST_F(ServerTest, PercentEncoding) {
  5267. auto res = cli_.Get("/e%6edwith%");
  5268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5269. EXPECT_EQ(StatusCode::OK_200, res->status);
  5270. }
  5271. TEST_F(ServerTest, PercentEncodingUnicode) {
  5272. auto res = cli_.Get("/e%u006edwith%");
  5273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5274. EXPECT_EQ(StatusCode::OK_200, res->status);
  5275. }
  5276. TEST_F(ServerTest, InvalidPercentEncoding) {
  5277. auto res = cli_.Get("/%endwith%");
  5278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5279. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5280. }
  5281. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5282. auto res = cli_.Get("/%uendwith%");
  5283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5284. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5285. }
  5286. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5287. auto res = cli_.Get("/hello?aaa=bbb%");
  5288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5289. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5290. }
  5291. TEST_F(ServerTest, PlusSignEncoding) {
  5292. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5294. EXPECT_EQ(StatusCode::OK_200, res->status);
  5295. EXPECT_EQ("a +b", res->body);
  5296. }
  5297. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5298. // This test simulates a potential DoS attack using many headers
  5299. // to verify our security fix prevents memory exhaustion
  5300. httplib::Headers attack_headers;
  5301. // Attempt to add many headers like an attacker would (200 headers to far
  5302. // exceed limit)
  5303. for (int i = 0; i < 200; i++) {
  5304. std::string name = "X-Attack-Header-" + std::to_string(i);
  5305. std::string value = "attack_payload_" + std::to_string(i);
  5306. attack_headers.emplace(name, value);
  5307. }
  5308. // Try to POST with excessive headers
  5309. cli_.set_keep_alive(true);
  5310. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5311. // Should either fail or return 400 Bad Request due to security limit
  5312. if (res) {
  5313. // If we get a response, it should be 400 Bad Request
  5314. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5315. EXPECT_EQ("close", res->get_header_value("Connection"));
  5316. }
  5317. EXPECT_FALSE(cli_.is_socket_open());
  5318. }
  5319. TEST_F(ServerTest, MultipartFormData) {
  5320. UploadFormDataItems items = {
  5321. {"text1", "text default", "", ""},
  5322. {"text2", "aωb", "", ""},
  5323. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5324. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5325. {"file3", "", "", "application/octet-stream"},
  5326. {"file4", "", "", " application/json tmp-string "}};
  5327. auto res = cli_.Post("/multipart", items);
  5328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5329. EXPECT_EQ(StatusCode::OK_200, res->status);
  5330. }
  5331. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5332. UploadFormDataItems items = {
  5333. {"text", "default text", "", ""},
  5334. {"multi_text1", "aaaaa", "", ""},
  5335. {"multi_text1", "bbbbb", "", ""},
  5336. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5337. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5338. "application/json"},
  5339. };
  5340. auto res = cli_.Post("/multipart/multi_file_values", items);
  5341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5342. EXPECT_EQ(StatusCode::OK_200, res->status);
  5343. }
  5344. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5345. auto res = cli_.Get("/hi");
  5346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5347. EXPECT_EQ(StatusCode::OK_200, res->status);
  5348. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5349. EXPECT_EQ("Hello World!", res->body);
  5350. }
  5351. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5352. Request req;
  5353. req.method = "POST";
  5354. req.path = "/chunked";
  5355. std::string host_and_port;
  5356. host_and_port += HOST;
  5357. host_and_port += ":";
  5358. host_and_port += std::to_string(PORT);
  5359. req.headers.emplace("Host", host_and_port.c_str());
  5360. req.headers.emplace("Accept", "*/*");
  5361. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5362. req.headers.emplace("Content-Type", "text/plain");
  5363. req.headers.emplace("Content-Length", "0");
  5364. req.headers.emplace(
  5365. "Transfer-Encoding",
  5366. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5367. // Client does not chunk, so make a chunked body manually.
  5368. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5369. auto res = std::make_shared<Response>();
  5370. auto error = Error::Success;
  5371. auto ret = cli_.send(req, *res, error);
  5372. ASSERT_TRUE(ret);
  5373. EXPECT_EQ(StatusCode::OK_200, res->status);
  5374. }
  5375. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5376. // rather than treat them as valid lengths.
  5377. template <typename ClientT>
  5378. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5379. Request req;
  5380. req.method = "POST";
  5381. req.path = "/chunked";
  5382. std::string host_and_port;
  5383. host_and_port += HOST;
  5384. host_and_port += ":";
  5385. host_and_port += std::to_string(PORT);
  5386. req.headers.emplace("Host", host_and_port.c_str());
  5387. req.headers.emplace("Content-Length", "0");
  5388. req.headers.emplace("Transfer-Encoding", "chunked");
  5389. req.body = body;
  5390. auto res = std::make_shared<Response>();
  5391. auto error = Error::Success;
  5392. ASSERT_TRUE(cli.send(req, *res, error));
  5393. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5394. }
  5395. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5396. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5397. }
  5398. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5399. expect_chunked_body_rejected(
  5400. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5401. }
  5402. TEST_F(ServerTest, GetStreamed2) {
  5403. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5405. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5406. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5407. EXPECT_EQ(true, res->has_header("Content-Range"));
  5408. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5409. EXPECT_EQ(std::string("ab"), res->body);
  5410. }
  5411. TEST_F(ServerTest, GetStreamed) {
  5412. auto res = cli_.Get("/streamed");
  5413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5414. EXPECT_EQ(StatusCode::OK_200, res->status);
  5415. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5416. EXPECT_EQ(std::string("aaabbb"), res->body);
  5417. }
  5418. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5419. auto res = cli_.Get("/streamed-without-length",
  5420. Headers{make_range_header({{0, -1}})});
  5421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5422. EXPECT_EQ(StatusCode::OK_200, res->status);
  5423. EXPECT_EQ(false, res->has_header("Content-Length"));
  5424. EXPECT_EQ(false, res->has_header("Content-Range"));
  5425. EXPECT_EQ(std::string("abcdefg"), res->body);
  5426. }
  5427. TEST_F(ServerTest, GetStreamedWithRange1) {
  5428. auto res =
  5429. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5431. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5432. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5433. EXPECT_EQ(true, res->has_header("Content-Range"));
  5434. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5435. EXPECT_EQ(std::string("def"), res->body);
  5436. }
  5437. TEST_F(ServerTest, GetStreamedWithRange2) {
  5438. auto res =
  5439. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5441. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5442. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5443. EXPECT_EQ(true, res->has_header("Content-Range"));
  5444. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5445. EXPECT_EQ(std::string("bcdefg"), res->body);
  5446. }
  5447. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5448. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5450. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5451. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5452. EXPECT_EQ(true, res->has_header("Content-Range"));
  5453. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5454. EXPECT_EQ(std::string("efg"), res->body);
  5455. }
  5456. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5457. auto res =
  5458. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5460. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5461. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5462. EXPECT_EQ(false, res->has_header("Content-Range"));
  5463. EXPECT_EQ(0U, res->body.size());
  5464. }
  5465. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5466. // Only a 206 is served as a partial representation. Under any other status
  5467. // `apply_ranges()` reported the full content length, so the body must match
  5468. // that header, and the content provider must never be asked for an offset
  5469. // outside the representation.
  5470. auto check = [&](int status, const char *range) {
  5471. auto path =
  5472. std::string("/streamed-with-range?status=") + std::to_string(status);
  5473. auto ctx = path + " Range: " + range;
  5474. auto res = cli_.Get(path, Headers{{"Range", range}});
  5475. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5476. EXPECT_EQ(status, res->status) << ctx;
  5477. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5478. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5479. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5480. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5481. };
  5482. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5483. check(403, "bytes=3-5");
  5484. // The offset is far past the representation.
  5485. check(403, "bytes=100000-100200");
  5486. // `first_pos` is still -1 here, and the bounds asserts in
  5487. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5488. check(403, "bytes=-3");
  5489. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5490. // multipart branch would have written one that is empty.
  5491. check(403, "bytes=1-2, 4-5");
  5492. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5493. // covers the whole representation.
  5494. check(200, "bytes=3-5");
  5495. check(200, "bytes=1-2, 4-5");
  5496. }
  5497. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5498. auto res =
  5499. cli_.Get("/streamed-with-range",
  5500. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5501. "92233720368547758079223372036854775807"}});
  5502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5503. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5504. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5505. EXPECT_EQ(false, res->has_header("Content-Range"));
  5506. EXPECT_EQ(0U, res->body.size());
  5507. }
  5508. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5509. auto res = cli_.Get(
  5510. "/with-range",
  5511. Headers{{"Range",
  5512. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5513. {"Accept-Encoding", ""}});
  5514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5515. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5516. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5517. EXPECT_EQ(true, res->has_header("Content-Range"));
  5518. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5519. EXPECT_EQ(std::string("abcdefg"), res->body);
  5520. }
  5521. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5522. auto res = cli_.Get("/with-range", Headers{
  5523. {"Range", "bytes=0-"},
  5524. {"Accept-Encoding", ""},
  5525. });
  5526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5527. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5528. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5529. EXPECT_EQ(true, res->has_header("Content-Range"));
  5530. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5531. EXPECT_EQ(std::string("abcdefg"), res->body);
  5532. }
  5533. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5534. auto res = cli_.Get("/streamed-with-range",
  5535. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5537. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5538. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5539. EXPECT_EQ(false, res->has_header("Content-Range"));
  5540. EXPECT_EQ(267U, res->body.size());
  5541. // Check that both range contents are present
  5542. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5543. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5544. // Check that Content-Range headers are present for both ranges
  5545. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5546. std::string::npos);
  5547. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5548. std::string::npos);
  5549. }
  5550. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5551. Ranges ranges;
  5552. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5553. ranges.emplace_back(0, -1);
  5554. }
  5555. auto res = cli_.Get("/streamed-with-range?error",
  5556. Headers{{make_range_header(ranges)}});
  5557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5558. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5559. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5560. EXPECT_EQ(false, res->has_header("Content-Range"));
  5561. EXPECT_EQ(0U, res->body.size());
  5562. }
  5563. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5564. auto res = cli_.Get("/streamed-with-range",
  5565. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5567. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5568. EXPECT_EQ(5U, res->body.size());
  5569. // Check that overlapping ranges are coalesced into a single range
  5570. EXPECT_EQ("bcdef", res->body);
  5571. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5572. // Should be single range, not multipart
  5573. EXPECT_TRUE(res->has_header("Content-Range"));
  5574. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5575. }
  5576. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5577. auto res = cli_.Get("/streamed-with-range",
  5578. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5580. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5581. EXPECT_EQ(268U, res->body.size());
  5582. // Check that both range contents are present
  5583. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5584. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5585. // Check that Content-Range headers are present for both ranges
  5586. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5587. std::string::npos);
  5588. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5589. std::string::npos);
  5590. }
  5591. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5592. auto res = cli_.Get("/streamed-with-range",
  5593. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5595. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5596. EXPECT_EQ(269U, res->body.size());
  5597. // Check that both duplicate range contents are present
  5598. size_t first_abc = res->body.find("abc\r\n");
  5599. EXPECT_TRUE(first_abc != std::string::npos);
  5600. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5601. EXPECT_TRUE(second_abc != std::string::npos);
  5602. // Check that Content-Range headers are present for both ranges
  5603. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5604. EXPECT_TRUE(first_range != std::string::npos);
  5605. size_t second_range =
  5606. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5607. EXPECT_TRUE(second_range != std::string::npos);
  5608. }
  5609. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5610. auto res =
  5611. cli_.Get("/streamed-with-range?error",
  5612. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5614. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5615. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5616. EXPECT_EQ(false, res->has_header("Content-Range"));
  5617. EXPECT_EQ(0U, res->body.size());
  5618. }
  5619. TEST_F(ServerTest, GetStreamedEndless) {
  5620. uint64_t offset = 0;
  5621. auto res = cli_.Get("/streamed-cancel",
  5622. [&](const char * /*data*/, uint64_t data_length) {
  5623. if (offset < 100) {
  5624. offset += data_length;
  5625. return true;
  5626. }
  5627. return false;
  5628. });
  5629. ASSERT_TRUE(!res);
  5630. EXPECT_EQ(Error::Canceled, res.error());
  5631. }
  5632. TEST_F(ServerTest, ClientStop) {
  5633. std::atomic_size_t count{4};
  5634. std::vector<std::thread> threads;
  5635. for (auto i = count.load(); i != 0; --i) {
  5636. threads.emplace_back([&]() {
  5637. auto res = cli_.Get("/streamed-cancel",
  5638. [&](const char *, uint64_t) { return true; });
  5639. --count;
  5640. ASSERT_TRUE(!res);
  5641. EXPECT_TRUE(res.error() == Error::Canceled ||
  5642. res.error() == Error::Read || res.error() == Error::Write);
  5643. });
  5644. }
  5645. std::this_thread::sleep_for(std::chrono::seconds(2));
  5646. while (count != 0) {
  5647. cli_.stop();
  5648. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5649. }
  5650. for (auto &t : threads) {
  5651. t.join();
  5652. }
  5653. }
  5654. TEST_F(ServerTest, GetWithRange1) {
  5655. auto res = cli_.Get("/with-range", Headers{
  5656. make_range_header({{3, 5}}),
  5657. {"Accept-Encoding", ""},
  5658. });
  5659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5660. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5661. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5662. EXPECT_EQ(true, res->has_header("Content-Range"));
  5663. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5664. EXPECT_EQ(std::string("def"), res->body);
  5665. }
  5666. TEST_F(ServerTest, GetWithRange2) {
  5667. auto res = cli_.Get("/with-range", Headers{
  5668. make_range_header({{1, -1}}),
  5669. {"Accept-Encoding", ""},
  5670. });
  5671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5672. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5673. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5674. EXPECT_EQ(true, res->has_header("Content-Range"));
  5675. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5676. EXPECT_EQ(std::string("bcdefg"), res->body);
  5677. }
  5678. TEST_F(ServerTest, GetWithRange3) {
  5679. auto res = cli_.Get("/with-range", Headers{
  5680. make_range_header({{0, 0}}),
  5681. {"Accept-Encoding", ""},
  5682. });
  5683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5684. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5685. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5686. EXPECT_EQ(true, res->has_header("Content-Range"));
  5687. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5688. EXPECT_EQ(std::string("a"), res->body);
  5689. }
  5690. TEST_F(ServerTest, GetWithRange4) {
  5691. auto res = cli_.Get("/with-range", Headers{
  5692. make_range_header({{-1, 2}}),
  5693. {"Accept-Encoding", ""},
  5694. });
  5695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5696. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5697. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5698. EXPECT_EQ(true, res->has_header("Content-Range"));
  5699. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5700. EXPECT_EQ(std::string("fg"), res->body);
  5701. }
  5702. TEST_F(ServerTest, GetWithRange5) {
  5703. auto res = cli_.Get("/with-range", Headers{
  5704. make_range_header({{0, 5}}),
  5705. {"Accept-Encoding", ""},
  5706. });
  5707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5708. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5709. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5710. EXPECT_EQ(true, res->has_header("Content-Range"));
  5711. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5712. EXPECT_EQ(std::string("abcdef"), res->body);
  5713. }
  5714. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5715. auto res =
  5716. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5718. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5719. }
  5720. TEST_F(ServerTest, GetWithRangeMultipart) {
  5721. auto res =
  5722. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5724. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5725. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5726. EXPECT_EQ(false, res->has_header("Content-Range"));
  5727. EXPECT_EQ(267U, res->body.size());
  5728. }
  5729. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5730. auto res = cli_.Get("/with-range",
  5731. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5733. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5734. }
  5735. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5736. auto res = cli_.Get("/with-range-customized-response",
  5737. Headers{{make_range_header({{1, 2}})}});
  5738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5739. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5740. EXPECT_EQ(true, res->has_header("Content-Length"));
  5741. EXPECT_EQ(false, res->has_header("Content-Range"));
  5742. EXPECT_EQ(JSON_DATA, res->body);
  5743. }
  5744. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5745. auto res = cli_.Get("/with-range-customized-response",
  5746. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5748. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5749. EXPECT_EQ(true, res->has_header("Content-Length"));
  5750. EXPECT_EQ(false, res->has_header("Content-Range"));
  5751. EXPECT_EQ(JSON_DATA, res->body);
  5752. }
  5753. TEST_F(ServerTest, Issue1772) {
  5754. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5756. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5757. }
  5758. TEST_F(ServerTest, Issue609) {
  5759. auto res = cli_.Delete("/issue609");
  5760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5761. EXPECT_EQ(StatusCode::OK_200, res->status);
  5762. EXPECT_EQ(std::string("ok"), res->body);
  5763. }
  5764. TEST_F(ServerTest, GetStreamedChunked) {
  5765. auto res = cli_.Get("/streamed-chunked");
  5766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5767. EXPECT_EQ(StatusCode::OK_200, res->status);
  5768. EXPECT_EQ(std::string("123456789"), res->body);
  5769. }
  5770. TEST_F(ServerTest, GetStreamedChunked2) {
  5771. auto res = cli_.Get("/streamed-chunked2");
  5772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5773. EXPECT_EQ(StatusCode::OK_200, res->status);
  5774. EXPECT_EQ(std::string("123456789"), res->body);
  5775. }
  5776. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5777. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5779. EXPECT_EQ(StatusCode::OK_200, res->status);
  5780. EXPECT_EQ(std::string("123456789"), res->body);
  5781. EXPECT_TRUE(res->has_header("Trailer"));
  5782. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5783. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5784. // Trailers are now stored separately from headers (security fix)
  5785. EXPECT_EQ(2U, res->trailers.size());
  5786. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5787. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5788. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5789. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5790. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5791. // Verify trailers are NOT in headers (security verification)
  5792. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5793. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5794. }
  5795. TEST_F(ServerTest, LargeChunkedPost) {
  5796. Request req;
  5797. req.method = "POST";
  5798. req.path = "/large-chunked";
  5799. std::string host_and_port;
  5800. host_and_port += HOST;
  5801. host_and_port += ":";
  5802. host_and_port += std::to_string(PORT);
  5803. req.headers.emplace("Host", host_and_port.c_str());
  5804. req.headers.emplace("Accept", "*/*");
  5805. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5806. req.headers.emplace("Content-Type", "text/plain");
  5807. req.headers.emplace("Content-Length", "0");
  5808. req.headers.emplace("Transfer-Encoding", "chunked");
  5809. std::string long_string(30 * 1024u, 'a');
  5810. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5811. // Attempt to make a large enough post to exceed OS buffers, to test that
  5812. // the server handles short reads if the full chunk data isn't available.
  5813. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5814. auto res = std::make_shared<Response>();
  5815. auto error = Error::Success;
  5816. auto ret = cli_.send(req, *res, error);
  5817. ASSERT_TRUE(ret);
  5818. EXPECT_EQ(StatusCode::OK_200, res->status);
  5819. }
  5820. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5821. auto res = cli_.Get("/remote_addr");
  5822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5823. EXPECT_EQ(StatusCode::OK_200, res->status);
  5824. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5825. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5826. }
  5827. TEST_F(ServerTest, GetMethodLocalAddr) {
  5828. auto res = cli_.Get("/local_addr");
  5829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5830. EXPECT_EQ(StatusCode::OK_200, res->status);
  5831. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5832. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5833. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5834. }
  5835. TEST_F(ServerTest, HTTPResponseSplitting) {
  5836. auto res = cli_.Get("/http_response_splitting");
  5837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5838. EXPECT_EQ(StatusCode::OK_200, res->status);
  5839. }
  5840. TEST_F(ServerTest, SlowRequest) {
  5841. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5842. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5843. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5844. }
  5845. #if 0
  5846. TEST_F(ServerTest, SlowPost) {
  5847. char buffer[64 * 1024];
  5848. memset(buffer, 0x42, sizeof(buffer));
  5849. auto res = cli_.Post(
  5850. "/slowpost", 64 * 1024 * 1024,
  5851. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5852. auto ret = sink.write(buffer, sizeof(buffer));
  5853. EXPECT_TRUE(ret);
  5854. return true;
  5855. },
  5856. "text/plain");
  5857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5858. EXPECT_EQ(StatusCode::OK_200, res->status);
  5859. }
  5860. TEST_F(ServerTest, SlowPostFail) {
  5861. char buffer[64 * 1024];
  5862. memset(buffer, 0x42, sizeof(buffer));
  5863. cli_.set_write_timeout(std::chrono::seconds(0));
  5864. auto res = cli_.Post(
  5865. "/slowpost", 64 * 1024 * 1024,
  5866. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5867. sink.write(buffer, sizeof(buffer));
  5868. return true;
  5869. },
  5870. "text/plain");
  5871. ASSERT_TRUE(!res);
  5872. EXPECT_EQ(Error::Write, res.error());
  5873. }
  5874. #endif
  5875. TEST_F(ServerTest, Put) {
  5876. auto res = cli_.Put("/put", "PUT", "text/plain");
  5877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5878. EXPECT_EQ(StatusCode::OK_200, res->status);
  5879. EXPECT_EQ("PUT", res->body);
  5880. }
  5881. TEST_F(ServerTest, PutWithContentProvider) {
  5882. auto res = cli_.Put(
  5883. "/put", 3,
  5884. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5885. sink.os << "PUT";
  5886. return true;
  5887. },
  5888. "text/plain");
  5889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5890. EXPECT_EQ(StatusCode::OK_200, res->status);
  5891. EXPECT_EQ("PUT", res->body);
  5892. }
  5893. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5894. auto res = cli_.Post(
  5895. "/post", 42,
  5896. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5897. return false;
  5898. },
  5899. "text/plain");
  5900. ASSERT_TRUE(!res);
  5901. EXPECT_EQ(Error::Canceled, res.error());
  5902. }
  5903. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5904. auto res = cli_.Put(
  5905. "/put",
  5906. [](size_t /*offset*/, DataSink &sink) {
  5907. sink.os << "PUT";
  5908. sink.done();
  5909. return true;
  5910. },
  5911. "text/plain");
  5912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5913. EXPECT_EQ(StatusCode::OK_200, res->status);
  5914. EXPECT_EQ("PUT", res->body);
  5915. }
  5916. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5917. auto res = cli_.Post(
  5918. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5919. "text/plain");
  5920. ASSERT_TRUE(!res);
  5921. EXPECT_EQ(Error::Canceled, res.error());
  5922. }
  5923. TEST_F(ServerTest, PostLoopBack) {
  5924. std::string body;
  5925. auto res = cli_.Post(
  5926. "/post-loopback", 9,
  5927. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5928. EXPECT_EQ(9u, length);
  5929. sink.write("123", 3);
  5930. sink.write("456", 3);
  5931. sink.write("789", 3);
  5932. return true;
  5933. },
  5934. "text/plain",
  5935. [&body](const char *data, size_t data_length) {
  5936. body.append(data, data_length);
  5937. return true;
  5938. });
  5939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5940. EXPECT_EQ(StatusCode::OK_200, res->status);
  5941. EXPECT_EQ("123456789", body);
  5942. }
  5943. TEST_F(ServerTest, PutLoopBack) {
  5944. std::string body;
  5945. auto res = cli_.Put(
  5946. "/put-loopback", 9,
  5947. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5948. EXPECT_EQ(9u, length);
  5949. sink.write("123", 3);
  5950. sink.write("456", 3);
  5951. sink.write("789", 3);
  5952. return true;
  5953. },
  5954. "text/plain",
  5955. [&body](const char *data, size_t data_length) {
  5956. body.append(data, data_length);
  5957. return true;
  5958. });
  5959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5960. EXPECT_EQ(StatusCode::OK_200, res->status);
  5961. EXPECT_EQ("123456789", body);
  5962. }
  5963. TEST_F(ServerTest, PatchLoopBack) {
  5964. std::string body;
  5965. auto res = cli_.Patch(
  5966. "/patch-loopback", 9,
  5967. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5968. EXPECT_EQ(9u, length);
  5969. sink.write("123", 3);
  5970. sink.write("456", 3);
  5971. sink.write("789", 3);
  5972. return true;
  5973. },
  5974. "text/plain",
  5975. [&body](const char *data, size_t data_length) {
  5976. body.append(data, data_length);
  5977. return true;
  5978. });
  5979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5980. EXPECT_EQ(StatusCode::OK_200, res->status);
  5981. EXPECT_EQ("123456789", body);
  5982. }
  5983. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5984. std::string body;
  5985. auto res = cli_.Post(
  5986. "/post-loopback",
  5987. [](size_t /*offset*/, DataSink &sink) {
  5988. sink.write("123", 3);
  5989. sink.write("456", 3);
  5990. sink.write("789", 3);
  5991. sink.done();
  5992. return true;
  5993. },
  5994. "text/plain",
  5995. [&body](const char *data, size_t data_length) {
  5996. body.append(data, data_length);
  5997. return true;
  5998. });
  5999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. EXPECT_EQ("123456789", body);
  6002. }
  6003. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6004. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6005. cli_.set_compress(true);
  6006. auto res = cli_.Put(
  6007. "/put", 3,
  6008. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6009. sink.os << "PUT";
  6010. return true;
  6011. },
  6012. "text/plain");
  6013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6014. EXPECT_EQ(StatusCode::OK_200, res->status);
  6015. EXPECT_EQ("PUT", res->body);
  6016. }
  6017. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6018. cli_.set_compress(true);
  6019. auto res = cli_.Post(
  6020. "/post", 42,
  6021. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6022. return false;
  6023. },
  6024. "text/plain");
  6025. ASSERT_TRUE(!res);
  6026. EXPECT_EQ(Error::Canceled, res.error());
  6027. }
  6028. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6029. cli_.set_compress(true);
  6030. auto res = cli_.Put(
  6031. "/put",
  6032. [](size_t /*offset*/, DataSink &sink) {
  6033. sink.os << "PUT";
  6034. sink.done();
  6035. return true;
  6036. },
  6037. "text/plain");
  6038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6039. EXPECT_EQ(StatusCode::OK_200, res->status);
  6040. EXPECT_EQ("PUT", res->body);
  6041. }
  6042. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6043. cli_.set_compress(true);
  6044. auto res = cli_.Post(
  6045. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6046. "text/plain");
  6047. ASSERT_TRUE(!res);
  6048. EXPECT_EQ(Error::Canceled, res.error());
  6049. }
  6050. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6051. cli_.set_compress(true);
  6052. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6054. EXPECT_EQ(StatusCode::OK_200, res->status);
  6055. EXPECT_EQ(LARGE_DATA, res->body);
  6056. }
  6057. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6058. #ifdef CPPHTTPLIB_SSL_ENABLED
  6059. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6060. Client cli(s.c_str());
  6061. cli.enable_server_certificate_verification(false);
  6062. #else
  6063. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6064. Client cli(s.c_str());
  6065. #endif
  6066. cli.set_compress(true);
  6067. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. EXPECT_EQ(StatusCode::OK_200, res->status);
  6070. EXPECT_EQ(LARGE_DATA, res->body);
  6071. // The compressed size should be less than a 10th of the original. May vary
  6072. // depending on the zlib library.
  6073. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6074. static_cast<uint64_t>(10 * 1024 * 1024));
  6075. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6076. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6077. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6078. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6079. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6080. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6081. #endif
  6082. }
  6083. TEST_F(ServerTest, PutContentWithDeflate) {
  6084. cli_.set_compress(false);
  6085. Headers headers;
  6086. headers.emplace("Content-Encoding", "deflate");
  6087. // PUT in deflate format:
  6088. auto res = cli_.Put("/put", headers,
  6089. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6091. EXPECT_EQ(StatusCode::OK_200, res->status);
  6092. EXPECT_EQ("PUT", res->body);
  6093. }
  6094. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6095. Headers headers;
  6096. headers.emplace("Accept-Encoding", "gzip, deflate");
  6097. auto res = cli_.Get("/streamed-chunked", headers);
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::OK_200, res->status);
  6100. EXPECT_EQ(std::string("123456789"), res->body);
  6101. }
  6102. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6103. Headers headers;
  6104. headers.emplace("Accept-Encoding", "gzip, deflate");
  6105. auto res = cli_.Get("/streamed-chunked2", headers);
  6106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6107. EXPECT_EQ(StatusCode::OK_200, res->status);
  6108. EXPECT_EQ(std::string("123456789"), res->body);
  6109. }
  6110. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6111. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6113. EXPECT_EQ(StatusCode::OK_200, res->status);
  6114. }
  6115. TEST(GzipDecompressor, ChunkedDecompression) {
  6116. std::string data;
  6117. for (size_t i = 0; i < 32 * 1024; ++i) {
  6118. data.push_back(static_cast<char>('a' + i % 26));
  6119. }
  6120. std::string compressed_data;
  6121. {
  6122. httplib::detail::gzip_compressor compressor;
  6123. bool result = compressor.compress(
  6124. data.data(), data.size(),
  6125. /*last=*/true,
  6126. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6127. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6128. compressed_data_size);
  6129. return true;
  6130. });
  6131. ASSERT_TRUE(result);
  6132. }
  6133. std::string decompressed_data;
  6134. {
  6135. httplib::detail::gzip_decompressor decompressor;
  6136. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6137. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6138. size_t chunk_size = 130;
  6139. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6140. chunk_begin += chunk_size) {
  6141. size_t current_chunk_size =
  6142. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6143. bool result = decompressor.decompress(
  6144. compressed_data.data() + chunk_begin, current_chunk_size,
  6145. [&](const char *decompressed_data_chunk,
  6146. size_t decompressed_data_chunk_size) {
  6147. decompressed_data.insert(decompressed_data.size(),
  6148. decompressed_data_chunk,
  6149. decompressed_data_chunk_size);
  6150. return true;
  6151. });
  6152. ASSERT_TRUE(result);
  6153. }
  6154. }
  6155. ASSERT_EQ(data, decompressed_data);
  6156. }
  6157. TEST(GzipDecompressor, DeflateDecompression) {
  6158. std::string original_text = "Raw deflate without gzip";
  6159. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6160. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6161. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6162. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6163. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6164. std::string decompressed_data;
  6165. {
  6166. httplib::detail::gzip_decompressor decompressor;
  6167. bool result = decompressor.decompress(
  6168. compressed_data.data(), compressed_data.size(),
  6169. [&](const char *decompressed_data_chunk,
  6170. size_t decompressed_data_chunk_size) {
  6171. decompressed_data.insert(decompressed_data.size(),
  6172. decompressed_data_chunk,
  6173. decompressed_data_chunk_size);
  6174. return true;
  6175. });
  6176. ASSERT_TRUE(result);
  6177. }
  6178. ASSERT_EQ(original_text, decompressed_data);
  6179. }
  6180. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6181. std::string original_text = "Raw deflate without gzip";
  6182. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6183. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6184. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6185. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6186. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6187. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6188. std::string decompressed_data;
  6189. {
  6190. httplib::detail::gzip_decompressor decompressor;
  6191. bool result = decompressor.decompress(
  6192. compressed_data.data(), compressed_data.size(),
  6193. [&](const char *decompressed_data_chunk,
  6194. size_t decompressed_data_chunk_size) {
  6195. decompressed_data.insert(decompressed_data.size(),
  6196. decompressed_data_chunk,
  6197. decompressed_data_chunk_size);
  6198. return true;
  6199. });
  6200. ASSERT_TRUE(result);
  6201. }
  6202. ASSERT_EQ(original_text, decompressed_data);
  6203. }
  6204. #endif
  6205. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6206. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6207. Headers headers;
  6208. headers.emplace("Accept-Encoding", "br");
  6209. auto res = cli_.Get("/streamed-chunked", headers);
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. EXPECT_EQ(StatusCode::OK_200, res->status);
  6212. EXPECT_EQ(std::string("123456789"), res->body);
  6213. }
  6214. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6215. Headers headers;
  6216. headers.emplace("Accept-Encoding", "br");
  6217. auto res = cli_.Get("/streamed-chunked2", headers);
  6218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6219. EXPECT_EQ(StatusCode::OK_200, res->status);
  6220. EXPECT_EQ(std::string("123456789"), res->body);
  6221. }
  6222. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6223. cli_.set_compress(true);
  6224. auto res = cli_.Put(
  6225. "/put", 3,
  6226. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6227. sink.os << "PUT";
  6228. return true;
  6229. },
  6230. "text/plain");
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. EXPECT_EQ(StatusCode::OK_200, res->status);
  6233. EXPECT_EQ("PUT", res->body);
  6234. }
  6235. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6236. cli_.set_compress(true);
  6237. auto res = cli_.Put(
  6238. "/put",
  6239. [](size_t /*offset*/, DataSink &sink) {
  6240. sink.os << "PUT";
  6241. sink.done();
  6242. return true;
  6243. },
  6244. "text/plain");
  6245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6246. EXPECT_EQ(StatusCode::OK_200, res->status);
  6247. EXPECT_EQ("PUT", res->body);
  6248. }
  6249. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6250. cli_.set_compress(true);
  6251. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6253. EXPECT_EQ(StatusCode::OK_200, res->status);
  6254. EXPECT_EQ(LARGE_DATA, res->body);
  6255. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6256. }
  6257. #endif
  6258. TEST_F(ServerTest, Patch) {
  6259. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6261. EXPECT_EQ(StatusCode::OK_200, res->status);
  6262. EXPECT_EQ("PATCH", res->body);
  6263. }
  6264. TEST_F(ServerTest, Delete) {
  6265. auto res = cli_.Delete("/delete");
  6266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6267. EXPECT_EQ(StatusCode::OK_200, res->status);
  6268. EXPECT_EQ("DELETE", res->body);
  6269. }
  6270. TEST_F(ServerTest, DeleteContentReceiver) {
  6271. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6273. EXPECT_EQ(StatusCode::OK_200, res->status);
  6274. EXPECT_EQ("content", res->body);
  6275. }
  6276. TEST_F(ServerTest, Options) {
  6277. auto res = cli_.Options("*");
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. EXPECT_EQ(StatusCode::OK_200, res->status);
  6280. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6281. EXPECT_TRUE(res->body.empty());
  6282. }
  6283. TEST_F(ServerTest, URL) {
  6284. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6286. EXPECT_EQ(StatusCode::OK_200, res->status);
  6287. }
  6288. TEST_F(ServerTest, ArrayParam) {
  6289. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. EXPECT_EQ(StatusCode::OK_200, res->status);
  6292. }
  6293. TEST_F(ServerTest, ArrayParamValues) {
  6294. auto res =
  6295. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6297. EXPECT_EQ(StatusCode::OK_200, res->status);
  6298. }
  6299. TEST_F(ServerTest, NoMultipleHeaders) {
  6300. Headers headers = {{"Content-Length", "5"}};
  6301. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6302. "text/plain");
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::OK_200, res->status);
  6305. }
  6306. TEST_F(ServerTest, PostContentReceiver) {
  6307. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6309. ASSERT_EQ(StatusCode::OK_200, res->status);
  6310. ASSERT_EQ("content", res->body);
  6311. }
  6312. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6313. UploadFormDataItems items = {
  6314. {"text1", "text default", "", ""},
  6315. {"text2", "aωb", "", ""},
  6316. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6317. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6318. {"file3", "", "", "application/octet-stream"},
  6319. };
  6320. auto res = cli_.Post("/content_receiver", items);
  6321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6322. EXPECT_EQ(StatusCode::OK_200, res->status);
  6323. }
  6324. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6325. UploadFormDataItems items = {
  6326. {"text1", "text default", "", ""},
  6327. {"text2", "aωb", "", ""},
  6328. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6329. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6330. {"file3", "", "", "application/octet-stream"},
  6331. };
  6332. auto boundary = std::string("+++++");
  6333. std::string body;
  6334. for (const auto &item : items) {
  6335. body += "--" + boundary + "\r\n";
  6336. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6337. if (!item.filename.empty()) {
  6338. body += "; filename=\"" + item.filename + "\"";
  6339. }
  6340. body += "\r\n";
  6341. if (!item.content_type.empty()) {
  6342. body += "Content-Type: " + item.content_type + "\r\n";
  6343. }
  6344. body += "\r\n";
  6345. body += item.content + "\r\n";
  6346. }
  6347. body += "--" + boundary + "--\r\n";
  6348. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6349. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6351. EXPECT_EQ(StatusCode::OK_200, res->status);
  6352. }
  6353. TEST(MultipartFormDataTest, FieldEscaping) {
  6354. Server svr;
  6355. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6356. const ContentReader &content_reader) {
  6357. ASSERT_TRUE(req.is_multipart_form_data());
  6358. std::vector<FormData> received;
  6359. content_reader(
  6360. [&](const FormData &file) {
  6361. received.push_back(file);
  6362. return true;
  6363. },
  6364. [&](const char *data, size_t data_length) {
  6365. received.back().content.append(data, data_length);
  6366. return true;
  6367. });
  6368. // '"', CR and LF in names and filenames are escaped following the
  6369. // WHATWG HTML standard, so each part still parses as a single part
  6370. // with no injected headers. Content types get CR/LF escaped too,
  6371. // while '"' (legal there, e.g. quoted charset) is preserved.
  6372. ASSERT_EQ(4U, received.size());
  6373. EXPECT_EQ("na%22me", received[0].name);
  6374. EXPECT_EQ("quoted name", received[0].content);
  6375. EXPECT_EQ("file", received[1].name);
  6376. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6377. received[1].filename);
  6378. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6379. EXPECT_EQ("injected", received[1].content);
  6380. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6381. EXPECT_EQ("my%22file.txt", received[2].filename);
  6382. EXPECT_EQ("cr lf name", received[2].content);
  6383. EXPECT_EQ("typed", received[3].name);
  6384. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6385. received[3].content_type);
  6386. EXPECT_EQ("typed content", received[3].content);
  6387. });
  6388. auto port = svr.bind_to_any_port("localhost");
  6389. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6390. auto se = detail::scope_exit([&] {
  6391. svr.stop();
  6392. t.join();
  6393. ASSERT_FALSE(svr.is_running());
  6394. });
  6395. svr.wait_until_ready();
  6396. Client cli("localhost", port);
  6397. UploadFormDataItems items = {
  6398. {"na\"me", "quoted name", "", ""},
  6399. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6400. "application/octet-stream"},
  6401. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6402. {"typed", "typed content", "",
  6403. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6404. };
  6405. auto res = cli.Post("/post", items);
  6406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6407. EXPECT_EQ(StatusCode::OK_200, res->status);
  6408. }
  6409. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6410. const UploadFormDataItems items = {
  6411. {"name1", "Content 1", "", ""},
  6412. {"name2", "Content 2", "file2.txt", "text/plain"},
  6413. };
  6414. Server svr;
  6415. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6416. const ContentReader &content_reader) {
  6417. ASSERT_TRUE(req.is_multipart_form_data());
  6418. std::vector<FormData> received;
  6419. content_reader(
  6420. [&](const FormData &file) {
  6421. received.push_back(file);
  6422. return true;
  6423. },
  6424. [&](const char *data, size_t data_length) {
  6425. received.back().content.append(data, data_length);
  6426. return true;
  6427. });
  6428. ASSERT_EQ(2U, received.size());
  6429. EXPECT_EQ("name1", received[0].name);
  6430. EXPECT_EQ("Content 1", received[0].content);
  6431. EXPECT_EQ("name2", received[1].name);
  6432. EXPECT_EQ("Content 2", received[1].content);
  6433. EXPECT_EQ("file2.txt", received[1].filename);
  6434. EXPECT_EQ("text/plain", received[1].content_type);
  6435. });
  6436. auto port = svr.bind_to_any_port("localhost");
  6437. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6438. auto se = detail::scope_exit([&] {
  6439. svr.stop();
  6440. t.join();
  6441. ASSERT_FALSE(svr.is_running());
  6442. });
  6443. svr.wait_until_ready();
  6444. Client cli("localhost", port);
  6445. // Whole-body serialization with a generated boundary
  6446. {
  6447. MultipartFormDataWriter writer;
  6448. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6449. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6450. writer.content_type());
  6451. auto body = writer.serialize(items);
  6452. EXPECT_EQ(body.size(), writer.content_length(items));
  6453. auto res = cli.Post("/post", body, writer.content_type());
  6454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6455. EXPECT_EQ(StatusCode::OK_200, res->status);
  6456. }
  6457. // Per-part framing with a custom boundary via a content provider
  6458. {
  6459. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6460. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6461. MultipartFormDataWriter writer("custom-boundary_123");
  6462. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6463. std::string body;
  6464. for (const auto &item : items) {
  6465. body += writer.item_begin(item);
  6466. body += item.content;
  6467. body += MultipartFormDataWriter::item_end();
  6468. }
  6469. body += writer.finish();
  6470. EXPECT_EQ(body.size(), writer.content_length(items));
  6471. auto res = cli.Post(
  6472. "/post", body.size(),
  6473. [&](size_t offset, size_t length, DataSink &sink) {
  6474. sink.write(body.data() + offset, length);
  6475. return true;
  6476. },
  6477. writer.content_type());
  6478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6479. EXPECT_EQ(StatusCode::OK_200, res->status);
  6480. }
  6481. }
  6482. TEST_F(ServerTest, PostContentReceiverGzip) {
  6483. cli_.set_compress(true);
  6484. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. ASSERT_EQ(StatusCode::OK_200, res->status);
  6487. ASSERT_EQ("content", res->body);
  6488. }
  6489. TEST_F(ServerTest, PutContentReceiver) {
  6490. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6492. ASSERT_EQ(StatusCode::OK_200, res->status);
  6493. ASSERT_EQ("content", res->body);
  6494. }
  6495. TEST_F(ServerTest, PatchContentReceiver) {
  6496. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6498. ASSERT_EQ(StatusCode::OK_200, res->status);
  6499. ASSERT_EQ("content", res->body);
  6500. }
  6501. template <typename ClientType>
  6502. void TestWithHeadersAndContentReceiver(
  6503. ClientType &cli,
  6504. std::function<Result(ClientType &, const std::string &, const Headers &,
  6505. const std::string &, const std::string &,
  6506. ContentReceiver, DownloadProgress)>
  6507. request_func) {
  6508. Headers headers;
  6509. headers.emplace("X-Custom-Header", "test-value");
  6510. std::string received_body;
  6511. auto res = request_func(
  6512. cli, "/content_receiver", headers, "content", "application/json",
  6513. [&](const char *data, size_t data_length) {
  6514. received_body.append(data, data_length);
  6515. return true;
  6516. },
  6517. nullptr);
  6518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6519. EXPECT_EQ(StatusCode::OK_200, res->status);
  6520. EXPECT_EQ("content", received_body);
  6521. }
  6522. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6523. #ifdef CPPHTTPLIB_SSL_ENABLED
  6524. using ClientT = SSLClient;
  6525. #else
  6526. using ClientT = Client;
  6527. #endif
  6528. TestWithHeadersAndContentReceiver<ClientT>(
  6529. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6530. const std::string &body, const std::string &content_type,
  6531. ContentReceiver receiver, DownloadProgress progress) {
  6532. return cli.Post(path, headers, body, content_type, receiver, progress);
  6533. });
  6534. }
  6535. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6536. #ifdef CPPHTTPLIB_SSL_ENABLED
  6537. using ClientT = SSLClient;
  6538. #else
  6539. using ClientT = Client;
  6540. #endif
  6541. TestWithHeadersAndContentReceiver<ClientT>(
  6542. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6543. const std::string &body, const std::string &content_type,
  6544. ContentReceiver receiver, DownloadProgress progress) {
  6545. return cli.Put(path, headers, body, content_type, receiver, progress);
  6546. });
  6547. }
  6548. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6549. #ifdef CPPHTTPLIB_SSL_ENABLED
  6550. using ClientT = SSLClient;
  6551. #else
  6552. using ClientT = Client;
  6553. #endif
  6554. TestWithHeadersAndContentReceiver<ClientT>(
  6555. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6556. const std::string &body, const std::string &content_type,
  6557. ContentReceiver receiver, DownloadProgress progress) {
  6558. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6559. });
  6560. }
  6561. template <typename ClientType>
  6562. void TestWithHeadersAndContentReceiverWithProgress(
  6563. ClientType &cli,
  6564. std::function<Result(ClientType &, const std::string &, const Headers &,
  6565. const std::string &, const std::string &,
  6566. ContentReceiver, DownloadProgress)>
  6567. request_func) {
  6568. Headers headers;
  6569. headers.emplace("X-Test-Header", "progress-test");
  6570. std::string received_body;
  6571. auto progress_called = false;
  6572. auto res = request_func(
  6573. cli, "/content_receiver", headers, "content", "text/plain",
  6574. [&](const char *data, size_t data_length) {
  6575. received_body.append(data, data_length);
  6576. return true;
  6577. },
  6578. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6579. progress_called = true;
  6580. return true;
  6581. });
  6582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6583. EXPECT_EQ(StatusCode::OK_200, res->status);
  6584. EXPECT_EQ("content", received_body);
  6585. EXPECT_TRUE(progress_called);
  6586. }
  6587. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6588. #ifdef CPPHTTPLIB_SSL_ENABLED
  6589. using ClientT = SSLClient;
  6590. #else
  6591. using ClientT = Client;
  6592. #endif
  6593. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6594. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6595. const std::string &body, const std::string &content_type,
  6596. ContentReceiver receiver, DownloadProgress progress) {
  6597. return cli.Post(path, headers, body, content_type, receiver, progress);
  6598. });
  6599. }
  6600. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6601. #ifdef CPPHTTPLIB_SSL_ENABLED
  6602. using ClientT = SSLClient;
  6603. #else
  6604. using ClientT = Client;
  6605. #endif
  6606. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6607. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6608. const std::string &body, const std::string &content_type,
  6609. ContentReceiver receiver, DownloadProgress progress) {
  6610. return cli.Put(path, headers, body, content_type, receiver, progress);
  6611. });
  6612. }
  6613. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6614. #ifdef CPPHTTPLIB_SSL_ENABLED
  6615. using ClientT = SSLClient;
  6616. #else
  6617. using ClientT = Client;
  6618. #endif
  6619. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6620. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6621. const std::string &body, const std::string &content_type,
  6622. ContentReceiver receiver, DownloadProgress progress) {
  6623. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6624. });
  6625. }
  6626. template <typename ClientType>
  6627. void TestWithHeadersAndContentReceiverError(
  6628. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6629. const Headers &, const std::string &,
  6630. const std::string &, ContentReceiver)>
  6631. request_func) {
  6632. Headers headers;
  6633. headers.emplace("X-Error-Test", "true");
  6634. std::string received_body;
  6635. auto receiver_failed = false;
  6636. auto res =
  6637. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6638. [&](const char *data, size_t data_length) {
  6639. received_body.append(data, data_length);
  6640. receiver_failed = true;
  6641. return false;
  6642. });
  6643. ASSERT_FALSE(res);
  6644. EXPECT_TRUE(receiver_failed);
  6645. }
  6646. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6647. #ifdef CPPHTTPLIB_SSL_ENABLED
  6648. using ClientT = SSLClient;
  6649. #else
  6650. using ClientT = Client;
  6651. #endif
  6652. TestWithHeadersAndContentReceiverError<ClientT>(
  6653. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6654. const std::string &body, const std::string &content_type,
  6655. ContentReceiver receiver) {
  6656. return cli.Post(path, headers, body, content_type, receiver);
  6657. });
  6658. }
  6659. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6660. #ifdef CPPHTTPLIB_SSL_ENABLED
  6661. using ClientT = SSLClient;
  6662. #else
  6663. using ClientT = Client;
  6664. #endif
  6665. TestWithHeadersAndContentReceiverError<ClientT>(
  6666. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6667. const std::string &body, const std::string &content_type,
  6668. ContentReceiver receiver) {
  6669. return cli.Put(path, headers, body, content_type, receiver);
  6670. });
  6671. }
  6672. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6673. #ifdef CPPHTTPLIB_SSL_ENABLED
  6674. using ClientT = SSLClient;
  6675. #else
  6676. using ClientT = Client;
  6677. #endif
  6678. TestWithHeadersAndContentReceiverError<ClientT>(
  6679. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6680. const std::string &body, const std::string &content_type,
  6681. ContentReceiver receiver) {
  6682. return cli.Patch(path, headers, body, content_type, receiver);
  6683. });
  6684. }
  6685. TEST_F(ServerTest, PostQueryStringAndBody) {
  6686. auto res =
  6687. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6689. ASSERT_EQ(StatusCode::OK_200, res->status);
  6690. }
  6691. TEST_F(ServerTest, HTTP2Magic) {
  6692. Request req;
  6693. req.method = "PRI";
  6694. req.path = "*";
  6695. req.body = "SM";
  6696. auto res = std::make_shared<Response>();
  6697. auto error = Error::Success;
  6698. auto ret = cli_.send(req, *res, error);
  6699. ASSERT_TRUE(ret);
  6700. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6701. }
  6702. TEST_F(ServerTest, KeepAlive) {
  6703. auto res = cli_.Get("/hi");
  6704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6705. EXPECT_EQ(StatusCode::OK_200, res->status);
  6706. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6707. EXPECT_EQ("Hello World!", res->body);
  6708. res = cli_.Get("/hi");
  6709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6712. EXPECT_EQ("Hello World!", res->body);
  6713. res = cli_.Get("/hi");
  6714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6715. EXPECT_EQ(StatusCode::OK_200, res->status);
  6716. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6717. EXPECT_EQ("Hello World!", res->body);
  6718. res = cli_.Get("/not-exist");
  6719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6720. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6721. res = cli_.Post("/empty", "", "text/plain");
  6722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6723. EXPECT_EQ(StatusCode::OK_200, res->status);
  6724. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6725. EXPECT_EQ("empty", res->body);
  6726. EXPECT_EQ("close", res->get_header_value("Connection"));
  6727. res = cli_.Post(
  6728. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6729. "text/plain");
  6730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6731. EXPECT_EQ(StatusCode::OK_200, res->status);
  6732. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6733. EXPECT_EQ("empty", res->body);
  6734. cli_.set_keep_alive(false);
  6735. res = cli_.Get("/last-request");
  6736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6737. EXPECT_EQ(StatusCode::OK_200, res->status);
  6738. EXPECT_EQ("close", res->get_header_value("Connection"));
  6739. }
  6740. TEST_F(ServerTest, TooManyRedirect) {
  6741. cli_.set_follow_location(true);
  6742. auto res = cli_.Get("/redirect/0");
  6743. ASSERT_TRUE(!res);
  6744. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6745. }
  6746. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6747. Request req;
  6748. req.method = "FOOBAR";
  6749. req.path = "/hi";
  6750. cli_.set_keep_alive(true);
  6751. auto res = cli_.send(req);
  6752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6753. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6754. EXPECT_EQ("close", res->get_header_value("Connection"));
  6755. EXPECT_FALSE(cli_.is_socket_open());
  6756. }
  6757. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6758. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6759. TEST_F(ServerTest, Gzip) {
  6760. Headers headers;
  6761. headers.emplace("Accept-Encoding", "gzip, deflate");
  6762. auto res = cli_.Get("/compress", headers);
  6763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6764. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6765. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6766. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6767. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6768. "7890123456789012345678901234567890",
  6769. res->body);
  6770. EXPECT_EQ(StatusCode::OK_200, res->status);
  6771. }
  6772. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6773. Headers headers;
  6774. headers.emplace("Accept-Encoding", "gzip, deflate");
  6775. auto res = cli_.Get("/compress-with-charset", headers);
  6776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6777. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6778. EXPECT_EQ("application/json; charset=utf-8",
  6779. res->get_header_value("Content-Type"));
  6780. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6781. "7890123456789012345678901234567890",
  6782. res->body);
  6783. EXPECT_EQ(StatusCode::OK_200, res->status);
  6784. }
  6785. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6786. Headers headers;
  6787. headers.emplace("Accept-Encoding", "");
  6788. auto res = cli_.Get("/compress", headers);
  6789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6790. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6791. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6792. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6793. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6794. "7890123456789012345678901234567890",
  6795. res->body);
  6796. EXPECT_EQ(StatusCode::OK_200, res->status);
  6797. }
  6798. TEST_F(ServerTest, GzipWithContentReceiver) {
  6799. Headers headers;
  6800. headers.emplace("Accept-Encoding", "gzip, deflate");
  6801. std::string body;
  6802. auto res = cli_.Get("/compress", headers,
  6803. [&](const char *data, uint64_t data_length) {
  6804. EXPECT_EQ(100U, data_length);
  6805. body.append(data, data_length);
  6806. return true;
  6807. });
  6808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6809. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6810. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6811. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6812. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6813. "7890123456789012345678901234567890",
  6814. body);
  6815. EXPECT_EQ(StatusCode::OK_200, res->status);
  6816. }
  6817. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6818. Headers headers;
  6819. headers.emplace("Accept-Encoding", "gzip, deflate");
  6820. cli_.set_decompress(false);
  6821. auto res = cli_.Get("/compress", headers);
  6822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6823. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6824. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6825. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6826. EXPECT_EQ(33U, res->body.size());
  6827. EXPECT_EQ(StatusCode::OK_200, res->status);
  6828. }
  6829. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6830. Headers headers;
  6831. headers.emplace("Accept-Encoding", "");
  6832. std::string body;
  6833. auto res = cli_.Get("/compress", headers,
  6834. [&](const char *data, uint64_t data_length) {
  6835. EXPECT_EQ(100U, data_length);
  6836. body.append(data, data_length);
  6837. return true;
  6838. });
  6839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6840. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6841. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6842. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6843. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6844. "7890123456789012345678901234567890",
  6845. body);
  6846. EXPECT_EQ(StatusCode::OK_200, res->status);
  6847. }
  6848. TEST_F(ServerTest, NoGzip) {
  6849. Headers headers;
  6850. headers.emplace("Accept-Encoding", "gzip, deflate");
  6851. auto res = cli_.Get("/nocompress", headers);
  6852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6853. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6854. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6855. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6856. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6857. "7890123456789012345678901234567890",
  6858. res->body);
  6859. EXPECT_EQ(StatusCode::OK_200, res->status);
  6860. }
  6861. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6862. Headers headers;
  6863. headers.emplace("Accept-Encoding", "gzip, deflate");
  6864. std::string body;
  6865. auto res = cli_.Get("/nocompress", headers,
  6866. [&](const char *data, uint64_t data_length) {
  6867. EXPECT_EQ(100U, data_length);
  6868. body.append(data, data_length);
  6869. return true;
  6870. });
  6871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6872. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6873. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6874. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6875. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6876. "7890123456789012345678901234567890",
  6877. body);
  6878. EXPECT_EQ(StatusCode::OK_200, res->status);
  6879. }
  6880. TEST_F(ServerTest, MultipartFormDataGzip) {
  6881. UploadFormDataItems items = {
  6882. {"key1", "test", "", ""},
  6883. {"key2", "--abcdefg123", "", ""},
  6884. };
  6885. cli_.set_compress(true);
  6886. auto res = cli_.Post("/compress-multipart", items);
  6887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6888. EXPECT_EQ(StatusCode::OK_200, res->status);
  6889. }
  6890. #endif
  6891. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6892. TEST_F(ServerTest, Brotli) {
  6893. Headers headers;
  6894. headers.emplace("Accept-Encoding", "br");
  6895. auto res = cli_.Get("/compress", headers);
  6896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6897. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6898. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6899. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6900. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6901. "7890123456789012345678901234567890",
  6902. res->body);
  6903. EXPECT_EQ(StatusCode::OK_200, res->status);
  6904. }
  6905. #endif
  6906. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6907. TEST_F(ServerTest, Zstd) {
  6908. Headers headers;
  6909. headers.emplace("Accept-Encoding", "zstd");
  6910. auto res = cli_.Get("/compress", headers);
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6913. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6914. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6915. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6916. "7890123456789012345678901234567890",
  6917. res->body);
  6918. EXPECT_EQ(StatusCode::OK_200, res->status);
  6919. }
  6920. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6921. Headers headers;
  6922. headers.emplace("Accept-Encoding", "");
  6923. auto res = cli_.Get("/compress", headers);
  6924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6925. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6926. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6927. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6928. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6929. "7890123456789012345678901234567890",
  6930. res->body);
  6931. EXPECT_EQ(StatusCode::OK_200, res->status);
  6932. }
  6933. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6934. Headers headers;
  6935. headers.emplace("Accept-Encoding", "zstd");
  6936. std::string body;
  6937. auto res = cli_.Get("/compress", headers,
  6938. [&](const char *data, uint64_t data_length) {
  6939. EXPECT_EQ(100U, data_length);
  6940. body.append(data, data_length);
  6941. return true;
  6942. });
  6943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6944. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6945. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6946. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6947. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6948. "7890123456789012345678901234567890",
  6949. body);
  6950. EXPECT_EQ(StatusCode::OK_200, res->status);
  6951. }
  6952. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6953. Headers headers;
  6954. headers.emplace("Accept-Encoding", "zstd");
  6955. cli_.set_decompress(false);
  6956. auto res = cli_.Get("/compress", headers);
  6957. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6958. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6959. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6960. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6963. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6964. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6965. EXPECT_EQ(StatusCode::OK_200, res->status);
  6966. ASSERT_EQ(26U, res->body.size());
  6967. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6968. 0);
  6969. }
  6970. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6971. Headers headers;
  6972. headers.emplace("Accept-Encoding", "");
  6973. std::string body;
  6974. auto res = cli_.Get("/compress", headers,
  6975. [&](const char *data, uint64_t data_length) {
  6976. EXPECT_EQ(100U, data_length);
  6977. body.append(data, data_length);
  6978. return true;
  6979. });
  6980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6981. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6982. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6983. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6984. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6985. "7890123456789012345678901234567890",
  6986. body);
  6987. EXPECT_EQ(StatusCode::OK_200, res->status);
  6988. }
  6989. TEST_F(ServerTest, NoZstd) {
  6990. Headers headers;
  6991. headers.emplace("Accept-Encoding", "zstd");
  6992. auto res = cli_.Get("/nocompress", headers);
  6993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6994. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6995. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6996. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6997. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6998. "7890123456789012345678901234567890",
  6999. res->body);
  7000. EXPECT_EQ(StatusCode::OK_200, res->status);
  7001. }
  7002. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7003. Headers headers;
  7004. headers.emplace("Accept-Encoding", "zstd");
  7005. std::string body;
  7006. auto res = cli_.Get("/nocompress", headers,
  7007. [&](const char *data, uint64_t data_length) {
  7008. EXPECT_EQ(100U, data_length);
  7009. body.append(data, data_length);
  7010. return true;
  7011. });
  7012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7013. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7014. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7015. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7016. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7017. "7890123456789012345678901234567890",
  7018. body);
  7019. EXPECT_EQ(StatusCode::OK_200, res->status);
  7020. }
  7021. // TODO: How to enable zstd ??
  7022. TEST_F(ServerTest, MultipartFormDataZstd) {
  7023. UploadFormDataItems items = {
  7024. {"key1", "test", "", ""},
  7025. {"key2", "--abcdefg123", "", ""},
  7026. };
  7027. Headers headers;
  7028. headers.emplace("Accept-Encoding", "zstd");
  7029. cli_.set_compress(true);
  7030. auto res = cli_.Post("/compress-multipart", headers, items);
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::OK_200, res->status);
  7033. }
  7034. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7035. Headers headers;
  7036. headers.emplace("Accept-Encoding", "zstd");
  7037. cli_.set_compress(true);
  7038. auto res = cli_.Put(
  7039. "/put", headers, 3,
  7040. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7041. sink.os << "PUT";
  7042. return true;
  7043. },
  7044. "text/plain");
  7045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7046. EXPECT_EQ(StatusCode::OK_200, res->status);
  7047. EXPECT_EQ("PUT", res->body);
  7048. }
  7049. // Pre-compression logging tests
  7050. TEST_F(ServerTest, PreCompressionLogging) {
  7051. // Test data for compression (matches the actual /compress endpoint content)
  7052. const std::string test_content =
  7053. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7054. "3456789012345678901234567890";
  7055. // Variables to capture logging data
  7056. std::string pre_compression_body;
  7057. std::string pre_compression_content_type;
  7058. std::string pre_compression_content_encoding;
  7059. std::string post_compression_body;
  7060. std::string post_compression_content_type;
  7061. std::string post_compression_content_encoding;
  7062. // Set up pre-compression logger
  7063. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7064. const Response &res) {
  7065. pre_compression_body = res.body;
  7066. pre_compression_content_type = res.get_header_value("Content-Type");
  7067. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7068. });
  7069. // Set up post-compression logger
  7070. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7071. post_compression_body = res.body;
  7072. post_compression_content_type = res.get_header_value("Content-Type");
  7073. post_compression_content_encoding =
  7074. res.get_header_value("Content-Encoding");
  7075. });
  7076. // Test with gzip compression
  7077. Headers headers;
  7078. headers.emplace("Accept-Encoding", "gzip");
  7079. auto res = cli_.Get("/compress", headers);
  7080. // Verify response was compressed
  7081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7082. EXPECT_EQ(StatusCode::OK_200, res->status);
  7083. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7084. // Verify pre-compression logger captured uncompressed content
  7085. EXPECT_EQ(test_content, pre_compression_body);
  7086. EXPECT_EQ("text/plain", pre_compression_content_type);
  7087. EXPECT_TRUE(pre_compression_content_encoding
  7088. .empty()); // No encoding header before compression
  7089. // Verify post-compression logger captured compressed content
  7090. EXPECT_NE(test_content,
  7091. post_compression_body); // Should be different after compression
  7092. EXPECT_EQ("text/plain", post_compression_content_type);
  7093. EXPECT_EQ("gzip", post_compression_content_encoding);
  7094. // Verify compressed content is smaller
  7095. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7096. }
  7097. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7098. const std::string test_content =
  7099. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7100. "3456789012345678901234567890";
  7101. std::string pre_compression_body;
  7102. std::string post_compression_body;
  7103. svr_.set_pre_compression_logger(
  7104. [&](const Request & /*req*/, const Response &res) {
  7105. pre_compression_body = res.body;
  7106. });
  7107. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7108. post_compression_body = res.body;
  7109. });
  7110. Headers headers;
  7111. headers.emplace("Accept-Encoding", "br");
  7112. auto res = cli_.Get("/compress", headers);
  7113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7114. EXPECT_EQ(StatusCode::OK_200, res->status);
  7115. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7116. // Verify pre-compression content is uncompressed
  7117. EXPECT_EQ(test_content, pre_compression_body);
  7118. // Verify post-compression content is compressed
  7119. EXPECT_NE(test_content, post_compression_body);
  7120. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7121. }
  7122. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7123. const std::string test_content =
  7124. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7125. "3456789012345678901234567890";
  7126. std::string pre_compression_body;
  7127. std::string post_compression_body;
  7128. svr_.set_pre_compression_logger(
  7129. [&](const Request & /*req*/, const Response &res) {
  7130. pre_compression_body = res.body;
  7131. });
  7132. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7133. post_compression_body = res.body;
  7134. });
  7135. // Request without compression (use /nocompress endpoint)
  7136. Headers headers;
  7137. auto res = cli_.Get("/nocompress", headers);
  7138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7139. EXPECT_EQ(StatusCode::OK_200, res->status);
  7140. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7141. // Pre-compression logger should not be called when no compression is applied
  7142. EXPECT_TRUE(
  7143. pre_compression_body.empty()); // Pre-compression logger not called
  7144. EXPECT_EQ(
  7145. test_content,
  7146. post_compression_body); // Post-compression logger captures final content
  7147. }
  7148. TEST_F(ServerTest, LoggerSeesContentLength) {
  7149. size_t logged_content_length = 0;
  7150. std::string logged_content_length_header;
  7151. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7152. logged_content_length = res.content_length_;
  7153. logged_content_length_header = res.get_header_value("Content-Length");
  7154. });
  7155. auto res = cli_.Get("/nocompress");
  7156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7157. EXPECT_EQ(StatusCode::OK_200, res->status);
  7158. EXPECT_EQ(res->body.size(), logged_content_length);
  7159. EXPECT_EQ(std::to_string(logged_content_length),
  7160. logged_content_length_header);
  7161. }
  7162. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7163. const std::string test_content =
  7164. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7165. "3456789012345678901234567890";
  7166. std::string pre_compression_body;
  7167. bool pre_logger_called = false;
  7168. // Set only pre-compression logger
  7169. svr_.set_pre_compression_logger(
  7170. [&](const Request & /*req*/, const Response &res) {
  7171. pre_compression_body = res.body;
  7172. pre_logger_called = true;
  7173. });
  7174. Headers headers;
  7175. headers.emplace("Accept-Encoding", "gzip");
  7176. auto res = cli_.Get("/compress", headers);
  7177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7178. EXPECT_EQ(StatusCode::OK_200, res->status);
  7179. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7180. // Verify pre-compression logger was called
  7181. EXPECT_TRUE(pre_logger_called);
  7182. EXPECT_EQ(test_content, pre_compression_body);
  7183. }
  7184. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7185. {
  7186. // Test with Expect: 100-continue header - success case
  7187. // Server returns 100 Continue, client sends body, server returns 200 OK
  7188. Request req;
  7189. req.method = "POST";
  7190. req.path = "/post-large";
  7191. req.set_header("Expect", "100-continue");
  7192. req.body = LARGE_DATA;
  7193. Response res;
  7194. auto error = Error::Success;
  7195. cli_.set_keep_alive(true);
  7196. auto ret = cli_.send(req, res, error);
  7197. EXPECT_TRUE(ret);
  7198. EXPECT_EQ(StatusCode::OK_200, res.status);
  7199. EXPECT_EQ(LARGE_DATA, res.body);
  7200. }
  7201. {
  7202. // Test with Expect: 100-continue header - error case
  7203. // Client should not send the body when server returns an error
  7204. Request req;
  7205. req.method = "POST";
  7206. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7207. req.set_header("Expect", "100-continue");
  7208. req.body = LARGE_DATA;
  7209. Response res;
  7210. auto error = Error::Success;
  7211. auto start = std::chrono::high_resolution_clock::now();
  7212. cli_.set_keep_alive(true);
  7213. auto ret = cli_.send(req, res, error);
  7214. auto end = std::chrono::high_resolution_clock::now();
  7215. auto elapsed =
  7216. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7217. .count();
  7218. // With Expect: 100-continue, request completes successfully but with error
  7219. EXPECT_TRUE(ret);
  7220. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7221. EXPECT_EQ("close", res.get_header_value("Connection"));
  7222. EXPECT_FALSE(cli_.is_socket_open());
  7223. EXPECT_LE(elapsed, 2000);
  7224. }
  7225. {
  7226. // Send an extra GET request to ensure error recovery without hanging
  7227. Request req;
  7228. req.method = "GET";
  7229. req.path = "/hi";
  7230. auto start = std::chrono::high_resolution_clock::now();
  7231. auto res = cli_.send(req);
  7232. auto end = std::chrono::high_resolution_clock::now();
  7233. auto elapsed =
  7234. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7235. .count();
  7236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7237. EXPECT_EQ(StatusCode::OK_200, res->status);
  7238. EXPECT_EQ("Hello World!", res->body);
  7239. EXPECT_LE(elapsed, 500);
  7240. }
  7241. }
  7242. TEST(ZstdDecompressor, ChunkedDecompression) {
  7243. std::string data;
  7244. for (size_t i = 0; i < 32 * 1024; ++i) {
  7245. data.push_back(static_cast<char>('a' + i % 26));
  7246. }
  7247. std::string compressed_data;
  7248. {
  7249. httplib::detail::zstd_compressor compressor;
  7250. bool result = compressor.compress(
  7251. data.data(), data.size(),
  7252. /*last=*/true,
  7253. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7254. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7255. compressed_data_size);
  7256. return true;
  7257. });
  7258. ASSERT_TRUE(result);
  7259. }
  7260. std::string decompressed_data;
  7261. {
  7262. httplib::detail::zstd_decompressor decompressor;
  7263. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7264. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7265. size_t chunk_size = 130;
  7266. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7267. chunk_begin += chunk_size) {
  7268. size_t current_chunk_size =
  7269. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7270. bool result = decompressor.decompress(
  7271. compressed_data.data() + chunk_begin, current_chunk_size,
  7272. [&](const char *decompressed_data_chunk,
  7273. size_t decompressed_data_chunk_size) {
  7274. decompressed_data.insert(decompressed_data.size(),
  7275. decompressed_data_chunk,
  7276. decompressed_data_chunk_size);
  7277. return true;
  7278. });
  7279. ASSERT_TRUE(result);
  7280. }
  7281. }
  7282. ASSERT_EQ(data, decompressed_data);
  7283. }
  7284. TEST(ZstdDecompressor, Decompress) {
  7285. std::string original_text = "Compressed with ZSTD";
  7286. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7287. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7288. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7289. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7290. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7291. std::string decompressed_data;
  7292. {
  7293. httplib::detail::zstd_decompressor decompressor;
  7294. bool result = decompressor.decompress(
  7295. compressed_data.data(), compressed_data.size(),
  7296. [&](const char *decompressed_data_chunk,
  7297. size_t decompressed_data_chunk_size) {
  7298. decompressed_data.insert(decompressed_data.size(),
  7299. decompressed_data_chunk,
  7300. decompressed_data_chunk_size);
  7301. return true;
  7302. });
  7303. ASSERT_TRUE(result);
  7304. }
  7305. ASSERT_EQ(original_text, decompressed_data);
  7306. }
  7307. #endif
  7308. // Sends a raw request to a server listening at HOST:PORT.
  7309. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7310. std::string *resp = nullptr, int port = PORT) {
  7311. auto error = Error::Success;
  7312. auto client_sock = detail::create_client_socket(
  7313. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7314. /*connection_timeout_sec=*/5, 0,
  7315. /*read_timeout_sec=*/5, 0,
  7316. /*write_timeout_sec=*/5, 0, std::string(), error);
  7317. if (client_sock == INVALID_SOCKET) { return false; }
  7318. auto ret = detail::process_client_socket(
  7319. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7320. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7321. if (req.size() !=
  7322. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  7323. return false;
  7324. }
  7325. char buf[512];
  7326. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7327. while (line_reader.getline()) {
  7328. if (resp) { *resp += line_reader.ptr(); }
  7329. }
  7330. return true;
  7331. });
  7332. detail::close_socket(client_sock);
  7333. return ret;
  7334. }
  7335. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7336. Server svr;
  7337. std::string header_value;
  7338. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7339. header_value = req.get_header_value("foo");
  7340. res.set_content("ok", "text/plain");
  7341. });
  7342. thread t = thread([&] { svr.listen(HOST, PORT); });
  7343. auto se = detail::scope_exit([&] {
  7344. svr.stop();
  7345. t.join();
  7346. ASSERT_FALSE(svr.is_running());
  7347. });
  7348. svr.wait_until_ready();
  7349. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7350. // like characters are not treated the same - use vertical tab and escape.
  7351. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7352. "foo: \t \v bar \x1B\t \r\n"
  7353. "Connection: close\r\n"
  7354. "\r\n";
  7355. std::string res;
  7356. ASSERT_TRUE(send_request(5, req, &res));
  7357. EXPECT_EQ(header_value, "");
  7358. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7359. }
  7360. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7361. Server svr;
  7362. std::string received;
  7363. svr.Get("/order", [&](const Request &req, Response &res) {
  7364. received = entries_to_string(req.headers);
  7365. res.set_content("ok", "text/plain");
  7366. });
  7367. auto port = svr.bind_to_any_port(HOST);
  7368. thread t = thread([&] { svr.listen_after_bind(); });
  7369. auto se = detail::scope_exit([&] {
  7370. svr.stop();
  7371. t.join();
  7372. ASSERT_FALSE(svr.is_running());
  7373. });
  7374. svr.wait_until_ready();
  7375. const std::string req = "GET /order HTTP/1.1\r\n"
  7376. "X-First: 1\r\n"
  7377. "X-Dup: a\r\n"
  7378. "X-Second: 2\r\n"
  7379. "X-Dup: b\r\n"
  7380. "Connection: close\r\n"
  7381. "\r\n";
  7382. std::string res;
  7383. ASSERT_TRUE(send_request(5, req, &res, port));
  7384. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7385. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7386. }
  7387. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7388. Server svr;
  7389. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7390. res.set_header("Set-Cookie", "first=1");
  7391. res.set_header("X-Between", "y");
  7392. res.set_header("Set-Cookie", "second=2");
  7393. res.set_content("ok", "text/plain");
  7394. });
  7395. auto port = svr.bind_to_any_port(HOST);
  7396. thread t = thread([&] { svr.listen_after_bind(); });
  7397. auto se = detail::scope_exit([&] {
  7398. svr.stop();
  7399. t.join();
  7400. ASSERT_FALSE(svr.is_running());
  7401. });
  7402. svr.wait_until_ready();
  7403. Client cli(HOST, port);
  7404. auto res = cli.Get("/cookies");
  7405. ASSERT_TRUE(res);
  7406. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7407. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7408. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7409. }
  7410. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7411. Server svr;
  7412. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7413. auto i = new int(0);
  7414. res.set_header("Trailer", "X-Safe, X-Reflected");
  7415. res.set_chunked_content_provider(
  7416. "text/plain",
  7417. [i](size_t /*offset*/, DataSink &sink) {
  7418. if (*i == 0) {
  7419. sink.os << "body";
  7420. } else {
  7421. Headers trailer;
  7422. // A valid trailer that must survive.
  7423. trailer.emplace("X-Safe", "safe");
  7424. // Attacker-controlled value carrying CR/LF (response splitting).
  7425. trailer.emplace("X-Reflected",
  7426. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7427. // Attacker-controlled name carrying CR/LF.
  7428. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7429. sink.done_with_trailer(trailer);
  7430. }
  7431. (*i)++;
  7432. return true;
  7433. },
  7434. [i](bool /*success*/) { delete i; });
  7435. });
  7436. thread t = thread([&] { svr.listen(HOST, PORT); });
  7437. auto se = detail::scope_exit([&] {
  7438. svr.stop();
  7439. t.join();
  7440. ASSERT_FALSE(svr.is_running());
  7441. });
  7442. svr.wait_until_ready();
  7443. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7444. "Host: " + HOST +
  7445. "\r\n"
  7446. "Connection: close\r\n"
  7447. "\r\n";
  7448. std::string res;
  7449. ASSERT_TRUE(send_request(5, req, &res));
  7450. // The injected fields must not appear anywhere in the raw response.
  7451. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7452. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7453. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7454. // Invalid trailers are dropped entirely, matching set_header().
  7455. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7456. // The valid trailer still passes through.
  7457. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7458. }
  7459. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7460. Server svr;
  7461. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7462. // res.headers is a public field an application can populate directly,
  7463. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7464. // A valid header that must survive.
  7465. res.headers.emplace("X-Safe", "safe");
  7466. // Attacker-controlled value carrying CR/LF (response splitting).
  7467. res.headers.emplace("X-Reflected",
  7468. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7469. // Attacker-controlled name carrying CR/LF.
  7470. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7471. res.set_content("body", "text/plain");
  7472. });
  7473. thread t = thread([&] { svr.listen(HOST, PORT); });
  7474. auto se = detail::scope_exit([&] {
  7475. svr.stop();
  7476. t.join();
  7477. ASSERT_FALSE(svr.is_running());
  7478. });
  7479. svr.wait_until_ready();
  7480. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7481. "Host: " + HOST +
  7482. "\r\n"
  7483. "Connection: close\r\n"
  7484. "\r\n";
  7485. std::string res;
  7486. ASSERT_TRUE(send_request(5, req, &res));
  7487. // The injected fields must not appear anywhere in the raw response.
  7488. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7489. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7490. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7491. // Invalid headers are dropped entirely, matching set_header().
  7492. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7493. // The valid header still passes through.
  7494. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7495. }
  7496. // Forward declaration: in split builds split.py strips `inline` and moves the
  7497. // definition into httplib.cc, so detail::write_request_line is not visible from
  7498. // the public httplib.h. Re-declaring it here lets the tests link against the
  7499. // symbol in both header-only and split builds.
  7500. namespace httplib {
  7501. namespace detail {
  7502. ssize_t write_request_line(Stream &strm, const std::string &method,
  7503. const std::string &path);
  7504. } // namespace detail
  7505. } // namespace httplib
  7506. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7507. // A well-formed target is written verbatim.
  7508. {
  7509. detail::BufferStream strm;
  7510. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7511. EXPECT_GT(n, 0);
  7512. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7513. }
  7514. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7515. // otherwise it splits the request line and injects a header or a whole
  7516. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7517. // when path encoding is disabled.
  7518. const std::string evil_targets[] = {
  7519. "/a\r\nInjected: pwned",
  7520. "/a\rInjected",
  7521. "/a\nInjected",
  7522. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7523. };
  7524. for (const auto &evil : evil_targets) {
  7525. detail::BufferStream strm;
  7526. auto n = detail::write_request_line(strm, "GET", evil);
  7527. EXPECT_LT(n, 0);
  7528. EXPECT_TRUE(strm.get_buffer().empty());
  7529. }
  7530. }
  7531. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7532. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7533. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7534. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7535. // client must fail cleanly with Error::Write instead of putting a
  7536. // request-line-less, header-injecting request on the wire.
  7537. Server svr;
  7538. svr.Get("/a", [](const Request &, Response &res) {
  7539. res.set_content("ok", "text/plain");
  7540. });
  7541. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7542. auto se = detail::scope_exit([&] {
  7543. svr.stop();
  7544. thread.join();
  7545. ASSERT_FALSE(svr.is_running());
  7546. });
  7547. svr.wait_until_ready();
  7548. {
  7549. Client cli(HOST, PORT);
  7550. cli.set_path_encode(false);
  7551. // The request is rejected before anything is written, so the connection
  7552. // stays silent and the subsequent response read would otherwise block for
  7553. // the full default read timeout. Shorten it -- the assertion is on the
  7554. // error, not the timeout.
  7555. cli.set_read_timeout(1, 0);
  7556. auto res = cli.Get("/a\r\nInjected: pwned");
  7557. EXPECT_FALSE(res);
  7558. EXPECT_EQ(Error::Write, res.error());
  7559. }
  7560. }
  7561. // Sends a raw request and verifies that there isn't a crash or exception.
  7562. static void test_raw_request(const std::string &req,
  7563. std::string *out = nullptr) {
  7564. Server svr;
  7565. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7566. res.set_content("ok", "text/plain");
  7567. });
  7568. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7569. res.set_content("ok", "text/plain");
  7570. });
  7571. svr.Get("/header_field_value_check",
  7572. [&](const Request & /*req*/, Response &res) {
  7573. res.set_content("ok", "text/plain");
  7574. });
  7575. // Server read timeout must be longer than the client read timeout for the
  7576. // bug to reproduce, probably to force the server to process a request
  7577. // without a trailing blank line.
  7578. const time_t client_read_timeout_sec = 1;
  7579. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7580. bool listen_thread_ok = false;
  7581. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7582. auto se = detail::scope_exit([&] {
  7583. svr.stop();
  7584. t.join();
  7585. ASSERT_FALSE(svr.is_running());
  7586. EXPECT_TRUE(listen_thread_ok);
  7587. });
  7588. svr.wait_until_ready();
  7589. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7590. }
  7591. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7592. // A certain header line causes an exception if the header property is parsed
  7593. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7594. test_raw_request(
  7595. "GET /hi HTTP/1.1\r\n"
  7596. " : "
  7597. " "
  7598. " ");
  7599. }
  7600. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7601. // A certain header line causes an exception if the header property *name* is
  7602. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7603. // greedy matcher and requires backtracking when there are a lot of ":"
  7604. // characters.
  7605. // This occurs with libc++ but not libstdc++.
  7606. test_raw_request(
  7607. "GET /hi HTTP/1.1\r\n"
  7608. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7609. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7610. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7611. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7612. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7613. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7614. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7615. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7616. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7617. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7618. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7619. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7620. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7621. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7622. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7623. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7624. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7625. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7626. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7627. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7628. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7629. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7630. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7631. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7632. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7633. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7634. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7635. "&&&%%%");
  7636. }
  7637. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7638. // Make sure this doesn't crash the server.
  7639. // In a previous version of the header line regex, the "\r" rendered the line
  7640. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7641. // a new position where the leading white space ended and the field value
  7642. // began.
  7643. // The crash occurs with libc++ but not libstdc++.
  7644. test_raw_request("GET /hi HTTP/1.1\r\n"
  7645. "a:" +
  7646. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7647. "\r\n"
  7648. "\r\n");
  7649. }
  7650. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7651. std::string out;
  7652. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7653. "Content-Type: text/plain\r\n"
  7654. "Transfer-Encoding: chunked\r\n"
  7655. "\r\n"
  7656. "nothex\r\n",
  7657. &out);
  7658. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7659. }
  7660. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7661. std::string out;
  7662. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7663. "Content-Type: text/plain\r\n"
  7664. "Transfer-Encoding: chunked\r\n"
  7665. "\r\n"
  7666. "3\r\n"
  7667. "xyz\r\n"
  7668. "NaN\r\n",
  7669. &out);
  7670. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7671. }
  7672. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7673. std::string out;
  7674. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7675. "Content-Type: text/plain\r\n"
  7676. "Transfer-Encoding: chunked\r\n"
  7677. "\r\n"
  7678. // Length is too large for 64 bits.
  7679. "1ffffffffffffffff\r\n"
  7680. "xyz\r\n",
  7681. &out);
  7682. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7683. }
  7684. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7685. test_raw_request("GET /hi HTTP/1.1\r\n"
  7686. "Content-Type: text/plain\r\n\r");
  7687. }
  7688. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7689. std::string out;
  7690. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7691. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7692. }
  7693. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7694. Server svr;
  7695. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7696. EXPECT_TRUE(!req.remote_addr.empty());
  7697. });
  7698. thread t = thread([&] { svr.listen(HOST, PORT); });
  7699. auto se = detail::scope_exit([&] {
  7700. svr.stop();
  7701. t.join();
  7702. ASSERT_FALSE(svr.is_running());
  7703. });
  7704. svr.wait_until_ready();
  7705. // Send an invalid request line to trigger Bad Request
  7706. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7707. std::string out;
  7708. ASSERT_TRUE(send_request(5, bad_req, &out));
  7709. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7710. }
  7711. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7712. std::string out;
  7713. std::string request(
  7714. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7715. test_raw_request(request, &out);
  7716. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7717. }
  7718. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7719. std::string out;
  7720. std::string request(
  7721. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7722. test_raw_request(request, &out);
  7723. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7724. }
  7725. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7726. std::string out;
  7727. std::string request(
  7728. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7729. test_raw_request(request, &out);
  7730. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7731. }
  7732. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7733. std::string out;
  7734. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7735. "Test: \r\n\r\n",
  7736. &out);
  7737. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7738. }
  7739. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7740. Server svr;
  7741. std::string x_custom;
  7742. std::string cookie;
  7743. std::string xff;
  7744. std::string x_unicode;
  7745. std::string x_iis;
  7746. svr.Get("/check", [&](const Request &req, Response &res) {
  7747. x_custom = req.get_header_value("X-Custom");
  7748. cookie = req.get_header_value("Cookie");
  7749. xff = req.get_header_value("X-Forwarded-For");
  7750. x_unicode = req.get_header_value("X-Unicode");
  7751. x_iis = req.get_header_value("X-IIS");
  7752. res.set_content("ok", "text/plain");
  7753. });
  7754. thread t = thread([&] { svr.listen(HOST, PORT); });
  7755. auto se = detail::scope_exit([&] {
  7756. svr.stop();
  7757. t.join();
  7758. ASSERT_FALSE(svr.is_running());
  7759. });
  7760. svr.wait_until_ready();
  7761. const std::string req = "GET /check HTTP/1.1\r\n"
  7762. "Host: localhost\r\n"
  7763. "X-Custom: a%0D%0AInjected: b\r\n"
  7764. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7765. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7766. "X-Unicode: %E3%81%82\r\n"
  7767. "X-IIS: %u00E9\r\n"
  7768. "Connection: close\r\n"
  7769. "\r\n";
  7770. std::string res;
  7771. ASSERT_TRUE(send_request(5, req, &res));
  7772. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7773. // Every value must be returned verbatim (wire form), with no decoding.
  7774. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7775. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7776. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7777. EXPECT_EQ("%E3%81%82", x_unicode);
  7778. EXPECT_EQ("%u00E9", x_iis);
  7779. }
  7780. // Applications that previously relied on automatic percent-decoding can
  7781. // reproduce the old behavior by explicitly calling decode_path_component()
  7782. // or, for RFC 3986 conformance, decode_uri_component().
  7783. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7784. Server svr;
  7785. std::string decoded;
  7786. svr.Get("/check", [&](const Request &req, Response &res) {
  7787. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7788. res.set_content("ok", "text/plain");
  7789. });
  7790. thread t = thread([&] { svr.listen(HOST, PORT); });
  7791. auto se = detail::scope_exit([&] {
  7792. svr.stop();
  7793. t.join();
  7794. ASSERT_FALSE(svr.is_running());
  7795. });
  7796. svr.wait_until_ready();
  7797. const std::string req = "GET /check HTTP/1.1\r\n"
  7798. "Host: localhost\r\n"
  7799. "X-Custom: hello%20world\r\n"
  7800. "Connection: close\r\n"
  7801. "\r\n";
  7802. std::string res;
  7803. ASSERT_TRUE(send_request(5, req, &res));
  7804. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7805. EXPECT_EQ("hello world", decoded);
  7806. }
  7807. // Regression test for #2033. Browsers send Referer values that include
  7808. // percent-encoded characters such as %0A inside the URL. Decoding the
  7809. // header value would either trip the post-decode CR/LF/NUL guard (the
  7810. // original bug, returning 400) or, after that guard was relaxed, silently
  7811. // store a literal LF — both unacceptable. The wire form must round-trip.
  7812. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7813. Server svr;
  7814. std::string referer;
  7815. svr.Get("/check", [&](const Request &req, Response &res) {
  7816. referer = req.get_header_value("Referer");
  7817. res.set_content("ok", "text/plain");
  7818. });
  7819. thread t = thread([&] { svr.listen(HOST, PORT); });
  7820. auto se = detail::scope_exit([&] {
  7821. svr.stop();
  7822. t.join();
  7823. ASSERT_FALSE(svr.is_running());
  7824. });
  7825. svr.wait_until_ready();
  7826. const std::string req = "GET /check HTTP/1.1\r\n"
  7827. "Host: localhost\r\n"
  7828. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7829. "Connection: close\r\n"
  7830. "\r\n";
  7831. std::string res;
  7832. ASSERT_TRUE(send_request(5, req, &res));
  7833. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7834. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7835. }
  7836. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7837. Server svr;
  7838. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7839. res.set_header("Cache-Control", "no-cache");
  7840. res.set_chunked_content_provider(
  7841. "text/event-stream", [](size_t offset, DataSink &sink) {
  7842. std::string s = "data:";
  7843. s += std::to_string(offset);
  7844. s += "\n\n";
  7845. auto ret = sink.write(s.data(), s.size());
  7846. EXPECT_TRUE(ret);
  7847. std::this_thread::sleep_for(std::chrono::seconds(1));
  7848. return true;
  7849. });
  7850. });
  7851. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7852. svr.wait_until_ready();
  7853. Client client(HOST, PORT);
  7854. const Headers headers = {{"Accept", "text/event-stream"}};
  7855. auto get_thread = std::thread([&client, &headers]() {
  7856. auto res = client.Get(
  7857. "/events", headers,
  7858. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7859. });
  7860. auto se = detail::scope_exit([&] {
  7861. svr.stop();
  7862. get_thread.join();
  7863. listen_thread.join();
  7864. ASSERT_FALSE(svr.is_running());
  7865. });
  7866. // Give GET time to get a few messages.
  7867. std::this_thread::sleep_for(std::chrono::seconds(2));
  7868. }
  7869. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7870. httplib::Server svr;
  7871. svr.Post("/hi",
  7872. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7873. res.status = StatusCode::OK_200;
  7874. });
  7875. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7876. svr.wait_until_ready();
  7877. Client cli(HOST, PORT);
  7878. auto res = cli.Post("/hi", "data", "text/plain");
  7879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7880. EXPECT_EQ(StatusCode::OK_200, res->status);
  7881. svr.stop();
  7882. thread.join();
  7883. ASSERT_FALSE(svr.is_running());
  7884. res = cli.Post("/hi", "data", "text/plain");
  7885. ASSERT_FALSE(res);
  7886. }
  7887. TEST(ServerStopTest, ListenFailure) {
  7888. Server svr;
  7889. auto t = thread([&]() {
  7890. auto ret = svr.listen("????", PORT);
  7891. EXPECT_FALSE(ret);
  7892. });
  7893. svr.wait_until_ready();
  7894. svr.stop();
  7895. t.join();
  7896. }
  7897. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7898. TEST(ServerStopTest, Decommision) {
  7899. Server svr;
  7900. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7901. for (int i = 0; i < 4; i++) {
  7902. auto is_even = !(i % 2);
  7903. std::thread t{[&] {
  7904. try {
  7905. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7906. if (is_even) {
  7907. throw std::runtime_error("Some thing that happens to go wrong.");
  7908. }
  7909. svr.listen(HOST, PORT);
  7910. } catch (...) { svr.decommission(); }
  7911. }};
  7912. svr.wait_until_ready();
  7913. // Server is up
  7914. {
  7915. Client cli(HOST, PORT);
  7916. auto res = cli.Get("/hi");
  7917. if (is_even) {
  7918. EXPECT_FALSE(res);
  7919. } else {
  7920. EXPECT_TRUE(res);
  7921. EXPECT_EQ("hi...", res->body);
  7922. }
  7923. }
  7924. svr.stop();
  7925. t.join();
  7926. // Server is down...
  7927. {
  7928. Client cli(HOST, PORT);
  7929. auto res = cli.Get("/hi");
  7930. EXPECT_FALSE(res);
  7931. }
  7932. }
  7933. }
  7934. #endif
  7935. // Helper function for string body upload progress tests
  7936. template <typename SetupHandler, typename ClientCall>
  7937. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7938. ClientCall &&client_call,
  7939. const string &body) {
  7940. Server svr;
  7941. setup_handler(svr);
  7942. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7943. auto se = detail::scope_exit([&] {
  7944. svr.stop();
  7945. t.join();
  7946. });
  7947. svr.wait_until_ready();
  7948. Client cli(HOST, PORT);
  7949. vector<uint64_t> progress_values;
  7950. bool progress_called = false;
  7951. auto res =
  7952. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7953. progress_values.push_back(current);
  7954. progress_called = true;
  7955. return true;
  7956. });
  7957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7958. EXPECT_EQ(200, res->status);
  7959. EXPECT_TRUE(progress_called);
  7960. }
  7961. TEST(UploadProgressTest, PostStringBodyBasic) {
  7962. TestStringBodyUploadProgress(
  7963. [](Server &svr) {
  7964. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7965. res.set_content("received", "text/plain");
  7966. });
  7967. },
  7968. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7969. return cli.Post("/test", body, "text/plain", progress_callback);
  7970. },
  7971. "test data for upload progress");
  7972. }
  7973. TEST(UploadProgressTest, PutStringBodyBasic) {
  7974. TestStringBodyUploadProgress(
  7975. [](Server &svr) {
  7976. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7977. res.set_content("put received", "text/plain");
  7978. });
  7979. },
  7980. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7981. return cli.Put("/test", body, "text/plain", progress_callback);
  7982. },
  7983. "put test data for upload progress");
  7984. }
  7985. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7986. TestStringBodyUploadProgress(
  7987. [](Server &svr) {
  7988. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7989. res.set_content("patch received", "text/plain");
  7990. });
  7991. },
  7992. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7993. return cli.Patch("/test", body, "text/plain", progress_callback);
  7994. },
  7995. "patch test data for upload progress");
  7996. }
  7997. // Helper function for content provider upload progress tests
  7998. template <typename SetupHandler, typename ClientCall>
  7999. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  8000. ClientCall &&client_call) {
  8001. Server svr;
  8002. setup_handler(svr);
  8003. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8004. auto se = detail::scope_exit([&] {
  8005. svr.stop();
  8006. t.join();
  8007. });
  8008. svr.wait_until_ready();
  8009. Client cli(HOST, PORT);
  8010. vector<uint64_t> progress_values;
  8011. auto res =
  8012. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8013. progress_values.push_back(current);
  8014. return true;
  8015. });
  8016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8017. EXPECT_EQ(200, res->status);
  8018. EXPECT_FALSE(progress_values.empty());
  8019. }
  8020. TEST(UploadProgressTest, PostContentProviderProgress) {
  8021. TestContentProviderUploadProgress(
  8022. [](Server &svr) {
  8023. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8024. res.set_content("provider received", "text/plain");
  8025. });
  8026. },
  8027. [](Client &cli, UploadProgress progress_callback) {
  8028. return cli.Post(
  8029. "/test", 10,
  8030. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  8031. sink.os << "test data";
  8032. return true;
  8033. },
  8034. "text/plain", progress_callback);
  8035. });
  8036. }
  8037. // Helper function for multipart upload progress tests
  8038. template <typename SetupHandler, typename ClientCall>
  8039. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  8040. ClientCall &&client_call,
  8041. const string &endpoint) {
  8042. Server svr;
  8043. setup_handler(svr);
  8044. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8045. auto se = detail::scope_exit([&] {
  8046. svr.stop();
  8047. t.join();
  8048. });
  8049. svr.wait_until_ready();
  8050. Client cli(HOST, PORT);
  8051. vector<uint64_t> progress_values;
  8052. UploadFormDataItems items = {
  8053. {"field1", "value1", "", ""},
  8054. {"field2", "longer value for progress tracking test", "", ""},
  8055. {"file1", "file content data for upload progress", "test.txt",
  8056. "text/plain"}};
  8057. auto res = client_call(cli, endpoint, items,
  8058. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8059. progress_values.push_back(current);
  8060. return true;
  8061. });
  8062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8063. EXPECT_EQ(200, res->status);
  8064. EXPECT_FALSE(progress_values.empty());
  8065. }
  8066. TEST(UploadProgressTest, PostMultipartProgress) {
  8067. TestMultipartUploadProgress(
  8068. [](Server &svr) {
  8069. svr.Post("/multipart", [](const Request &req, Response &res) {
  8070. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  8071. res.set_content("multipart received", "text/plain");
  8072. });
  8073. },
  8074. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  8075. UploadProgress progress_callback) {
  8076. return cli.Post(endpoint, items, progress_callback);
  8077. },
  8078. "/multipart");
  8079. }
  8080. // Helper function for basic download progress tests
  8081. template <typename SetupHandler, typename ClientCall>
  8082. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8083. ClientCall &&client_call, const string &endpoint,
  8084. size_t expected_content_size) {
  8085. Server svr;
  8086. setup_handler(svr);
  8087. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8088. auto se = detail::scope_exit([&] {
  8089. svr.stop();
  8090. t.join();
  8091. });
  8092. svr.wait_until_ready();
  8093. Client cli(HOST, PORT);
  8094. vector<uint64_t> progress_values;
  8095. auto res = client_call(cli, endpoint,
  8096. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8097. progress_values.push_back(current);
  8098. return true;
  8099. });
  8100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8101. EXPECT_EQ(200, res->status);
  8102. EXPECT_FALSE(progress_values.empty());
  8103. EXPECT_EQ(expected_content_size, res->body.size());
  8104. }
  8105. TEST(DownloadProgressTest, GetBasic) {
  8106. TestBasicDownloadProgress(
  8107. [](Server &svr) {
  8108. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8109. string content(1000, 'D');
  8110. res.set_content(content, "text/plain");
  8111. });
  8112. },
  8113. [](Client &cli, const string &endpoint,
  8114. DownloadProgress progress_callback) {
  8115. return cli.Get(endpoint, progress_callback);
  8116. },
  8117. "/download", 1000u);
  8118. }
  8119. // Helper function for content receiver download progress tests
  8120. template <typename SetupHandler, typename ClientCall>
  8121. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8122. ClientCall &&client_call,
  8123. const string &endpoint,
  8124. size_t expected_content_size) {
  8125. Server svr;
  8126. setup_handler(svr);
  8127. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8128. auto se = detail::scope_exit([&] {
  8129. svr.stop();
  8130. t.join();
  8131. });
  8132. svr.wait_until_ready();
  8133. Client cli(HOST, PORT);
  8134. vector<uint64_t> progress_values;
  8135. string received_body;
  8136. auto res = client_call(
  8137. cli, endpoint,
  8138. [&](const char *data, size_t data_length) -> bool {
  8139. received_body.append(data, data_length);
  8140. return true;
  8141. },
  8142. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8143. progress_values.push_back(current);
  8144. return true;
  8145. });
  8146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8147. EXPECT_EQ(200, res->status);
  8148. EXPECT_FALSE(progress_values.empty());
  8149. EXPECT_EQ(expected_content_size, received_body.size());
  8150. EXPECT_TRUE(res->body.empty());
  8151. }
  8152. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8153. TestContentReceiverDownloadProgress(
  8154. [](Server &svr) {
  8155. svr.Get("/download-receiver",
  8156. [](const Request & /*req*/, Response &res) {
  8157. string content(2000, 'R');
  8158. res.set_content(content, "text/plain");
  8159. });
  8160. },
  8161. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8162. DownloadProgress progress_callback) {
  8163. return cli.Get(endpoint, content_receiver, progress_callback);
  8164. },
  8165. "/download-receiver", 2000u);
  8166. }
  8167. TEST(StreamingTest, NoContentLengthStreaming) {
  8168. Server svr;
  8169. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8170. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8171. if (offset < 6) {
  8172. sink.os << (offset < 3 ? "a" : "b");
  8173. } else {
  8174. sink.done();
  8175. }
  8176. return true;
  8177. });
  8178. });
  8179. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8180. auto listen_se = detail::scope_exit([&] {
  8181. svr.stop();
  8182. listen_thread.join();
  8183. ASSERT_FALSE(svr.is_running());
  8184. });
  8185. svr.wait_until_ready();
  8186. Client client(HOST, PORT);
  8187. auto get_thread = std::thread([&client]() {
  8188. std::string s;
  8189. auto res =
  8190. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8191. s += std::string(data, len);
  8192. return true;
  8193. });
  8194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8195. EXPECT_EQ(StatusCode::OK_200, res->status);
  8196. EXPECT_EQ("aaabbb", s);
  8197. });
  8198. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8199. // Give GET time to get a few messages.
  8200. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8201. }
  8202. TEST(MountTest, Unmount) {
  8203. Server svr;
  8204. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8205. auto se = detail::scope_exit([&] {
  8206. svr.stop();
  8207. listen_thread.join();
  8208. ASSERT_FALSE(svr.is_running());
  8209. });
  8210. svr.wait_until_ready();
  8211. Client cli("localhost", PORT);
  8212. svr.set_mount_point("/mount2", "./www2");
  8213. auto res = cli.Get("/");
  8214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8215. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8216. res = cli.Get("/mount2/dir/test.html");
  8217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8218. EXPECT_EQ(StatusCode::OK_200, res->status);
  8219. svr.set_mount_point("/", "./www");
  8220. res = cli.Get("/dir/");
  8221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8222. EXPECT_EQ(StatusCode::OK_200, res->status);
  8223. svr.remove_mount_point("/");
  8224. res = cli.Get("/dir/");
  8225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8226. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8227. svr.remove_mount_point("/mount2");
  8228. res = cli.Get("/mount2/dir/test.html");
  8229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8230. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8231. }
  8232. TEST(MountTest, PathSegmentBoundary) {
  8233. Server svr;
  8234. svr.set_mount_point("/mount2", "./www2");
  8235. svr.set_mount_point("/", "./www");
  8236. auto port = svr.bind_to_any_port(HOST);
  8237. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8238. auto se = detail::scope_exit([&] {
  8239. svr.stop();
  8240. listen_thread.join();
  8241. ASSERT_FALSE(svr.is_running());
  8242. });
  8243. svr.wait_until_ready();
  8244. Client cli(HOST, port);
  8245. auto res = cli.Get("/mount2/dir/test.html");
  8246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8247. EXPECT_EQ(StatusCode::OK_200, res->status);
  8248. // "/mount2" must not match part-way through a path segment.
  8249. res = cli.Get("/mount2dir/test.html");
  8250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8251. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8252. // A mount point ending in '/' keeps matching every path below it.
  8253. res = cli.Get("/dir/test.html");
  8254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8255. EXPECT_EQ(StatusCode::OK_200, res->status);
  8256. }
  8257. TEST(MountTest, Redicect) {
  8258. Server svr;
  8259. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8260. auto se = detail::scope_exit([&] {
  8261. svr.stop();
  8262. listen_thread.join();
  8263. ASSERT_FALSE(svr.is_running());
  8264. });
  8265. svr.set_mount_point("/", "./www");
  8266. svr.wait_until_ready();
  8267. Client cli("localhost", PORT);
  8268. auto res = cli.Get("/dir/");
  8269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8270. EXPECT_EQ(StatusCode::OK_200, res->status);
  8271. res = cli.Get("/dir");
  8272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8273. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8274. res = cli.Get("/file");
  8275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8276. EXPECT_EQ(StatusCode::OK_200, res->status);
  8277. res = cli.Get("/file/");
  8278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8279. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8280. cli.set_follow_location(true);
  8281. res = cli.Get("/dir");
  8282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8283. EXPECT_EQ(StatusCode::OK_200, res->status);
  8284. }
  8285. TEST(MountTest, MultibytesPathName) {
  8286. Server svr;
  8287. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8288. auto se = detail::scope_exit([&] {
  8289. svr.stop();
  8290. listen_thread.join();
  8291. ASSERT_FALSE(svr.is_running());
  8292. });
  8293. svr.set_mount_point("/", "./www");
  8294. svr.wait_until_ready();
  8295. Client cli("localhost", PORT);
  8296. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8298. EXPECT_EQ(StatusCode::OK_200, res->status);
  8299. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8300. }
  8301. #ifdef _WIN32
  8302. // Issue #2435: mmap::open() must succeed even when another handle holds
  8303. // the file open for writing (e.g. an active log file).
  8304. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8305. const char *path = "mmap_concurrent_writer_test.txt";
  8306. const char *content = "hello";
  8307. {
  8308. std::ofstream f(path, std::ios::binary);
  8309. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8310. }
  8311. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8312. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8313. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8314. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8315. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8316. detail::mmap m(path);
  8317. ASSERT_TRUE(m.is_open());
  8318. EXPECT_EQ(strlen(content), m.size());
  8319. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8320. }
  8321. #endif
  8322. #ifndef _WIN32
  8323. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8324. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8325. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8326. TEST(MmapTest, FailedMappingIsNotOpen) {
  8327. const char *path = "./mmap_failed_mapping_test_dir";
  8328. ASSERT_EQ(0, ::mkdir(path, 0755));
  8329. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8330. detail::mmap m(path);
  8331. EXPECT_FALSE(m.is_open());
  8332. EXPECT_EQ(0U, m.size());
  8333. EXPECT_NE(static_cast<const void *>(m.data()),
  8334. static_cast<const void *>(MAP_FAILED));
  8335. }
  8336. #endif
  8337. TEST(KeepAliveTest, ReadTimeout) {
  8338. Server svr;
  8339. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8340. std::this_thread::sleep_for(std::chrono::seconds(2));
  8341. res.set_content("a", "text/plain");
  8342. });
  8343. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8344. res.set_content("b", "text/plain");
  8345. });
  8346. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8347. auto se = detail::scope_exit([&] {
  8348. svr.stop();
  8349. listen_thread.join();
  8350. ASSERT_FALSE(svr.is_running());
  8351. });
  8352. svr.wait_until_ready();
  8353. Client cli("localhost", PORT);
  8354. cli.set_keep_alive(true);
  8355. cli.set_read_timeout(std::chrono::seconds(1));
  8356. auto resa = cli.Get("/a");
  8357. ASSERT_FALSE(resa);
  8358. EXPECT_EQ(Error::Read, resa.error());
  8359. auto resb = cli.Get("/b");
  8360. ASSERT_TRUE(resb);
  8361. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8362. EXPECT_EQ("b", resb->body);
  8363. }
  8364. TEST(KeepAliveTest, MaxCount) {
  8365. size_t keep_alive_max_count = 3;
  8366. Server svr;
  8367. svr.set_keep_alive_max_count(keep_alive_max_count);
  8368. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8369. res.set_content("Hello World!", "text/plain");
  8370. });
  8371. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8372. auto se = detail::scope_exit([&] {
  8373. svr.stop();
  8374. listen_thread.join();
  8375. ASSERT_FALSE(svr.is_running());
  8376. });
  8377. svr.wait_until_ready();
  8378. Client cli(HOST, PORT);
  8379. cli.set_keep_alive(true);
  8380. for (size_t i = 0; i < 5; i++) {
  8381. auto result = cli.Get("/hi");
  8382. ASSERT_TRUE(result);
  8383. EXPECT_EQ(StatusCode::OK_200, result->status);
  8384. if (i == keep_alive_max_count - 1) {
  8385. EXPECT_EQ("close", result->get_header_value("Connection"));
  8386. } else {
  8387. EXPECT_FALSE(result->has_header("Connection"));
  8388. }
  8389. }
  8390. }
  8391. TEST(KeepAliveTest, Issue1041) {
  8392. Server svr;
  8393. svr.set_keep_alive_timeout(3);
  8394. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8395. res.set_content("Hello World!", "text/plain");
  8396. });
  8397. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8398. auto se = detail::scope_exit([&] {
  8399. svr.stop();
  8400. listen_thread.join();
  8401. ASSERT_FALSE(svr.is_running());
  8402. });
  8403. svr.wait_until_ready();
  8404. Client cli(HOST, PORT);
  8405. cli.set_keep_alive(true);
  8406. auto result = cli.Get("/hi");
  8407. ASSERT_TRUE(result);
  8408. EXPECT_EQ(StatusCode::OK_200, result->status);
  8409. std::this_thread::sleep_for(std::chrono::seconds(5));
  8410. result = cli.Get("/hi");
  8411. ASSERT_TRUE(result);
  8412. EXPECT_EQ(StatusCode::OK_200, result->status);
  8413. }
  8414. TEST(KeepAliveTest, Issue1959) {
  8415. Server svr;
  8416. svr.set_keep_alive_timeout(5);
  8417. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8418. res.set_content("a", "text/plain");
  8419. });
  8420. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8421. auto se = detail::scope_exit([&] {
  8422. if (!svr.is_running()) return;
  8423. svr.stop();
  8424. listen_thread.join();
  8425. ASSERT_FALSE(svr.is_running());
  8426. });
  8427. svr.wait_until_ready();
  8428. Client cli("localhost", PORT);
  8429. cli.set_keep_alive(true);
  8430. using namespace std::chrono;
  8431. auto start = steady_clock::now();
  8432. cli.Get("/a");
  8433. svr.stop();
  8434. listen_thread.join();
  8435. auto end = steady_clock::now();
  8436. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8437. EXPECT_LT(elapsed, 5000);
  8438. }
  8439. #ifdef CPPHTTPLIB_SSL_ENABLED
  8440. TEST(KeepAliveTest, SSLClientReconnection) {
  8441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8442. ASSERT_TRUE(svr.is_valid());
  8443. svr.set_keep_alive_timeout(1);
  8444. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8445. res.set_content("Hello World!", "text/plain");
  8446. });
  8447. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8448. auto se = detail::scope_exit([&] {
  8449. svr.stop();
  8450. listen_thread.join();
  8451. ASSERT_FALSE(svr.is_running());
  8452. });
  8453. svr.wait_until_ready();
  8454. SSLClient cli(HOST, PORT);
  8455. cli.enable_server_certificate_verification(false);
  8456. cli.set_keep_alive(true);
  8457. auto result = cli.Get("/hi");
  8458. ASSERT_TRUE(result);
  8459. EXPECT_EQ(StatusCode::OK_200, result->status);
  8460. result = cli.Get("/hi");
  8461. ASSERT_TRUE(result);
  8462. EXPECT_EQ(StatusCode::OK_200, result->status);
  8463. std::this_thread::sleep_for(std::chrono::seconds(2));
  8464. // Recoonect
  8465. result = cli.Get("/hi");
  8466. ASSERT_TRUE(result);
  8467. EXPECT_EQ(StatusCode::OK_200, result->status);
  8468. result = cli.Get("/hi");
  8469. ASSERT_TRUE(result);
  8470. EXPECT_EQ(StatusCode::OK_200, result->status);
  8471. }
  8472. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8473. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8474. ASSERT_TRUE(svr.is_valid());
  8475. svr.set_keep_alive_timeout(1);
  8476. std::string content = "reconnect";
  8477. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8478. res.set_content("Hello World!", "text/plain");
  8479. });
  8480. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8481. auto se = detail::scope_exit([&] {
  8482. svr.stop();
  8483. listen_thread.join();
  8484. ASSERT_FALSE(svr.is_running());
  8485. });
  8486. svr.wait_until_ready();
  8487. SSLClient cli(HOST, PORT);
  8488. cli.enable_server_certificate_verification(false);
  8489. cli.set_keep_alive(true);
  8490. auto result = cli.Post(
  8491. "/hi", content.size(),
  8492. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8493. sink.write(content.c_str(), content.size());
  8494. return true;
  8495. },
  8496. "text/plain");
  8497. ASSERT_TRUE(result);
  8498. EXPECT_EQ(200, result->status);
  8499. std::this_thread::sleep_for(std::chrono::seconds(2));
  8500. // Recoonect
  8501. result = cli.Post(
  8502. "/hi", content.size(),
  8503. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8504. sink.write(content.c_str(), content.size());
  8505. return true;
  8506. },
  8507. "text/plain");
  8508. ASSERT_TRUE(result);
  8509. EXPECT_EQ(200, result->status);
  8510. result = cli.Post(
  8511. "/hi", content.size(),
  8512. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8513. sink.write(content.c_str(), content.size());
  8514. return true;
  8515. },
  8516. "text/plain");
  8517. ASSERT_TRUE(result);
  8518. EXPECT_EQ(200, result->status);
  8519. }
  8520. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8521. using namespace httplib::tls;
  8522. {
  8523. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8524. ASSERT_TRUE(svr.is_valid());
  8525. svr.Get("/sni", [&](const Request &req, Response &res) {
  8526. std::string expected = req.sni();
  8527. EXPECT_EQ(expected, req.get_param_value("expected"));
  8528. res.set_content("ok", "text/plain");
  8529. });
  8530. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8531. auto se = detail::scope_exit([&] {
  8532. svr.stop();
  8533. listen_thread.join();
  8534. ASSERT_FALSE(svr.is_running());
  8535. });
  8536. svr.wait_until_ready();
  8537. {
  8538. SSLClient cli("localhost", PORT);
  8539. cli.enable_server_certificate_verification(false);
  8540. auto res = cli.Get("/sni?expected=localhost");
  8541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8542. }
  8543. {
  8544. SSLClient cli("::1", PORT);
  8545. cli.enable_server_certificate_verification(false);
  8546. auto res = cli.Get("/sni?expected=");
  8547. // NOTE: This may fail if the server is listening on IPv4 only
  8548. // (e.g., when localhost resolves to 127.0.0.1 only)
  8549. if (res) {
  8550. EXPECT_EQ(StatusCode::OK_200, res->status);
  8551. } else {
  8552. EXPECT_EQ(Error::Connection, res.error());
  8553. }
  8554. }
  8555. }
  8556. }
  8557. #endif
  8558. TEST(ClientProblemDetectionTest, ContentProvider) {
  8559. Server svr;
  8560. size_t content_length = 1024 * 1024;
  8561. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8562. res.set_content_provider(
  8563. content_length, "text/plain",
  8564. [&](size_t offset, size_t length, DataSink &sink) {
  8565. auto out_len = std::min(length, static_cast<size_t>(1024));
  8566. std::string out(out_len, '@');
  8567. sink.write(out.data(), out_len);
  8568. return offset < 4096;
  8569. },
  8570. [](bool success) { ASSERT_FALSE(success); });
  8571. });
  8572. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8573. res.set_content_provider(
  8574. 0, "text/plain",
  8575. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8576. EXPECT_TRUE(false);
  8577. return true;
  8578. },
  8579. [](bool success) { ASSERT_FALSE(success); });
  8580. });
  8581. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8582. auto se = detail::scope_exit([&] {
  8583. svr.stop();
  8584. listen_thread.join();
  8585. ASSERT_FALSE(svr.is_running());
  8586. });
  8587. svr.wait_until_ready();
  8588. Client cli("localhost", PORT);
  8589. {
  8590. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8591. size_t /*data_length*/) { return false; });
  8592. ASSERT_FALSE(res);
  8593. }
  8594. {
  8595. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8596. size_t /*data_length*/) { return false; });
  8597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8598. }
  8599. }
  8600. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8601. Server svr;
  8602. svr.set_error_handler([](Request const &, Response &res) -> void {
  8603. res.set_chunked_content_provider(
  8604. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8605. sink.os << "hello";
  8606. sink.os << "world";
  8607. sink.done();
  8608. return true;
  8609. });
  8610. });
  8611. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8612. auto se = detail::scope_exit([&] {
  8613. svr.stop();
  8614. listen_thread.join();
  8615. ASSERT_FALSE(svr.is_running());
  8616. });
  8617. svr.wait_until_ready();
  8618. Client cli("localhost", PORT);
  8619. auto res = cli.Get("/");
  8620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8621. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8622. EXPECT_EQ("helloworld", res->body);
  8623. }
  8624. TEST(LongPollingTest, ClientCloseDetection) {
  8625. Server svr;
  8626. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8627. res.set_chunked_content_provider(
  8628. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8629. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8630. sink.os << "hello";
  8631. auto count = 10;
  8632. while (count > 0 && sink.is_writable()) {
  8633. this_thread::sleep_for(chrono::milliseconds(10));
  8634. count--;
  8635. }
  8636. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8637. return true;
  8638. });
  8639. });
  8640. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8641. auto se = detail::scope_exit([&] {
  8642. svr.stop();
  8643. listen_thread.join();
  8644. ASSERT_FALSE(svr.is_running());
  8645. });
  8646. svr.wait_until_ready();
  8647. Client cli("localhost", PORT);
  8648. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8649. EXPECT_EQ("hello", string(data, data_length));
  8650. return false; // close the socket immediately.
  8651. });
  8652. ASSERT_FALSE(res);
  8653. }
  8654. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8655. Server svr;
  8656. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8657. res.set_chunked_content_provider(
  8658. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8659. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8660. sink.os << "hello";
  8661. EXPECT_TRUE(sink.os.good());
  8662. // Wait for the client to close the connection
  8663. auto count = 10;
  8664. while (count > 0 && sink.is_writable()) {
  8665. this_thread::sleep_for(chrono::milliseconds(10));
  8666. count--;
  8667. }
  8668. // After client disconnect, write repeatedly until the socket
  8669. // write actually fails (small writes may be absorbed by the
  8670. // kernel buffer)
  8671. std::string chunk(1024, 'x');
  8672. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8673. sink.os << chunk;
  8674. }
  8675. EXPECT_TRUE(sink.os.fail());
  8676. return true;
  8677. });
  8678. });
  8679. auto port = svr.bind_to_any_port("localhost");
  8680. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8681. auto se = detail::scope_exit([&] {
  8682. svr.stop();
  8683. listen_thread.join();
  8684. ASSERT_FALSE(svr.is_running());
  8685. });
  8686. svr.wait_until_ready();
  8687. Client cli("localhost", port);
  8688. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8689. EXPECT_EQ("hello", string(data, data_length));
  8690. return false; // close the socket immediately.
  8691. });
  8692. ASSERT_FALSE(res);
  8693. }
  8694. TEST(GetWithParametersTest, GetWithParameters) {
  8695. Server svr;
  8696. svr.Get("/", [&](const Request &req, Response &) {
  8697. EXPECT_EQ("world", req.get_param_value("hello"));
  8698. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8699. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8700. });
  8701. svr.Get("/params", [&](const Request &req, Response &) {
  8702. EXPECT_EQ("world", req.get_param_value("hello"));
  8703. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8704. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8705. });
  8706. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8707. EXPECT_EQ("resource-id", req.matches[1]);
  8708. EXPECT_EQ("foo", req.get_param_value("param1"));
  8709. EXPECT_EQ("bar", req.get_param_value("param2"));
  8710. });
  8711. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8712. EXPECT_EQ("user-id", req.path_params.at("id"));
  8713. EXPECT_EQ("foo", req.get_param_value("param1"));
  8714. EXPECT_EQ("bar", req.get_param_value("param2"));
  8715. });
  8716. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8717. auto se = detail::scope_exit([&] {
  8718. svr.stop();
  8719. listen_thread.join();
  8720. ASSERT_FALSE(svr.is_running());
  8721. });
  8722. svr.wait_until_ready();
  8723. {
  8724. Client cli(HOST, PORT);
  8725. Params params;
  8726. params.emplace("hello", "world");
  8727. params.emplace("hello2", "world2");
  8728. params.emplace("hello3", "world3");
  8729. auto res = cli.Get("/", params, Headers{});
  8730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8731. EXPECT_EQ(StatusCode::OK_200, res->status);
  8732. }
  8733. {
  8734. Client cli(HOST, PORT);
  8735. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8737. EXPECT_EQ(StatusCode::OK_200, res->status);
  8738. }
  8739. {
  8740. Client cli(HOST, PORT);
  8741. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8743. EXPECT_EQ(StatusCode::OK_200, res->status);
  8744. }
  8745. {
  8746. Client cli(HOST, PORT);
  8747. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8749. EXPECT_EQ(StatusCode::OK_200, res->status);
  8750. }
  8751. }
  8752. TEST(GetWithParametersTest, GetWithParameters2) {
  8753. Server svr;
  8754. svr.Get("/", [&](const Request &req, Response &res) {
  8755. auto text = req.get_param_value("hello");
  8756. res.set_content(text, "text/plain");
  8757. });
  8758. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8759. auto se = detail::scope_exit([&] {
  8760. svr.stop();
  8761. listen_thread.join();
  8762. ASSERT_FALSE(svr.is_running());
  8763. });
  8764. svr.wait_until_ready();
  8765. Client cli("localhost", PORT);
  8766. Params params;
  8767. params.emplace("hello", "world");
  8768. std::string body;
  8769. auto res = cli.Get("/", params, Headers{},
  8770. [&](const char *data, size_t data_length) {
  8771. body.append(data, data_length);
  8772. return true;
  8773. });
  8774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8775. EXPECT_EQ(StatusCode::OK_200, res->status);
  8776. EXPECT_EQ("world", body);
  8777. }
  8778. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8779. Server svr;
  8780. svr.Get("/search", [&](const Request &req, Response &res) {
  8781. auto q = req.get_param_value("q");
  8782. res.set_content(q, "text/plain");
  8783. });
  8784. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8785. auto se = detail::scope_exit([&] {
  8786. svr.stop();
  8787. listen_thread.join();
  8788. ASSERT_FALSE(svr.is_running());
  8789. });
  8790. svr.wait_until_ready();
  8791. Client cli("localhost", PORT);
  8792. // Verify that Get(path, params) works without requiring Headers argument
  8793. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8795. EXPECT_EQ(StatusCode::OK_200, res->status);
  8796. EXPECT_EQ("cpp-httplib", res->body);
  8797. }
  8798. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8799. auto host = "httpbingo.org";
  8800. auto path = std::string{"/range/32"};
  8801. #ifdef CPPHTTPLIB_SSL_ENABLED
  8802. SSLClient cli(host);
  8803. #else
  8804. Client cli(host);
  8805. #endif
  8806. cli.set_default_headers({make_range_header({{1, 10}})});
  8807. cli.set_connection_timeout(5);
  8808. {
  8809. auto res = cli.Get(path);
  8810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8811. EXPECT_EQ("bcdefghijk", res->body);
  8812. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8813. }
  8814. {
  8815. auto res = cli.Get(path);
  8816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8817. EXPECT_EQ("bcdefghijk", res->body);
  8818. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8819. }
  8820. }
  8821. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8822. Server svr;
  8823. svr.set_default_headers({{"Hello", "World"}});
  8824. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8825. res.set_content("ok", "text/plain");
  8826. });
  8827. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8828. auto se = detail::scope_exit([&] {
  8829. svr.stop();
  8830. listen_thread.join();
  8831. ASSERT_FALSE(svr.is_running());
  8832. });
  8833. svr.wait_until_ready();
  8834. Client cli("localhost", PORT);
  8835. auto res = cli.Get("/");
  8836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8837. EXPECT_EQ(StatusCode::OK_200, res->status);
  8838. EXPECT_EQ("ok", res->body);
  8839. EXPECT_EQ("World", res->get_header_value("Hello"));
  8840. }
  8841. #ifdef CPPHTTPLIB_SSL_ENABLED
  8842. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8844. ASSERT_TRUE(svr.is_valid());
  8845. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8846. std::this_thread::sleep_for(std::chrono::seconds(2));
  8847. res.set_content("a", "text/plain");
  8848. });
  8849. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8850. res.set_content("b", "text/plain");
  8851. });
  8852. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8853. auto se = detail::scope_exit([&] {
  8854. svr.stop();
  8855. listen_thread.join();
  8856. ASSERT_FALSE(svr.is_running());
  8857. });
  8858. svr.wait_until_ready();
  8859. SSLClient cli("localhost", PORT);
  8860. cli.enable_server_certificate_verification(false);
  8861. cli.set_keep_alive(true);
  8862. cli.set_read_timeout(std::chrono::seconds(1));
  8863. auto resa = cli.Get("/a");
  8864. ASSERT_TRUE(!resa);
  8865. EXPECT_EQ(Error::Read, resa.error());
  8866. auto resb = cli.Get("/b");
  8867. ASSERT_TRUE(resb);
  8868. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8869. EXPECT_EQ("b", resb->body);
  8870. }
  8871. #endif
  8872. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8873. protected:
  8874. ServerTestWithAI_PASSIVE()
  8875. : cli_(HOST, PORT)
  8876. #ifdef CPPHTTPLIB_SSL_ENABLED
  8877. ,
  8878. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8879. #endif
  8880. {
  8881. #ifdef CPPHTTPLIB_SSL_ENABLED
  8882. cli_.enable_server_certificate_verification(false);
  8883. #endif
  8884. }
  8885. virtual void SetUp() {
  8886. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8887. res.set_content("Hello World!", "text/plain");
  8888. });
  8889. t_ = thread(
  8890. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8891. svr_.wait_until_ready();
  8892. }
  8893. virtual void TearDown() {
  8894. svr_.stop();
  8895. t_.join();
  8896. }
  8897. #ifdef CPPHTTPLIB_SSL_ENABLED
  8898. SSLClient cli_;
  8899. SSLServer svr_;
  8900. #else
  8901. Client cli_;
  8902. Server svr_;
  8903. #endif
  8904. thread t_;
  8905. };
  8906. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8907. auto res = cli_.Get("/hi");
  8908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8909. EXPECT_EQ(StatusCode::OK_200, res->status);
  8910. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8911. EXPECT_EQ("Hello World!", res->body);
  8912. }
  8913. class ServerUpDownTest : public ::testing::Test {
  8914. protected:
  8915. ServerUpDownTest() : cli_(HOST, PORT) {}
  8916. virtual void SetUp() {
  8917. t_ = thread([&]() {
  8918. svr_.bind_to_any_port(HOST);
  8919. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8920. ASSERT_TRUE(svr_.listen_after_bind());
  8921. });
  8922. svr_.wait_until_ready();
  8923. }
  8924. virtual void TearDown() {
  8925. svr_.stop();
  8926. t_.join();
  8927. }
  8928. Client cli_;
  8929. Server svr_;
  8930. thread t_;
  8931. };
  8932. TEST_F(ServerUpDownTest, QuickStartStop) {
  8933. // Should not crash, especially when run with
  8934. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8935. }
  8936. class PayloadMaxLengthTest : public ::testing::Test {
  8937. protected:
  8938. PayloadMaxLengthTest()
  8939. : cli_(HOST, PORT)
  8940. #ifdef CPPHTTPLIB_SSL_ENABLED
  8941. ,
  8942. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8943. #endif
  8944. {
  8945. #ifdef CPPHTTPLIB_SSL_ENABLED
  8946. cli_.enable_server_certificate_verification(false);
  8947. #endif
  8948. }
  8949. virtual void SetUp() {
  8950. svr_.set_payload_max_length(8);
  8951. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8952. res.set_content("test", "text/plain");
  8953. });
  8954. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8955. svr_.wait_until_ready();
  8956. }
  8957. virtual void TearDown() {
  8958. svr_.stop();
  8959. t_.join();
  8960. }
  8961. #ifdef CPPHTTPLIB_SSL_ENABLED
  8962. SSLClient cli_;
  8963. SSLServer svr_;
  8964. #else
  8965. Client cli_;
  8966. Server svr_;
  8967. #endif
  8968. thread t_;
  8969. };
  8970. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8971. auto res = cli_.Post("/test", "123456789", "text/plain");
  8972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8973. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8974. res = cli_.Post("/test", "12345678", "text/plain");
  8975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8976. EXPECT_EQ(StatusCode::OK_200, res->status);
  8977. }
  8978. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8979. // Test chunked encoding with payload exceeding the 8-byte limit
  8980. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8981. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8983. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8984. }
  8985. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8986. // Test chunked encoding with payload within the 8-byte limit
  8987. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8988. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8990. EXPECT_EQ(StatusCode::OK_200, res->status);
  8991. }
  8992. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8993. // Test using send_request to send chunked data exceeding payload limit
  8994. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8995. "Host: " +
  8996. std::string(HOST) + ":" + std::to_string(PORT) +
  8997. "\r\n"
  8998. "Transfer-Encoding: chunked\r\n"
  8999. "Connection: close\r\n"
  9000. "\r\n"
  9001. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  9002. "0123456789\r\n"
  9003. "0\r\n" // End chunk
  9004. "\r\n";
  9005. std::string response;
  9006. bool result = send_request(1, chunked_request, &response);
  9007. if (!result) {
  9008. // If send_request fails, it might be because the server closed the
  9009. // connection due to payload limit enforcement, which is acceptable
  9010. SUCCEED()
  9011. << "Server rejected oversized chunked request (connection closed)";
  9012. } else {
  9013. // If we got a response, check if it's an error response or connection was
  9014. // closed early Short response length indicates connection was closed due to
  9015. // payload limit
  9016. if (response.length() <= 10) {
  9017. SUCCEED() << "Server closed connection for oversized chunked request";
  9018. } else {
  9019. // Check for error status codes
  9020. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9021. response.find("Payload Too Large") != std::string::npos ||
  9022. response.find("400") != std::string::npos);
  9023. }
  9024. }
  9025. }
  9026. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  9027. // Test request without Content-Length header exceeding payload limit
  9028. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9029. "Host: " +
  9030. std::string(HOST) + ":" +
  9031. std::to_string(PORT) +
  9032. "\r\n"
  9033. "Connection: close\r\n"
  9034. "\r\n";
  9035. // Add payload exceeding the 8-byte limit
  9036. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  9037. request_without_content_length += large_payload;
  9038. std::string response;
  9039. bool result = send_request(1, request_without_content_length, &response);
  9040. if (!result) {
  9041. // If send_request fails, server likely closed connection due to payload
  9042. // limit
  9043. SUCCEED() << "Server rejected oversized request without Content-Length "
  9044. "(connection closed)";
  9045. } else {
  9046. // Check if server responded with error or closed connection early
  9047. if (response.length() <= 10) {
  9048. SUCCEED() << "Server closed connection for oversized request without "
  9049. "Content-Length";
  9050. } else {
  9051. // Check for error status codes
  9052. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9053. response.find("Payload Too Large") != std::string::npos ||
  9054. response.find("400") != std::string::npos);
  9055. }
  9056. }
  9057. }
  9058. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  9059. // Test request without Content-Length header within payload limit
  9060. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9061. "Host: " +
  9062. std::string(HOST) + ":" +
  9063. std::to_string(PORT) +
  9064. "\r\n"
  9065. "Connection: close\r\n"
  9066. "\r\n";
  9067. // Add payload within the 8-byte limit
  9068. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  9069. request_without_content_length += small_payload;
  9070. std::string response;
  9071. bool result = send_request(1, request_without_content_length, &response);
  9072. // For requests without Content-Length, the server may have different behavior
  9073. // The key is that it should not reject due to payload limit for small
  9074. // payloads
  9075. if (result) {
  9076. // Check for any HTTP response (success or error, but not connection closed)
  9077. if (response.length() > 10) {
  9078. SUCCEED()
  9079. << "Server processed request without Content-Length within limit";
  9080. } else {
  9081. // Short response might indicate connection closed, which is acceptable
  9082. SUCCEED() << "Server closed connection for request without "
  9083. "Content-Length (acceptable behavior)";
  9084. }
  9085. } else {
  9086. // Connection failure might be due to protocol requirements
  9087. SUCCEED() << "Connection issue with request without Content-Length "
  9088. "(environment-specific)";
  9089. }
  9090. }
  9091. class LargePayloadMaxLengthTest : public ::testing::Test {
  9092. protected:
  9093. LargePayloadMaxLengthTest()
  9094. : cli_(HOST, PORT)
  9095. #ifdef CPPHTTPLIB_SSL_ENABLED
  9096. ,
  9097. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9098. #endif
  9099. {
  9100. #ifdef CPPHTTPLIB_SSL_ENABLED
  9101. cli_.enable_server_certificate_verification(false);
  9102. #endif
  9103. }
  9104. virtual void SetUp() {
  9105. // Set 10MB payload limit
  9106. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9107. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9108. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9109. res.set_content("Large payload test", "text/plain");
  9110. });
  9111. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9112. svr_.wait_until_ready();
  9113. }
  9114. virtual void TearDown() {
  9115. svr_.stop();
  9116. t_.join();
  9117. }
  9118. #ifdef CPPHTTPLIB_SSL_ENABLED
  9119. SSLClient cli_;
  9120. SSLServer svr_;
  9121. #else
  9122. Client cli_;
  9123. Server svr_;
  9124. #endif
  9125. thread t_;
  9126. };
  9127. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9128. // Test chunked encoding with payload within 10MB limit
  9129. std::string medium_payload(5 * 1024 * 1024,
  9130. 'A'); // 5MB payload, within 10MB limit
  9131. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9133. EXPECT_EQ(StatusCode::OK_200, res->status);
  9134. }
  9135. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9136. // Test chunked encoding with payload exceeding 10MB limit
  9137. std::string large_payload(12 * 1024 * 1024,
  9138. 'B'); // 12MB payload, exceeds 10MB limit
  9139. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9140. // Server may either return 413 or close the connection
  9141. if (res) {
  9142. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9143. } else {
  9144. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9145. }
  9146. }
  9147. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9148. // Test request without Content-Length header within 10MB limit
  9149. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9150. "Host: " +
  9151. std::string(HOST) + ":" +
  9152. std::to_string(PORT) +
  9153. "\r\n"
  9154. "Connection: close\r\n"
  9155. "\r\n";
  9156. // Add 1MB payload (within 10MB limit)
  9157. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9158. request_without_content_length += medium_payload;
  9159. std::string response;
  9160. bool result = send_request(5, request_without_content_length, &response);
  9161. if (result) {
  9162. // Should get a proper HTTP response for payloads within limit
  9163. if (response.length() > 10) {
  9164. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9165. "10MB limit";
  9166. } else {
  9167. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9168. "Content-Length)";
  9169. }
  9170. } else {
  9171. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9172. }
  9173. }
  9174. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9175. // Test request without Content-Length header exceeding 10MB limit
  9176. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9177. "Host: " +
  9178. std::string(HOST) + ":" +
  9179. std::to_string(PORT) +
  9180. "\r\n"
  9181. "Connection: close\r\n"
  9182. "\r\n";
  9183. // Add 12MB payload (exceeds 10MB limit)
  9184. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9185. request_without_content_length += large_payload;
  9186. std::string response;
  9187. bool result = send_request(10, request_without_content_length, &response);
  9188. if (!result) {
  9189. // Server should close connection due to payload limit
  9190. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9191. "(connection closed)";
  9192. } else {
  9193. // Check for error response
  9194. if (response.length() <= 10) {
  9195. SUCCEED()
  9196. << "Server closed connection for 12MB request exceeding 10MB limit";
  9197. } else {
  9198. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9199. response.find("Payload Too Large") != std::string::npos ||
  9200. response.find("400") != std::string::npos);
  9201. }
  9202. }
  9203. }
  9204. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9205. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9206. // path.
  9207. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9208. Server svr;
  9209. const size_t LIMIT = 64 * 1024; // 64KB
  9210. svr.set_payload_max_length(LIMIT);
  9211. size_t total = 0;
  9212. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9213. const ContentReader &content_reader) {
  9214. content_reader([&](const char * /*data*/, size_t len) {
  9215. total += len;
  9216. return true;
  9217. });
  9218. res.status = 200;
  9219. res.set_content("stream_ok", "text/plain");
  9220. });
  9221. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9222. auto se = detail::scope_exit([&] {
  9223. svr.stop();
  9224. thread.join();
  9225. ASSERT_FALSE(svr.is_running());
  9226. });
  9227. svr.wait_until_ready();
  9228. // Prepare 256KB raw data and gzip-compress it
  9229. std::string raw(256 * 1024, 'A');
  9230. std::string gz;
  9231. {
  9232. z_stream zs{};
  9233. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9234. Z_DEFAULT_STRATEGY);
  9235. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9236. zs.avail_in = static_cast<uInt>(raw.size());
  9237. char outbuf[4096];
  9238. int ret;
  9239. do {
  9240. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9241. zs.avail_out = sizeof(outbuf);
  9242. ret = deflate(&zs, Z_FINISH);
  9243. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9244. } while (ret != Z_STREAM_END);
  9245. deflateEnd(&zs);
  9246. }
  9247. Client cli(HOST, PORT);
  9248. cli.set_connection_timeout(std::chrono::seconds(5));
  9249. Headers headers = {{"Content-Encoding", "gzip"}};
  9250. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9251. "application/octet-stream");
  9252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9253. // Server must reject oversized decompressed payloads with 413.
  9254. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9255. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9256. EXPECT_LE(total, LIMIT);
  9257. }
  9258. #ifndef CPPHTTPLIB_SSL_ENABLED
  9259. // For a request with neither Content-Length nor Transfer-Encoding, the
  9260. // non-SSL raw-socket fallback in read_content_core() used to hand the
  9261. // compressed wire bytes straight to the ContentReader without ever routing
  9262. // them through the decompressor, so payload_max_length_ only bounded the
  9263. // compressed size on the wire, not the decompressed size.
  9264. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  9265. Server svr;
  9266. const size_t LIMIT = 64 * 1024; // 64KB
  9267. svr.set_payload_max_length(LIMIT);
  9268. size_t total = 0;
  9269. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9270. const ContentReader &content_reader) {
  9271. content_reader([&](const char * /*data*/, size_t len) {
  9272. total += len;
  9273. return true;
  9274. });
  9275. res.status = 200;
  9276. res.set_content("stream_ok", "text/plain");
  9277. });
  9278. auto port = svr.bind_to_any_port(HOST);
  9279. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9280. auto se = detail::scope_exit([&] {
  9281. svr.stop();
  9282. thread.join();
  9283. ASSERT_FALSE(svr.is_running());
  9284. });
  9285. svr.wait_until_ready();
  9286. // Prepare 256KB raw data and gzip-compress it, same payload as the
  9287. // StreamingGzipDecompression test above.
  9288. std::string raw(256 * 1024, 'A');
  9289. std::string gz;
  9290. {
  9291. httplib::detail::gzip_compressor compressor;
  9292. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  9293. [&](const char *chunk, size_t len) {
  9294. gz.append(chunk, len);
  9295. return true;
  9296. });
  9297. ASSERT_TRUE(result);
  9298. }
  9299. // Send the gzip body over raw TCP with neither Content-Length nor
  9300. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  9301. // kicks in.
  9302. std::string req = "POST /stream HTTP/1.1\r\n"
  9303. "Host: " +
  9304. std::string(HOST) + ":" + std::to_string(port) +
  9305. "\r\n"
  9306. "Content-Encoding: gzip\r\n"
  9307. "Connection: close\r\n"
  9308. "\r\n" +
  9309. gz;
  9310. std::string response;
  9311. ASSERT_TRUE(send_request(5, req, &response, port));
  9312. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9313. EXPECT_LE(total, LIMIT);
  9314. }
  9315. #endif
  9316. #endif
  9317. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9318. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9319. // the payload must be passed through untouched instead of being rejected.
  9320. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9321. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9322. Server svr;
  9323. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9324. res.set_content(body, "image/jpeg");
  9325. res.set_header("Content-Encoding", "UTF-8");
  9326. });
  9327. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9328. res.set_content(body, "image/jpeg");
  9329. res.set_header("Content-Encoding", "identity");
  9330. });
  9331. svr.Post("/echo", [](const Request &req, Response &res) {
  9332. res.set_content(req.body, "image/jpeg");
  9333. });
  9334. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9335. auto se = detail::scope_exit([&] {
  9336. svr.stop();
  9337. t.join();
  9338. ASSERT_FALSE(svr.is_running());
  9339. });
  9340. svr.wait_until_ready();
  9341. Client cli(HOST, PORT);
  9342. {
  9343. auto res = cli.Get("/image");
  9344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9345. EXPECT_EQ(StatusCode::OK_200, res->status);
  9346. EXPECT_EQ(body, res->body);
  9347. }
  9348. {
  9349. auto res = cli.Get("/identity");
  9350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9351. EXPECT_EQ(StatusCode::OK_200, res->status);
  9352. EXPECT_EQ(body, res->body);
  9353. }
  9354. {
  9355. // The same applies to a request body reaching the server.
  9356. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9357. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9359. EXPECT_EQ(StatusCode::OK_200, res->status);
  9360. EXPECT_EQ(body, res->body);
  9361. }
  9362. }
  9363. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9364. // gzip-encoded response even when the build has no zlib support.
  9365. static const char GZIPPED_HELLO_WORLD[] = {
  9366. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9367. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9368. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9369. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9370. // A content coding is a whole token, not something the field value merely
  9371. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  9372. // as "fibre" look like Brotli, and turned a multi-coding value like
  9373. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  9374. // it was never meant to see.
  9375. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  9376. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9377. Server svr;
  9378. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  9379. res.set_content(body, "image/jpeg");
  9380. res.set_header("Content-Encoding", "fibre");
  9381. });
  9382. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  9383. res.set_content(body, "image/jpeg");
  9384. res.set_header("Content-Encoding", "gzip, br");
  9385. });
  9386. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  9387. res.set_content(body, "image/jpeg");
  9388. res.set_header("Content-Encoding", "x-zstd-ish");
  9389. });
  9390. auto port = svr.bind_to_any_port(HOST);
  9391. thread t = thread([&]() { svr.listen_after_bind(); });
  9392. auto se = detail::scope_exit([&] {
  9393. svr.stop();
  9394. t.join();
  9395. ASSERT_FALSE(svr.is_running());
  9396. });
  9397. svr.wait_until_ready();
  9398. Client cli(HOST, port);
  9399. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  9400. auto res = cli.Get(path);
  9401. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9402. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9403. // Not a coding we recognize, so the payload comes back untouched
  9404. EXPECT_EQ(body, res->body) << path;
  9405. }
  9406. }
  9407. // A content coding cpp-httplib recognizes but was not built with must be
  9408. // reported as such. Handing the still-compressed payload back to the caller
  9409. // would silently corrupt it.
  9410. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9411. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9412. Server svr;
  9413. // "image/jpeg" keeps the server from applying a content coding of its own,
  9414. // so the hand-crafted Content-Encoding below survives.
  9415. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9416. res.set_content(gzipped, "image/jpeg");
  9417. res.set_header("Content-Encoding", "gzip");
  9418. });
  9419. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9420. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9421. res.set_content(gzipped, "image/jpeg");
  9422. res.set_header("Content-Encoding", "GZIP");
  9423. });
  9424. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9425. auto se = detail::scope_exit([&] {
  9426. svr.stop();
  9427. t.join();
  9428. ASSERT_FALSE(svr.is_running());
  9429. });
  9430. svr.wait_until_ready();
  9431. Client cli(HOST, PORT);
  9432. {
  9433. auto res = cli.Get("/gzipped");
  9434. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9436. EXPECT_EQ("Hello World!", res->body);
  9437. #else
  9438. ASSERT_FALSE(res);
  9439. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9440. #endif
  9441. }
  9442. {
  9443. // open_stream() must behave the same way.
  9444. auto handle = cli.open_stream("GET", "/gzipped");
  9445. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9446. ASSERT_TRUE(handle.is_valid());
  9447. std::string received;
  9448. char buf[256];
  9449. ssize_t n;
  9450. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9451. received.append(buf, static_cast<size_t>(n));
  9452. }
  9453. EXPECT_EQ("Hello World!", received);
  9454. #else
  9455. EXPECT_FALSE(handle.is_valid());
  9456. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9457. #endif
  9458. }
  9459. {
  9460. // A differently-cased coding must not be mistaken for an unknown one, or
  9461. // the body would be handed back still compressed.
  9462. auto res = cli.Get("/gzipped-uppercase");
  9463. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9465. EXPECT_EQ("Hello World!", res->body);
  9466. #else
  9467. ASSERT_FALSE(res);
  9468. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9469. #endif
  9470. }
  9471. }
  9472. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  9473. // the same message as the comma-joined one, so both have to be read the same
  9474. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  9475. // single gzip coding, and a body the sender says was encoded twice was handed
  9476. // back after one pass, still compressed but presented as decoded.
  9477. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  9478. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9479. Server svr;
  9480. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  9481. res.set_content(body, "image/jpeg");
  9482. res.headers.emplace("Content-Encoding", "gzip");
  9483. res.headers.emplace("Content-Encoding", "gzip");
  9484. });
  9485. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  9486. res.set_content(body, "image/jpeg");
  9487. res.set_header("Content-Encoding", "gzip, gzip");
  9488. });
  9489. auto port = svr.bind_to_any_port(HOST);
  9490. thread t = thread([&]() { svr.listen_after_bind(); });
  9491. auto se = detail::scope_exit([&] {
  9492. svr.stop();
  9493. t.join();
  9494. ASSERT_FALSE(svr.is_running());
  9495. });
  9496. svr.wait_until_ready();
  9497. Client cli(HOST, port);
  9498. // Two codings is not something cpp-httplib decodes, so both representations
  9499. // take the pass-through path rather than one of them being gunzipped once.
  9500. for (const char *path : {"/split", "/joined"}) {
  9501. auto res = cli.Get(path);
  9502. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9503. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9504. EXPECT_EQ(body, res->body) << path;
  9505. }
  9506. }
  9507. // Regression test for DoS vulnerability: a malicious server sending a response
  9508. // without Content-Length header must not cause unbounded memory consumption on
  9509. // the client side. The client should stop reading after a reasonable limit,
  9510. // similar to the server-side set_payload_max_length protection.
  9511. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9512. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9513. #ifndef _WIN32
  9514. signal(SIGPIPE, SIG_IGN);
  9515. #endif
  9516. auto server_thread = std::thread([] {
  9517. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9518. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9519. default_socket_options(srv);
  9520. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9521. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9522. sockaddr_in addr{};
  9523. addr.sin_family = AF_INET;
  9524. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9525. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9526. int opt = 1;
  9527. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9528. #ifdef _WIN32
  9529. reinterpret_cast<const char *>(&opt),
  9530. #else
  9531. &opt,
  9532. #endif
  9533. sizeof(opt));
  9534. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9535. ::listen(srv, 1);
  9536. sockaddr_in cli_addr{};
  9537. socklen_t cli_len = sizeof(cli_addr);
  9538. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9539. if (cli != INVALID_SOCKET) {
  9540. char buf[4096];
  9541. ::recv(cli, buf, sizeof(buf), 0);
  9542. // Malicious response: no Content-Length, no chunked encoding
  9543. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9544. "Connection: close\r\n"
  9545. "\r\n";
  9546. ::send(cli,
  9547. #ifdef _WIN32
  9548. static_cast<const char *>(response_header.c_str()),
  9549. static_cast<int>(response_header.size()),
  9550. #else
  9551. response_header.c_str(), response_header.size(),
  9552. #endif
  9553. 0);
  9554. // Send 10MB of data
  9555. std::string chunk(64 * 1024, 'A');
  9556. size_t total_sent = 0;
  9557. while (total_sent < MALICIOUS_DATA_SIZE) {
  9558. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9559. auto sent = ::send(cli,
  9560. #ifdef _WIN32
  9561. static_cast<const char *>(chunk.c_str()),
  9562. static_cast<int>(to_send),
  9563. #else
  9564. chunk.c_str(), to_send,
  9565. #endif
  9566. 0);
  9567. if (sent <= 0) break;
  9568. total_sent += static_cast<size_t>(sent);
  9569. }
  9570. detail::close_socket(cli);
  9571. }
  9572. detail::close_socket(srv);
  9573. });
  9574. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9575. size_t total_read = 0;
  9576. {
  9577. Client cli("127.0.0.1", PORT + 2);
  9578. cli.set_read_timeout(5, 0);
  9579. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9580. auto stream = cli.open_stream("GET", "/malicious");
  9581. ASSERT_TRUE(stream.is_valid());
  9582. char buffer[64 * 1024];
  9583. ssize_t n;
  9584. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9585. total_read += static_cast<size_t>(n);
  9586. }
  9587. } // StreamHandle and Client destroyed here, closing the socket
  9588. server_thread.join();
  9589. // With set_payload_max_length, the client must stop reading before consuming
  9590. // all 10MB. The read loop should be cut off at or near the configured limit.
  9591. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9592. << "Client read " << total_read << " bytes, exceeding the configured "
  9593. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9594. }
  9595. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9596. // the entire response body without truncation.
  9597. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9598. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9599. #ifndef _WIN32
  9600. signal(SIGPIPE, SIG_IGN);
  9601. #endif
  9602. auto server_thread = std::thread([] {
  9603. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9604. default_socket_options(srv);
  9605. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9606. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9607. sockaddr_in addr{};
  9608. addr.sin_family = AF_INET;
  9609. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9610. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9611. int opt = 1;
  9612. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9613. #ifdef _WIN32
  9614. reinterpret_cast<const char *>(&opt),
  9615. #else
  9616. &opt,
  9617. #endif
  9618. sizeof(opt));
  9619. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9620. ::listen(srv, 1);
  9621. sockaddr_in cli_addr{};
  9622. socklen_t cli_len = sizeof(cli_addr);
  9623. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9624. if (cli != INVALID_SOCKET) {
  9625. char buf[4096];
  9626. ::recv(cli, buf, sizeof(buf), 0);
  9627. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9628. "Connection: close\r\n"
  9629. "\r\n";
  9630. ::send(cli,
  9631. #ifdef _WIN32
  9632. static_cast<const char *>(response_header.c_str()),
  9633. static_cast<int>(response_header.size()),
  9634. #else
  9635. response_header.c_str(), response_header.size(),
  9636. #endif
  9637. 0);
  9638. std::string chunk(64 * 1024, 'A');
  9639. size_t total_sent = 0;
  9640. while (total_sent < DATA_SIZE) {
  9641. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9642. auto sent = ::send(cli,
  9643. #ifdef _WIN32
  9644. static_cast<const char *>(chunk.c_str()),
  9645. static_cast<int>(to_send),
  9646. #else
  9647. chunk.c_str(), to_send,
  9648. #endif
  9649. 0);
  9650. if (sent <= 0) break;
  9651. total_sent += static_cast<size_t>(sent);
  9652. }
  9653. #ifdef _WIN32
  9654. ::shutdown(cli, SD_SEND);
  9655. #else
  9656. ::shutdown(cli, SHUT_WR);
  9657. #endif
  9658. // Drain until the client closes its end, ensuring all data is delivered
  9659. char drain[1024];
  9660. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9661. detail::close_socket(cli);
  9662. }
  9663. detail::close_socket(srv);
  9664. });
  9665. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9666. size_t total_read = 0;
  9667. {
  9668. Client cli("127.0.0.1", PORT + 2);
  9669. cli.set_read_timeout(5, 0);
  9670. cli.set_payload_max_length(0); // 0 means no limit
  9671. auto stream = cli.open_stream("GET", "/data");
  9672. ASSERT_TRUE(stream.is_valid());
  9673. char buffer[64 * 1024];
  9674. ssize_t n;
  9675. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9676. total_read += static_cast<size_t>(n);
  9677. }
  9678. }
  9679. server_thread.join();
  9680. EXPECT_EQ(total_read, DATA_SIZE)
  9681. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9682. << " bytes without truncation, but only read " << total_read << " bytes.";
  9683. }
  9684. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9685. // enormous Content-Length must not cause the client to pre-allocate a huge
  9686. // response body buffer. The reservation is capped at payload_max_length_, and
  9687. // the read itself fails when the body exceeds the limit.
  9688. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9689. #ifndef _WIN32
  9690. signal(SIGPIPE, SIG_IGN);
  9691. #endif
  9692. auto server_thread = std::thread([] {
  9693. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9694. default_socket_options(srv);
  9695. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9696. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9697. sockaddr_in addr{};
  9698. addr.sin_family = AF_INET;
  9699. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9700. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9701. int opt = 1;
  9702. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9703. #ifdef _WIN32
  9704. reinterpret_cast<const char *>(&opt),
  9705. #else
  9706. &opt,
  9707. #endif
  9708. sizeof(opt));
  9709. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9710. ::listen(srv, 1);
  9711. sockaddr_in cli_addr{};
  9712. socklen_t cli_len = sizeof(cli_addr);
  9713. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9714. if (cli != INVALID_SOCKET) {
  9715. char buf[4096];
  9716. ::recv(cli, buf, sizeof(buf), 0);
  9717. // Malicious response: claim a 20GB body but send only a tiny payload.
  9718. std::string response = "HTTP/1.1 200 OK\r\n"
  9719. "Content-Length: 20000000000\r\n"
  9720. "\r\n"
  9721. "abc";
  9722. ::send(cli,
  9723. #ifdef _WIN32
  9724. static_cast<const char *>(response.c_str()),
  9725. static_cast<int>(response.size()),
  9726. #else
  9727. response.c_str(), response.size(),
  9728. #endif
  9729. 0);
  9730. detail::close_socket(cli);
  9731. }
  9732. detail::close_socket(srv);
  9733. });
  9734. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9735. {
  9736. Client cli("127.0.0.1", PORT + 2);
  9737. cli.set_read_timeout(5, 0);
  9738. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9739. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9740. // (server claims more bytes than payload_max_length permits), but it must
  9741. // not exhaust memory before getting there.
  9742. auto res = cli.Get("/malicious");
  9743. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9744. }
  9745. server_thread.join();
  9746. }
  9747. // Verify that content_receiver bypasses the default payload_max_length,
  9748. // allowing streaming downloads larger than 100MB without requiring an explicit
  9749. // set_payload_max_length call.
  9750. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9751. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9752. #ifndef _WIN32
  9753. signal(SIGPIPE, SIG_IGN);
  9754. #endif
  9755. auto server_thread = std::thread([] {
  9756. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9757. default_socket_options(srv);
  9758. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9759. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9760. sockaddr_in addr{};
  9761. addr.sin_family = AF_INET;
  9762. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9763. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9764. int opt = 1;
  9765. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9766. #ifdef _WIN32
  9767. reinterpret_cast<const char *>(&opt),
  9768. #else
  9769. &opt,
  9770. #endif
  9771. sizeof(opt));
  9772. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9773. ::listen(srv, 1);
  9774. sockaddr_in cli_addr{};
  9775. socklen_t cli_len = sizeof(cli_addr);
  9776. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9777. if (cli != INVALID_SOCKET) {
  9778. char buf[4096];
  9779. ::recv(cli, buf, sizeof(buf), 0);
  9780. // Response with Content-Length larger than default 100MB limit
  9781. auto content_length = std::to_string(DATA_SIZE);
  9782. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9783. "Content-Length: " +
  9784. content_length +
  9785. "\r\n"
  9786. "Connection: close\r\n"
  9787. "\r\n";
  9788. ::send(cli,
  9789. #ifdef _WIN32
  9790. static_cast<const char *>(response_header.c_str()),
  9791. static_cast<int>(response_header.size()),
  9792. #else
  9793. response_header.c_str(), response_header.size(),
  9794. #endif
  9795. 0);
  9796. std::string chunk(64 * 1024, 'A');
  9797. size_t total_sent = 0;
  9798. while (total_sent < DATA_SIZE) {
  9799. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9800. auto sent = ::send(cli,
  9801. #ifdef _WIN32
  9802. static_cast<const char *>(chunk.c_str()),
  9803. static_cast<int>(to_send),
  9804. #else
  9805. chunk.c_str(), to_send,
  9806. #endif
  9807. 0);
  9808. if (sent <= 0) break;
  9809. total_sent += static_cast<size_t>(sent);
  9810. }
  9811. detail::close_socket(cli);
  9812. }
  9813. detail::close_socket(srv);
  9814. });
  9815. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9816. size_t total_received = 0;
  9817. {
  9818. Client cli("127.0.0.1", PORT + 2);
  9819. cli.set_read_timeout(10, 0);
  9820. // Do NOT call set_payload_max_length — use the default 100MB limit
  9821. auto res =
  9822. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9823. total_received += data_length;
  9824. return true;
  9825. });
  9826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9827. EXPECT_EQ(StatusCode::OK_200, res->status);
  9828. }
  9829. server_thread.join();
  9830. EXPECT_EQ(total_received, DATA_SIZE)
  9831. << "With content_receiver, the client should read all " << DATA_SIZE
  9832. << " bytes despite the default 100MB payload_max_length, but only read "
  9833. << total_received << " bytes.";
  9834. }
  9835. // Verify that an explicit set_payload_max_length smaller than the response is
  9836. // enforced even when a content_receiver is used.
  9837. TEST(ClientVulnerabilityTest,
  9838. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9839. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9840. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9841. #ifndef _WIN32
  9842. signal(SIGPIPE, SIG_IGN);
  9843. #endif
  9844. auto server_thread = std::thread([] {
  9845. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9846. default_socket_options(srv);
  9847. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9848. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9849. sockaddr_in addr{};
  9850. addr.sin_family = AF_INET;
  9851. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9852. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9853. int opt = 1;
  9854. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9855. #ifdef _WIN32
  9856. reinterpret_cast<const char *>(&opt),
  9857. #else
  9858. &opt,
  9859. #endif
  9860. sizeof(opt));
  9861. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9862. ::listen(srv, 1);
  9863. sockaddr_in cli_addr{};
  9864. socklen_t cli_len = sizeof(cli_addr);
  9865. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9866. if (cli != INVALID_SOCKET) {
  9867. char buf[4096];
  9868. ::recv(cli, buf, sizeof(buf), 0);
  9869. auto content_length = std::to_string(DATA_SIZE);
  9870. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9871. "Content-Length: " +
  9872. content_length +
  9873. "\r\n"
  9874. "Connection: close\r\n"
  9875. "\r\n";
  9876. ::send(cli,
  9877. #ifdef _WIN32
  9878. static_cast<const char *>(response_header.c_str()),
  9879. static_cast<int>(response_header.size()),
  9880. #else
  9881. response_header.c_str(), response_header.size(),
  9882. #endif
  9883. 0);
  9884. std::string chunk(64 * 1024, 'A');
  9885. size_t total_sent = 0;
  9886. while (total_sent < DATA_SIZE) {
  9887. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9888. auto sent = ::send(cli,
  9889. #ifdef _WIN32
  9890. static_cast<const char *>(chunk.c_str()),
  9891. static_cast<int>(to_send),
  9892. #else
  9893. chunk.c_str(), to_send,
  9894. #endif
  9895. 0);
  9896. if (sent <= 0) break;
  9897. total_sent += static_cast<size_t>(sent);
  9898. }
  9899. detail::close_socket(cli);
  9900. }
  9901. detail::close_socket(srv);
  9902. });
  9903. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9904. size_t total_received = 0;
  9905. {
  9906. Client cli("127.0.0.1", PORT + 2);
  9907. cli.set_read_timeout(10, 0);
  9908. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9909. auto res =
  9910. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9911. total_received += data_length;
  9912. return true;
  9913. });
  9914. // Should fail because 200MB exceeds the explicit 150MB limit
  9915. EXPECT_FALSE(res);
  9916. }
  9917. server_thread.join();
  9918. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9919. << "Client with content_receiver should respect the explicit "
  9920. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9921. << total_received << " bytes.";
  9922. }
  9923. // Verify that an explicit set_payload_max_length larger than the response
  9924. // allows the content_receiver to read all data successfully.
  9925. TEST(ClientVulnerabilityTest,
  9926. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9927. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9928. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9929. #ifndef _WIN32
  9930. signal(SIGPIPE, SIG_IGN);
  9931. #endif
  9932. auto server_thread = std::thread([] {
  9933. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9934. default_socket_options(srv);
  9935. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9936. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9937. sockaddr_in addr{};
  9938. addr.sin_family = AF_INET;
  9939. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9940. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9941. int opt = 1;
  9942. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9943. #ifdef _WIN32
  9944. reinterpret_cast<const char *>(&opt),
  9945. #else
  9946. &opt,
  9947. #endif
  9948. sizeof(opt));
  9949. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9950. ::listen(srv, 1);
  9951. sockaddr_in cli_addr{};
  9952. socklen_t cli_len = sizeof(cli_addr);
  9953. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9954. if (cli != INVALID_SOCKET) {
  9955. char buf[4096];
  9956. ::recv(cli, buf, sizeof(buf), 0);
  9957. auto content_length = std::to_string(DATA_SIZE);
  9958. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9959. "Content-Length: " +
  9960. content_length +
  9961. "\r\n"
  9962. "Connection: close\r\n"
  9963. "\r\n";
  9964. ::send(cli,
  9965. #ifdef _WIN32
  9966. static_cast<const char *>(response_header.c_str()),
  9967. static_cast<int>(response_header.size()),
  9968. #else
  9969. response_header.c_str(), response_header.size(),
  9970. #endif
  9971. 0);
  9972. std::string chunk(64 * 1024, 'A');
  9973. size_t total_sent = 0;
  9974. while (total_sent < DATA_SIZE) {
  9975. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9976. auto sent = ::send(cli,
  9977. #ifdef _WIN32
  9978. static_cast<const char *>(chunk.c_str()),
  9979. static_cast<int>(to_send),
  9980. #else
  9981. chunk.c_str(), to_send,
  9982. #endif
  9983. 0);
  9984. if (sent <= 0) break;
  9985. total_sent += static_cast<size_t>(sent);
  9986. }
  9987. #ifdef _WIN32
  9988. ::shutdown(cli, SD_SEND);
  9989. #else
  9990. ::shutdown(cli, SHUT_WR);
  9991. #endif
  9992. char drain[1024];
  9993. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9994. detail::close_socket(cli);
  9995. }
  9996. detail::close_socket(srv);
  9997. });
  9998. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9999. size_t total_received = 0;
  10000. {
  10001. Client cli("127.0.0.1", PORT + 2);
  10002. cli.set_read_timeout(10, 0);
  10003. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  10004. auto res =
  10005. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10006. total_received += data_length;
  10007. return true;
  10008. });
  10009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10010. EXPECT_EQ(StatusCode::OK_200, res->status);
  10011. }
  10012. server_thread.join();
  10013. EXPECT_EQ(total_received, DATA_SIZE)
  10014. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  10015. << " bytes (larger than " << DATA_SIZE
  10016. << " bytes response), content_receiver should read all data, but only "
  10017. "read "
  10018. << total_received << " bytes.";
  10019. }
  10020. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  10021. // Regression test for "zip bomb" attack on the client side: a malicious server
  10022. // sends a small gzip-compressed response that decompresses to a huge payload.
  10023. // The client must enforce payload_max_length on the decompressed size.
  10024. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  10025. constexpr size_t DECOMPRESSED_SIZE =
  10026. 10 * 1024 * 1024; // 10MB after decompression
  10027. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10028. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  10029. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  10030. std::string compressed;
  10031. {
  10032. httplib::detail::gzip_compressor compressor;
  10033. bool ok =
  10034. compressor.compress(uncompressed.data(), uncompressed.size(),
  10035. /*last=*/true, [&](const char *buf, size_t len) {
  10036. compressed.append(buf, len);
  10037. return true;
  10038. });
  10039. ASSERT_TRUE(ok);
  10040. }
  10041. // Sanity: compressed data should be much smaller than the decompressed size
  10042. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  10043. #ifndef _WIN32
  10044. signal(SIGPIPE, SIG_IGN);
  10045. #endif
  10046. // Set up the listening socket in the main thread so the server is guaranteed
  10047. // to be ready before the client connects (eliminates race condition).
  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 + 3));
  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. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  10065. ASSERT_EQ(0, ::listen(srv, 1));
  10066. auto server_thread = std::thread([&compressed, srv] {
  10067. sockaddr_in cli_addr{};
  10068. socklen_t cli_len = sizeof(cli_addr);
  10069. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10070. if (cli != INVALID_SOCKET) {
  10071. // Read the full HTTP request (until \r\n\r\n)
  10072. char buf[4096];
  10073. size_t total = 0;
  10074. while (total < sizeof(buf)) {
  10075. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  10076. if (n <= 0) break;
  10077. total += static_cast<size_t>(n);
  10078. // Check for end of headers
  10079. if (total >= 4) {
  10080. std::string req(buf, total);
  10081. if (req.find("\r\n\r\n") != std::string::npos) break;
  10082. }
  10083. }
  10084. // Malicious response: gzip-compressed body, no Content-Length
  10085. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10086. "Content-Encoding: gzip\r\n"
  10087. "Connection: close\r\n"
  10088. "\r\n";
  10089. ::send(cli,
  10090. #ifdef _WIN32
  10091. static_cast<const char *>(response_header.c_str()),
  10092. static_cast<int>(response_header.size()),
  10093. #else
  10094. response_header.c_str(), response_header.size(),
  10095. #endif
  10096. 0);
  10097. // Send the compressed payload (small on the wire, huge when decompressed)
  10098. size_t total_sent = 0;
  10099. while (total_sent < compressed.size()) {
  10100. auto to_send = std::min(compressed.size() - total_sent,
  10101. static_cast<size_t>(64 * 1024));
  10102. auto sent =
  10103. ::send(cli,
  10104. #ifdef _WIN32
  10105. static_cast<const char *>(compressed.c_str() + total_sent),
  10106. static_cast<int>(to_send),
  10107. #else
  10108. compressed.c_str() + total_sent, to_send,
  10109. #endif
  10110. 0);
  10111. if (sent <= 0) break;
  10112. total_sent += static_cast<size_t>(sent);
  10113. }
  10114. detail::close_socket(cli);
  10115. }
  10116. });
  10117. auto se = detail::scope_exit([&] {
  10118. detail::close_socket(srv);
  10119. server_thread.join();
  10120. });
  10121. size_t total_decompressed = 0;
  10122. {
  10123. Client cli("127.0.0.1", PORT + 3);
  10124. cli.set_read_timeout(5, 0);
  10125. cli.set_decompress(true);
  10126. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10127. auto stream = cli.open_stream("GET", "/zipbomb");
  10128. ASSERT_TRUE(stream.is_valid());
  10129. char buffer[64 * 1024];
  10130. ssize_t n;
  10131. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10132. total_decompressed += static_cast<size_t>(n);
  10133. }
  10134. }
  10135. // The decompressed size must be capped by payload_max_length. Without
  10136. // protection, the client would decompress the full 10MB from a tiny
  10137. // compressed payload, enabling a zip bomb DoS attack.
  10138. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  10139. << "Client decompressed " << total_decompressed
  10140. << " bytes from a gzip response. The decompressed size should be "
  10141. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  10142. }
  10143. #endif
  10144. TEST(HostAndPortPropertiesTest, NoSSL) {
  10145. httplib::Client cli("www.google.com", 1234);
  10146. ASSERT_EQ("www.google.com", cli.host());
  10147. ASSERT_EQ(1234, cli.port());
  10148. }
  10149. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10150. httplib::Client cli("www.google.com:1234");
  10151. ASSERT_EQ("www.google.com", cli.host());
  10152. ASSERT_EQ(1234, cli.port());
  10153. }
  10154. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10155. // Port number that overflows int — should not crash, client becomes invalid
  10156. httplib::Client cli("http://www.google.com:99999999999999999999");
  10157. ASSERT_FALSE(cli.is_valid());
  10158. }
  10159. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10160. // Port 99999 exceeds valid range (1-65535) — should not crash
  10161. httplib::Client cli("http://www.google.com:99999");
  10162. ASSERT_FALSE(cli.is_valid());
  10163. }
  10164. #ifdef CPPHTTPLIB_SSL_ENABLED
  10165. TEST(HostAndPortPropertiesTest, SSL) {
  10166. httplib::SSLClient cli("www.google.com");
  10167. ASSERT_EQ("www.google.com", cli.host());
  10168. ASSERT_EQ(443, cli.port());
  10169. }
  10170. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10171. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10172. std::string cert;
  10173. read_file(CA_CERT_FILE, cert);
  10174. httplib::SSLClient httplib_client("www.google.com");
  10175. // Load CA store first time
  10176. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10177. // Load CA store second time (update)
  10178. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10179. // Verify client is still valid and can make connections
  10180. httplib_client.enable_server_certificate_verification(true);
  10181. auto res = httplib_client.Get("/");
  10182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10183. // Google may return 200 or 301 depending on various factors
  10184. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10185. res->status == StatusCode::MovedPermanently_301);
  10186. }
  10187. TEST(SSLClientTest, ServerNameIndication_Online) {
  10188. auto host = "httpbingo.org";
  10189. auto path = std::string{"/get"};
  10190. SSLClient cli(host, 443);
  10191. auto res = cli.Get(path);
  10192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10193. ASSERT_EQ(StatusCode::OK_200, res->status);
  10194. }
  10195. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10196. // Use a site that will cause SSL verification failure due to self-signed cert
  10197. SSLClient cli("self-signed.badssl.com", 443);
  10198. cli.enable_server_certificate_verification(true);
  10199. auto res = cli.Get("/");
  10200. ASSERT_TRUE(!res);
  10201. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10202. // Verify backend error is captured for SSLServerVerification
  10203. // This occurs when certificate verification fails
  10204. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10205. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10206. EXPECT_NE(0UL, res.ssl_backend_error());
  10207. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10208. // For OpenSSL, ssl_error is 0 for verification errors
  10209. EXPECT_EQ(0, res.ssl_error());
  10210. #if !defined(_WIN32) || \
  10211. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10212. // On non-Windows or when Windows Schannel is disabled, the error comes
  10213. // from OpenSSL's verification
  10214. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10215. res.ssl_backend_error());
  10216. #endif
  10217. #endif
  10218. }
  10219. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10220. // Use a site where hostname doesn't match the certificate
  10221. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10222. SSLClient cli("wrong.host.badssl.com", 443);
  10223. cli.enable_server_certificate_verification(true);
  10224. cli.enable_server_hostname_verification(true);
  10225. auto res = cli.Get("/");
  10226. ASSERT_TRUE(!res);
  10227. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10228. // Verify backend error is captured for hostname verification failure
  10229. EXPECT_NE(0UL, res.ssl_backend_error());
  10230. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10231. // For OpenSSL, ssl_error is 0 for verification errors
  10232. EXPECT_EQ(0, res.ssl_error());
  10233. #if !defined(_WIN32) || \
  10234. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10235. // On non-Windows or when Windows Schannel is disabled, the error comes
  10236. // from OpenSSL's hostname verification
  10237. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10238. res.ssl_backend_error());
  10239. #endif
  10240. #endif
  10241. }
  10242. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10243. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10244. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10245. SSLClient cli("www.google.com", 443);
  10246. cli.enable_server_certificate_verification(true);
  10247. auto res = cli.Get("/");
  10248. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10249. }
  10250. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10251. SSLClient cli("www.google.com", 443);
  10252. cli.enable_server_certificate_verification(true);
  10253. cli.enable_windows_certificate_verification(false);
  10254. auto res = cli.Get("/");
  10255. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10256. }
  10257. #endif
  10258. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10259. Client cli("https://google.com");
  10260. auto res = cli.Get("/");
  10261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10262. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10263. }
  10264. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10265. SSLClient cli("google.com");
  10266. cli.set_ca_cert_path(CA_CERT_FILE);
  10267. auto res = cli.Get("/");
  10268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10269. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10270. }
  10271. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10272. SSLClient cli("google.com");
  10273. cli.enable_server_certificate_verification(true);
  10274. cli.set_ca_cert_path("hello");
  10275. auto res = cli.Get("/");
  10276. ASSERT_TRUE(!res);
  10277. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10278. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10279. // should be set
  10280. EXPECT_EQ(0, res.ssl_error());
  10281. // Verify backend error is captured for SSLLoadingCerts
  10282. // This error occurs when loading CA certificates fails
  10283. EXPECT_NE(0UL, res.ssl_backend_error());
  10284. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10285. // OpenSSL specific error codes:
  10286. // > openssl errstr 0x80000002
  10287. // error:80000002:system library::No such file or directory
  10288. // > openssl errstr 0xA000126
  10289. // error:0A000126:SSL routines::unexpected eof while reading
  10290. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10291. res.ssl_backend_error() == 0xA000126);
  10292. #endif
  10293. }
  10294. TEST(SSLClientTest, ServerCertificateVerification4) {
  10295. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10296. ASSERT_TRUE(svr.is_valid());
  10297. svr.Get("/test", [&](const Request &, Response &res) {
  10298. res.set_content("test", "text/plain");
  10299. svr.stop();
  10300. ASSERT_TRUE(true);
  10301. });
  10302. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10303. auto se = detail::scope_exit([&] {
  10304. t.join();
  10305. ASSERT_FALSE(svr.is_running());
  10306. });
  10307. svr.wait_until_ready();
  10308. SSLClient cli("127.0.0.1", PORT);
  10309. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10310. cli.enable_server_certificate_verification(true);
  10311. cli.set_connection_timeout(30);
  10312. auto res = cli.Get("/test");
  10313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10314. ASSERT_EQ(StatusCode::OK_200, res->status);
  10315. }
  10316. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10317. std::string cert;
  10318. read_file(CA_CERT_FILE, cert);
  10319. SSLClient cli("google.com");
  10320. cli.load_ca_cert_store(cert.data(), cert.size());
  10321. const auto res = cli.Get("/");
  10322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10323. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10324. }
  10325. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10326. // clang-format off
  10327. static constexpr char cert[] =
  10328. "GlobalSign Root CA\n"
  10329. "==================\n"
  10330. "-----BEGIN CERTIFICATE-----\n"
  10331. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10332. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10333. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10334. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10335. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10336. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10337. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10338. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10339. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10340. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10341. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10342. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10343. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10344. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10345. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10346. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10347. "-----END CERTIFICATE-----\n";
  10348. // clang-format on
  10349. SSLClient cli("google.com");
  10350. cli.load_ca_cert_store(cert, sizeof(cert));
  10351. const auto res = cli.Get("/");
  10352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10353. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10354. }
  10355. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10356. SSLClient cli("www.youtube.com");
  10357. cli.set_ca_cert_path(CA_CERT_FILE);
  10358. cli.enable_server_certificate_verification(true);
  10359. cli.set_follow_location(true);
  10360. auto res = cli.Get("/");
  10361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10362. ASSERT_EQ(StatusCode::OK_200, res->status);
  10363. }
  10364. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10365. SSLClient cli("wWw.YouTube.Com");
  10366. cli.set_ca_cert_path(CA_CERT_FILE);
  10367. cli.enable_server_certificate_verification(true);
  10368. cli.enable_server_hostname_verification(true);
  10369. cli.set_follow_location(true);
  10370. auto res = cli.Get("/");
  10371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10372. ASSERT_EQ(StatusCode::OK_200, res->status);
  10373. }
  10374. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10375. SSLClient cli("gOoGlE.COm");
  10376. cli.enable_server_certificate_verification(true);
  10377. cli.enable_server_hostname_verification(true);
  10378. cli.set_follow_location(true);
  10379. auto res = cli.Get("/");
  10380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10381. ASSERT_EQ(StatusCode::OK_200, res->status);
  10382. }
  10383. TEST(SSLClientTest, Issue2004_Online) {
  10384. Client client("https://google.com");
  10385. client.set_follow_location(true);
  10386. auto res = client.Get("/");
  10387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10388. ASSERT_EQ(StatusCode::OK_200, res->status);
  10389. auto body = res->body;
  10390. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10391. }
  10392. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10393. // Create SSLClient with invalid cert/key to make is_valid() return false
  10394. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10395. "nonexistent_key.pem");
  10396. // is_valid() should be false due to cert loading failure
  10397. ASSERT_FALSE(cli.is_valid());
  10398. auto res = cli.Get("/");
  10399. ASSERT_FALSE(res);
  10400. EXPECT_EQ(Error::SSLConnection, res.error());
  10401. }
  10402. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10403. // Test for Issue #2251: SSL error not properly reported when client cert
  10404. // and key paths are swapped or mismatched
  10405. // This simulates the scenario where user accidentally swaps the cert and key
  10406. // files
  10407. // Using client cert file as private key and vice versa (completely wrong)
  10408. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10409. // Should fail validation due to cert/key mismatch
  10410. ASSERT_FALSE(cli.is_valid());
  10411. // Attempt to make a request should fail with proper error
  10412. auto res = cli.Get("/");
  10413. ASSERT_FALSE(res);
  10414. EXPECT_EQ(Error::SSLConnection, res.error());
  10415. // SSL error should be recorded in the Result object (this is the key fix for
  10416. // Issue #2251)
  10417. auto backend_error = res.ssl_backend_error();
  10418. EXPECT_NE(0u, backend_error);
  10419. }
  10420. // Tests cert/key mismatch detection at the TLS context level
  10421. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10422. // Test that using mismatched cert/key causes connection failure.
  10423. // We verify this at the SSLClient level rather than through internal
  10424. // TLS API functions.
  10425. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10426. cli.enable_server_certificate_verification(false);
  10427. cli.set_connection_timeout(2);
  10428. // The mismatch should cause a connection or handshake error
  10429. auto res = cli.Get("/test");
  10430. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10431. // Either way, the request should fail
  10432. EXPECT_FALSE(res);
  10433. }
  10434. #endif
  10435. #if 0
  10436. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10437. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10438. ASSERT_TRUE(cli != nullptr);
  10439. cli->set_address_family(AF_INET6);
  10440. cli->set_interface("en0");
  10441. auto res = cli->Get("/get");
  10442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10443. ASSERT_EQ(StatusCode::OK_200, res->status);
  10444. }
  10445. #endif
  10446. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10447. #ifdef CPPHTTPLIB_SSL_ENABLED
  10448. void ClientCertPresent(
  10449. const std::string &client_cert_file,
  10450. const std::string &client_private_key_file,
  10451. const std::string &client_encrypted_private_key_pass = std::string()) {
  10452. using namespace httplib::tls;
  10453. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10454. CLIENT_CA_CERT_DIR);
  10455. ASSERT_TRUE(svr.is_valid());
  10456. svr.Get("/test", [&](const Request &req, Response &res) {
  10457. res.set_content("test", "text/plain");
  10458. auto cert = req.peer_cert();
  10459. ASSERT_TRUE(static_cast<bool>(cert));
  10460. std::string common_name = cert.subject_cn();
  10461. EXPECT_EQ("Common Name", common_name);
  10462. });
  10463. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10464. auto se = detail::scope_exit([&] {
  10465. svr.stop();
  10466. t.join();
  10467. ASSERT_FALSE(svr.is_running());
  10468. });
  10469. svr.wait_until_ready();
  10470. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10471. client_encrypted_private_key_pass);
  10472. cli.enable_server_certificate_verification(false);
  10473. cli.set_connection_timeout(30);
  10474. auto res = cli.Get("/test");
  10475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10476. ASSERT_EQ(StatusCode::OK_200, res->status);
  10477. }
  10478. TEST(SSLClientServerTest, ClientCertPresent) {
  10479. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10480. }
  10481. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10482. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10483. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10484. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10485. }
  10486. // PEM memory-based constructor tests (works with all TLS backends)
  10487. void PemMemoryClientCertPresent(
  10488. const std::string &client_cert_file,
  10489. const std::string &client_private_key_file,
  10490. const std::string &client_encrypted_private_key_pass = std::string()) {
  10491. // Read PEM files into memory
  10492. std::string server_cert_pem, server_key_pem;
  10493. std::string client_ca_pem;
  10494. std::string client_cert_pem, client_key_pem;
  10495. read_file(SERVER_CERT_FILE, server_cert_pem);
  10496. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10497. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10498. read_file(client_cert_file, client_cert_pem);
  10499. read_file(client_private_key_file, client_key_pem);
  10500. // Create server with PEM memory
  10501. SSLServer::PemMemory server_pem = {
  10502. server_cert_pem.c_str(),
  10503. server_cert_pem.size(),
  10504. server_key_pem.c_str(),
  10505. server_key_pem.size(),
  10506. client_ca_pem.c_str(),
  10507. client_ca_pem.size(),
  10508. nullptr // no password for server key
  10509. };
  10510. SSLServer svr(server_pem);
  10511. ASSERT_TRUE(svr.is_valid());
  10512. svr.Get("/test", [&](const Request &, Response &res) {
  10513. res.set_content("test", "text/plain");
  10514. });
  10515. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10516. auto se = detail::scope_exit([&] {
  10517. svr.stop();
  10518. t.join();
  10519. ASSERT_FALSE(svr.is_running());
  10520. });
  10521. svr.wait_until_ready();
  10522. // Create client with PEM memory
  10523. const char *password = client_encrypted_private_key_pass.empty()
  10524. ? nullptr
  10525. : client_encrypted_private_key_pass.c_str();
  10526. SSLClient::PemMemory client_pem = {
  10527. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10528. client_key_pem.size(), password};
  10529. SSLClient cli(HOST, PORT, client_pem);
  10530. cli.enable_server_certificate_verification(false);
  10531. cli.set_connection_timeout(30);
  10532. auto res = cli.Get("/test");
  10533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10534. ASSERT_EQ(StatusCode::OK_200, res->status);
  10535. }
  10536. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10537. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10538. }
  10539. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10540. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10541. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10542. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10543. }
  10544. TEST(SSLClientServerTest, ClientCertMissing) {
  10545. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10546. CLIENT_CA_CERT_DIR);
  10547. ASSERT_TRUE(svr.is_valid());
  10548. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10549. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10550. auto se = detail::scope_exit([&] {
  10551. svr.stop();
  10552. t.join();
  10553. ASSERT_FALSE(svr.is_running());
  10554. });
  10555. svr.wait_until_ready();
  10556. SSLClient cli(HOST, PORT);
  10557. cli.set_connection_timeout(30);
  10558. auto res = cli.Get("/test");
  10559. ASSERT_TRUE(!res);
  10560. // When client cert is missing and server requires it, connection fails
  10561. // Error type depends on backend implementation
  10562. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10563. res.error() == Error::SSLConnection);
  10564. // Verify backend error is captured
  10565. // Note: This test may have different error codes depending on the exact
  10566. // verification failure
  10567. EXPECT_NE(0UL, res.ssl_backend_error());
  10568. }
  10569. TEST(SSLClientServerTest, TrustDirOptional) {
  10570. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10571. ASSERT_TRUE(svr.is_valid());
  10572. svr.Get("/test", [&](const Request &, Response &res) {
  10573. res.set_content("test", "text/plain");
  10574. });
  10575. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10576. auto se = detail::scope_exit([&] {
  10577. svr.stop();
  10578. t.join();
  10579. ASSERT_FALSE(svr.is_running());
  10580. });
  10581. svr.wait_until_ready();
  10582. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10583. cli.enable_server_certificate_verification(false);
  10584. cli.set_connection_timeout(30);
  10585. auto res = cli.Get("/test");
  10586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10587. ASSERT_EQ(StatusCode::OK_200, res->status);
  10588. }
  10589. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10590. class NoListenSSLServer : public SSLServer {
  10591. public:
  10592. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10593. const char *client_ca_cert_file_path,
  10594. const char *client_ca_cert_dir_path = nullptr)
  10595. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10596. client_ca_cert_dir_path),
  10597. stop_(false) {}
  10598. std::atomic_bool stop_;
  10599. private:
  10600. bool process_and_close_socket(socket_t /*sock*/) override {
  10601. // Don't create SSL context
  10602. while (!stop_.load()) {
  10603. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10604. }
  10605. return true;
  10606. }
  10607. };
  10608. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10609. CLIENT_CA_CERT_FILE);
  10610. ASSERT_TRUE(svr.is_valid());
  10611. svr.Get("/test", [&](const Request &, Response &res) {
  10612. res.set_content("test", "text/plain");
  10613. });
  10614. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10615. auto se = detail::scope_exit([&] {
  10616. svr.stop_ = true;
  10617. svr.stop();
  10618. t.join();
  10619. ASSERT_FALSE(svr.is_running());
  10620. });
  10621. svr.wait_until_ready();
  10622. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10623. cli.enable_server_certificate_verification(false);
  10624. cli.set_connection_timeout(1);
  10625. auto res = cli.Get("/test");
  10626. ASSERT_TRUE(!res);
  10627. EXPECT_EQ(Error::SSLConnection, res.error());
  10628. // Timeout results in WantRead error code (maps to backend-specific value)
  10629. EXPECT_NE(0, res.ssl_error());
  10630. }
  10631. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10632. // Test SSLServer with client certificate verification using the standard
  10633. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10634. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10635. CLIENT_CA_CERT_DIR);
  10636. ASSERT_TRUE(svr.is_valid());
  10637. svr.Get("/test", [&](const Request &req, Response &res) {
  10638. res.set_content("test", "text/plain");
  10639. auto cert = req.peer_cert();
  10640. ASSERT_TRUE(static_cast<bool>(cert));
  10641. auto common_name = cert.subject_cn();
  10642. EXPECT_EQ("Common Name", common_name);
  10643. });
  10644. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10645. auto se = detail::scope_exit([&] {
  10646. svr.stop();
  10647. t.join();
  10648. ASSERT_FALSE(svr.is_running());
  10649. });
  10650. svr.wait_until_ready();
  10651. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10652. cli.enable_server_certificate_verification(false);
  10653. cli.set_connection_timeout(30);
  10654. auto res = cli.Get("/test");
  10655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10656. ASSERT_EQ(StatusCode::OK_200, res->status);
  10657. }
  10658. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10659. // Verifies that wildcard matching and exact matching work consistently
  10660. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10661. using namespace httplib::tls;
  10662. // We need a running server to test against
  10663. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10664. ASSERT_TRUE(svr.is_valid());
  10665. svr.Get("/test", [](const Request &, Response &res) {
  10666. res.set_content("ok", "text/plain");
  10667. });
  10668. thread t([&]() { svr.listen(HOST, PORT); });
  10669. auto se = detail::scope_exit([&] {
  10670. svr.stop();
  10671. t.join();
  10672. });
  10673. svr.wait_until_ready();
  10674. bool verify_callback_called = false;
  10675. bool verify_result_wrong = false;
  10676. SSLClient cli(HOST, PORT);
  10677. cli.enable_server_certificate_verification(true);
  10678. cli.set_ca_cert_path(CA_CERT_FILE);
  10679. cli.set_connection_timeout(5);
  10680. // Note: Test certificate has CN="Common Name", not "localhost"
  10681. bool verify_result_cn = false;
  10682. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10683. verify_callback_called = true;
  10684. if (!ctx.cert) return false;
  10685. // Test 1: "Common Name" should match (our test server cert CN)
  10686. verify_result_cn = ctx.check_hostname("Common Name");
  10687. // Test 2: wrong hostname should not match
  10688. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10689. return true; // Accept for the purpose of this test
  10690. });
  10691. auto res = cli.Get("/test");
  10692. // The request may succeed or fail depending on cert configuration
  10693. // but the callback should have been called
  10694. ASSERT_TRUE(verify_callback_called)
  10695. << "Verify callback should have been called";
  10696. // CN="Common Name" should match our test certificate
  10697. //
  10698. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10699. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10700. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10701. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10702. // <openssl/base.h>, which is included transitively when
  10703. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10704. #if defined(OPENSSL_IS_BORINGSSL)
  10705. EXPECT_FALSE(verify_result_cn)
  10706. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10707. #else
  10708. EXPECT_TRUE(verify_result_cn)
  10709. << "verify_hostname should match 'Common Name' (certificate CN)";
  10710. #endif
  10711. // Wrong hostname should not match
  10712. EXPECT_FALSE(verify_result_wrong)
  10713. << "verify_hostname should not match 'wronghost.example.com'";
  10714. }
  10715. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10716. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10717. // X509_check_ip behavior and must hold for every backend.
  10718. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10719. using namespace httplib::tls;
  10720. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10721. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10722. ASSERT_TRUE(svr.is_valid());
  10723. svr.Get("/test", [](const Request &, Response &res) {
  10724. res.set_content("ok", "text/plain");
  10725. });
  10726. thread t([&]() { svr.listen(HOST, PORT); });
  10727. auto se = detail::scope_exit([&] {
  10728. svr.stop();
  10729. t.join();
  10730. });
  10731. svr.wait_until_ready();
  10732. bool verify_callback_called = false;
  10733. bool ip_matched_via_cn = true;
  10734. SSLClient cli(HOST, PORT);
  10735. cli.enable_server_certificate_verification(true);
  10736. cli.set_ca_cert_path(CA_CERT_FILE);
  10737. cli.set_connection_timeout(5);
  10738. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10739. verify_callback_called = true;
  10740. if (!ctx.cert) return false;
  10741. // The IP appears only in the CN, so it must NOT be accepted.
  10742. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10743. return true; // Accept for the purpose of this test
  10744. });
  10745. cli.Get("/test");
  10746. ASSERT_TRUE(verify_callback_called)
  10747. << "Verify callback should have been called";
  10748. EXPECT_FALSE(ip_matched_via_cn)
  10749. << "An IP host must not be authenticated via the certificate CN";
  10750. }
  10751. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10752. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10753. using namespace httplib::tls;
  10754. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10755. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10756. ASSERT_TRUE(svr.is_valid());
  10757. svr.Get("/test", [](const Request &, Response &res) {
  10758. res.set_content("ok", "text/plain");
  10759. });
  10760. thread t([&]() { svr.listen(HOST, PORT); });
  10761. auto se = detail::scope_exit([&] {
  10762. svr.stop();
  10763. t.join();
  10764. });
  10765. svr.wait_until_ready();
  10766. bool verify_callback_called = false;
  10767. bool san_matched = false;
  10768. bool wrong_ipv6_matched = true;
  10769. bool cn_ipv6_matched = true;
  10770. SSLClient cli(HOST, PORT);
  10771. cli.enable_server_certificate_verification(true);
  10772. cli.set_ca_cert_path(CA_CERT_FILE);
  10773. cli.set_connection_timeout(5);
  10774. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10775. verify_callback_called = true;
  10776. if (!ctx.cert) return false;
  10777. // Matches the IPv6 iPAddress SAN.
  10778. san_matched = ctx.check_hostname("2001:db8::1");
  10779. // A different IPv6 address must not match.
  10780. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10781. // "::1" lives only in the CN, so it must not be accepted.
  10782. cn_ipv6_matched = ctx.check_hostname("::1");
  10783. return true; // Accept for the purpose of this test
  10784. });
  10785. cli.Get("/test");
  10786. ASSERT_TRUE(verify_callback_called)
  10787. << "Verify callback should have been called";
  10788. EXPECT_TRUE(san_matched)
  10789. << "verify_hostname should match an IPv6 iPAddress SAN";
  10790. EXPECT_FALSE(wrong_ipv6_matched)
  10791. << "verify_hostname should not match a non-matching IPv6 address";
  10792. EXPECT_FALSE(cn_ipv6_matched)
  10793. << "An IPv6 host must not be authenticated via the certificate CN";
  10794. }
  10795. #endif
  10796. // mbedTLS-specific callback constructor test
  10797. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10798. #ifdef CPPHTTPLIB_SSL_ENABLED
  10799. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10800. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10801. ASSERT_TRUE(svr.is_valid());
  10802. // Set up a handler to verify client certificate is present
  10803. bool client_cert_verified = false;
  10804. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10805. // Verify that client certificate was provided
  10806. client_cert_verified = true;
  10807. res.set_content("success", "text/plain");
  10808. });
  10809. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10810. auto se = detail::scope_exit([&] {
  10811. svr.stop();
  10812. t.join();
  10813. ASSERT_FALSE(svr.is_running());
  10814. });
  10815. svr.wait_until_ready();
  10816. // Client with certificate
  10817. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10818. cli.enable_server_certificate_verification(false);
  10819. cli.set_connection_timeout(30);
  10820. auto res = cli.Get("/test");
  10821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10822. ASSERT_EQ(StatusCode::OK_200, res->status);
  10823. ASSERT_TRUE(client_cert_verified);
  10824. EXPECT_EQ("success", res->body);
  10825. }
  10826. #endif
  10827. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10828. // backends
  10829. #ifdef CPPHTTPLIB_SSL_ENABLED
  10830. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10831. using namespace httplib::tls;
  10832. // Test that when client CA cert file is provided,
  10833. // the server properly requests and validates client certificates
  10834. // Create a server with client authentication
  10835. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10836. ASSERT_TRUE(svr.is_valid());
  10837. bool handler_called = false;
  10838. svr.Get("/test", [&](const Request &req, Response &res) {
  10839. handler_called = true;
  10840. // Verify that a client certificate was provided
  10841. auto cert = req.peer_cert();
  10842. ASSERT_TRUE(static_cast<bool>(cert));
  10843. // Get the issuer name
  10844. std::string issuer_str = cert.issuer_name();
  10845. ASSERT_FALSE(issuer_str.empty());
  10846. // The client certificate should be issued by our test CA
  10847. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10848. res.set_content("authenticated", "text/plain");
  10849. });
  10850. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10851. auto se = detail::scope_exit([&] {
  10852. svr.stop();
  10853. t.join();
  10854. ASSERT_FALSE(svr.is_running());
  10855. });
  10856. svr.wait_until_ready();
  10857. // Connect with a client certificate issued by the CA
  10858. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10859. cli.enable_server_certificate_verification(false);
  10860. cli.set_connection_timeout(30);
  10861. auto res = cli.Get("/test");
  10862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10863. ASSERT_EQ(StatusCode::OK_200, res->status);
  10864. ASSERT_TRUE(handler_called);
  10865. EXPECT_EQ("authenticated", res->body);
  10866. }
  10867. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10868. using namespace httplib::tls;
  10869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10870. ASSERT_TRUE(svr.is_valid());
  10871. svr.Get("/test", [](const Request &, Response &res) {
  10872. res.set_content("ok", "text/plain");
  10873. });
  10874. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10875. auto se = detail::scope_exit([&] {
  10876. svr.stop();
  10877. t.join();
  10878. });
  10879. svr.wait_until_ready();
  10880. SSLClient cli(HOST, PORT);
  10881. cli.enable_server_certificate_verification(false);
  10882. cli.set_connection_timeout(30);
  10883. bool cert_checked = false;
  10884. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10885. if (ctx.cert) {
  10886. auto sans = ctx.sans();
  10887. // Test certificate may or may not have SANs - just verify the API
  10888. // works If SANs exist, verify the types are valid
  10889. for (const auto &san : sans) {
  10890. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10891. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10892. san.type == SanType::OTHER);
  10893. EXPECT_FALSE(san.value.empty());
  10894. }
  10895. cert_checked = true;
  10896. }
  10897. return true;
  10898. });
  10899. auto res = cli.Get("/test");
  10900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10901. EXPECT_TRUE(cert_checked);
  10902. }
  10903. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10904. using namespace httplib::tls;
  10905. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10906. ASSERT_TRUE(svr.is_valid());
  10907. svr.Get("/test", [](const Request &, Response &res) {
  10908. res.set_content("ok", "text/plain");
  10909. });
  10910. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10911. auto se = detail::scope_exit([&] {
  10912. svr.stop();
  10913. t.join();
  10914. });
  10915. svr.wait_until_ready();
  10916. SSLClient cli(HOST, PORT);
  10917. cli.enable_server_certificate_verification(false);
  10918. cli.set_connection_timeout(30);
  10919. bool validity_checked = false;
  10920. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10921. if (ctx.cert) {
  10922. time_t not_before = 0, not_after = 0;
  10923. bool result = ctx.validity(not_before, not_after);
  10924. EXPECT_TRUE(result);
  10925. // Verify that not_before < now < not_after for a valid cert
  10926. time_t now = time(nullptr);
  10927. EXPECT_LT(not_before, now);
  10928. EXPECT_GT(not_after, now);
  10929. validity_checked = true;
  10930. }
  10931. return true;
  10932. });
  10933. auto res = cli.Get("/test");
  10934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10935. EXPECT_TRUE(validity_checked);
  10936. }
  10937. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10938. using namespace httplib::tls;
  10939. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10940. ASSERT_TRUE(svr.is_valid());
  10941. svr.Get("/test", [](const Request &, Response &res) {
  10942. res.set_content("ok", "text/plain");
  10943. });
  10944. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10945. auto se = detail::scope_exit([&] {
  10946. svr.stop();
  10947. t.join();
  10948. });
  10949. svr.wait_until_ready();
  10950. SSLClient cli(HOST, PORT);
  10951. cli.enable_server_certificate_verification(false);
  10952. cli.set_connection_timeout(30);
  10953. bool serial_checked = false;
  10954. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10955. if (ctx.cert) {
  10956. std::string serial = ctx.serial();
  10957. EXPECT_FALSE(serial.empty());
  10958. // Serial should be a hex string
  10959. for (char c : serial) {
  10960. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10961. (c >= 'a' && c <= 'f'));
  10962. }
  10963. serial_checked = true;
  10964. }
  10965. return true;
  10966. });
  10967. auto res = cli.Get("/test");
  10968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10969. EXPECT_TRUE(serial_checked);
  10970. }
  10971. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10972. // Test 1: Valid CA file - no error should be recorded
  10973. {
  10974. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10975. CLIENT_CA_CERT_FILE);
  10976. ASSERT_TRUE(svr.is_valid());
  10977. // With valid setup, last_ssl_error should be 0
  10978. EXPECT_EQ(0, svr.ssl_last_error());
  10979. }
  10980. // Test 2: Invalid CA file content
  10981. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10982. {
  10983. // Create a temporary file with completely invalid content
  10984. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10985. {
  10986. std::ofstream ofs(temp_invalid_ca);
  10987. ofs << "This is not a certificate file at all\n";
  10988. ofs << "Just plain text content\n";
  10989. }
  10990. // Create server with invalid CA file
  10991. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10992. // Clean up temporary file
  10993. std::remove(temp_invalid_ca);
  10994. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10995. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10996. // Note: SSL_CTX_load_verify_locations typically fails first,
  10997. // but our error handling code path is still exercised
  10998. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10999. }
  11000. }
  11001. TEST(VerifyCallbackTest, VerifyContextFields) {
  11002. using namespace httplib::tls;
  11003. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11004. ASSERT_TRUE(svr.is_valid());
  11005. svr.Get("/test", [](const Request &, Response &res) {
  11006. res.set_content("ok", "text/plain");
  11007. });
  11008. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11009. auto se = detail::scope_exit([&] {
  11010. svr.stop();
  11011. t.join();
  11012. });
  11013. svr.wait_until_ready();
  11014. SSLClient cli(HOST, PORT);
  11015. cli.enable_server_certificate_verification(false);
  11016. cli.set_connection_timeout(30);
  11017. int callback_count = 0;
  11018. bool saw_leaf_cert = false;
  11019. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11020. if (ctx.cert) {
  11021. callback_count++;
  11022. // We should see at least one certificate (the leaf)
  11023. std::string cn = ctx.subject_cn();
  11024. if (!cn.empty()) { saw_leaf_cert = true; }
  11025. // Verify context fields are populated
  11026. EXPECT_NE(ctx.session, nullptr);
  11027. EXPECT_GE(ctx.depth, 0);
  11028. }
  11029. return true;
  11030. });
  11031. auto res = cli.Get("/test");
  11032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11033. EXPECT_GT(callback_count, 0);
  11034. EXPECT_TRUE(saw_leaf_cert);
  11035. }
  11036. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  11037. using httplib::tls::TlsError;
  11038. // Test that verify_error_to_string returns empty for success
  11039. std::string success_str = TlsError::verify_error_to_string(0);
  11040. EXPECT_TRUE(success_str.empty());
  11041. // Test that verify_error_to_string returns non-empty for error codes
  11042. // Using a common error code (certificate expired)
  11043. std::string error_str =
  11044. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  11045. EXPECT_FALSE(error_str.empty());
  11046. }
  11047. TEST(SessionVerifierTest, CertificateAccepted) {
  11048. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11049. ASSERT_TRUE(svr.is_valid());
  11050. svr.Get("/test", [](const Request &, Response &res) {
  11051. res.set_content("ok", "text/plain");
  11052. });
  11053. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11054. auto se = detail::scope_exit([&] {
  11055. svr.stop();
  11056. t.join();
  11057. });
  11058. svr.wait_until_ready();
  11059. SSLClient cli(HOST, PORT);
  11060. cli.enable_server_certificate_verification(false);
  11061. cli.set_connection_timeout(30);
  11062. bool callback_called = false;
  11063. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11064. EXPECT_NE(session, nullptr);
  11065. callback_called = true;
  11066. return SSLVerifierResponse::CertificateAccepted;
  11067. });
  11068. auto res = cli.Get("/test");
  11069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11070. EXPECT_EQ(200, res->status);
  11071. EXPECT_TRUE(callback_called);
  11072. }
  11073. TEST(SessionVerifierTest, CertificateRejected) {
  11074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11075. ASSERT_TRUE(svr.is_valid());
  11076. svr.Get("/test", [](const Request &, Response &res) {
  11077. res.set_content("ok", "text/plain");
  11078. });
  11079. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11080. auto se = detail::scope_exit([&] {
  11081. svr.stop();
  11082. t.join();
  11083. });
  11084. svr.wait_until_ready();
  11085. SSLClient cli(HOST, PORT);
  11086. cli.enable_server_certificate_verification(false);
  11087. cli.set_connection_timeout(30);
  11088. bool callback_called = false;
  11089. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11090. EXPECT_NE(session, nullptr);
  11091. callback_called = true;
  11092. return SSLVerifierResponse::CertificateRejected;
  11093. });
  11094. auto res = cli.Get("/test");
  11095. EXPECT_FALSE(res);
  11096. EXPECT_TRUE(callback_called);
  11097. }
  11098. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  11099. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11100. ASSERT_TRUE(svr.is_valid());
  11101. svr.Get("/test", [](const Request &, Response &res) {
  11102. res.set_content("ok", "text/plain");
  11103. });
  11104. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11105. auto se = detail::scope_exit([&] {
  11106. svr.stop();
  11107. t.join();
  11108. });
  11109. svr.wait_until_ready();
  11110. // NoDecisionMade with verification disabled should succeed (no default check)
  11111. SSLClient cli(HOST, PORT);
  11112. cli.enable_server_certificate_verification(false);
  11113. cli.set_connection_timeout(30);
  11114. bool callback_called = false;
  11115. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11116. EXPECT_NE(session, nullptr);
  11117. callback_called = true;
  11118. return SSLVerifierResponse::NoDecisionMade;
  11119. });
  11120. auto res = cli.Get("/test");
  11121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11122. EXPECT_EQ(200, res->status);
  11123. EXPECT_TRUE(callback_called);
  11124. }
  11125. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  11126. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11127. ASSERT_TRUE(svr.is_valid());
  11128. svr.Get("/test", [](const Request &, Response &res) {
  11129. res.set_content("ok", "text/plain");
  11130. });
  11131. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11132. auto se = detail::scope_exit([&] {
  11133. svr.stop();
  11134. t.join();
  11135. });
  11136. svr.wait_until_ready();
  11137. // NoDecisionMade with verification enabled should fail (self-signed cert).
  11138. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  11139. // so we only check that the request fails, not whether the callback was
  11140. // called.
  11141. SSLClient cli(HOST, PORT);
  11142. cli.enable_server_certificate_verification(true);
  11143. cli.set_connection_timeout(30);
  11144. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11145. EXPECT_NE(session, nullptr);
  11146. return SSLVerifierResponse::NoDecisionMade;
  11147. });
  11148. auto res = cli.Get("/test");
  11149. EXPECT_FALSE(res);
  11150. }
  11151. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11152. // Test SSL server using PemMemory constructor with client CA certificates
  11153. // Read PEM files
  11154. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11155. read_file(SERVER_CERT_FILE, server_cert_pem);
  11156. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11157. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11158. // Create SSLServer with PemMemory constructor including client CA
  11159. SSLServer::PemMemory server_pem = {
  11160. server_cert_pem.c_str(),
  11161. server_cert_pem.size(),
  11162. server_key_pem.c_str(),
  11163. server_key_pem.size(),
  11164. client_ca_pem.c_str(),
  11165. client_ca_pem.size(),
  11166. nullptr // no password for server key
  11167. };
  11168. SSLServer svr(server_pem);
  11169. ASSERT_TRUE(svr.is_valid());
  11170. // No SSL error should be recorded for valid setup
  11171. EXPECT_EQ(0, svr.ssl_last_error());
  11172. // Set up server endpoints
  11173. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11174. res.set_content("ok", "text/plain");
  11175. });
  11176. // Start server in a thread
  11177. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11178. svr.wait_until_ready();
  11179. // Connect with client certificate (using constructor with paths)
  11180. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11181. cli.enable_server_certificate_verification(false);
  11182. auto res = cli.Get("/test-pem-ca");
  11183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11184. EXPECT_EQ(200, res->status);
  11185. EXPECT_EQ("ok", res->body);
  11186. svr.stop();
  11187. server_thread.join();
  11188. }
  11189. #endif
  11190. #ifdef _WIN32
  11191. TEST(CleanupTest, WSACleanup) {
  11192. int ret = WSACleanup();
  11193. ASSERT_EQ(0, ret);
  11194. }
  11195. #endif
  11196. #ifndef CPPHTTPLIB_SSL_ENABLED
  11197. TEST(NoSSLSupport, SimpleInterface) {
  11198. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11199. }
  11200. #endif
  11201. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11202. TEST(InvalidScheme, SimpleInterface) {
  11203. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11204. }
  11205. #endif
  11206. TEST(NoScheme, SimpleInterface) {
  11207. Client cli("yahoo.com:80");
  11208. ASSERT_TRUE(cli.is_valid());
  11209. }
  11210. TEST(SendAPI, SimpleInterface_Online) {
  11211. Client cli("http://yahoo.com");
  11212. Request req;
  11213. req.method = "GET";
  11214. req.path = "/";
  11215. auto res = cli.send(req);
  11216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11217. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11218. }
  11219. TEST(SendAPI, WithParamsInRequest) {
  11220. Server svr;
  11221. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11222. EXPECT_TRUE(req.has_param("test"));
  11223. EXPECT_EQ("test_value", req.get_param_value("test"));
  11224. });
  11225. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11226. auto se = detail::scope_exit([&] {
  11227. svr.stop();
  11228. t.join();
  11229. ASSERT_FALSE(svr.is_running());
  11230. });
  11231. svr.wait_until_ready();
  11232. Client cli(HOST, PORT);
  11233. {
  11234. Request req;
  11235. req.method = "GET";
  11236. req.path = "/";
  11237. req.params.emplace("test", "test_value");
  11238. auto res = cli.send(req);
  11239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11240. }
  11241. {
  11242. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11244. }
  11245. }
  11246. TEST(ClientImplMethods, GetSocketTest) {
  11247. httplib::Server svr;
  11248. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11249. res.status = StatusCode::OK_200;
  11250. });
  11251. auto port = svr.bind_to_any_port("127.0.0.1");
  11252. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11253. auto se = detail::scope_exit([&] {
  11254. svr.stop();
  11255. thread.join();
  11256. ASSERT_FALSE(svr.is_running());
  11257. });
  11258. svr.wait_until_ready();
  11259. {
  11260. httplib::Client cli("127.0.0.1", port);
  11261. cli.set_keep_alive(true);
  11262. // Use the behavior of cpp-httplib of opening the connection
  11263. // only when the first request happens. If that changes,
  11264. // this test would be obsolete.
  11265. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11266. // This also implicitly tests the server. But other tests would fail much
  11267. // earlier than this one to be considered.
  11268. auto res = cli.Get("/");
  11269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11270. EXPECT_EQ(StatusCode::OK_200, res->status);
  11271. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11272. }
  11273. }
  11274. #ifdef CPPHTTPLIB_SSL_ENABLED
  11275. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11276. Client cli("http://yahoo.com");
  11277. auto res = cli.Get("/");
  11278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11279. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11280. cli.set_follow_location(true);
  11281. res = cli.Get("/");
  11282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11283. EXPECT_EQ(StatusCode::OK_200, res->status);
  11284. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11285. }
  11286. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11287. Client cli("https://yahoo.com");
  11288. auto res = cli.Get("/");
  11289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11290. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11291. cli.set_follow_location(true);
  11292. res = cli.Get("/");
  11293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11294. EXPECT_EQ(StatusCode::OK_200, res->status);
  11295. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11296. }
  11297. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11298. Client cli("https://yahoo.com");
  11299. auto res = cli.Get("/");
  11300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11301. ASSERT_FALSE(!res);
  11302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11303. ASSERT_FALSE(res == nullptr);
  11304. ASSERT_TRUE(res != nullptr);
  11305. EXPECT_EQ(Error::Success, res.error());
  11306. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11307. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11308. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11309. cli.set_follow_location(true);
  11310. res = cli.Get("/");
  11311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11312. EXPECT_EQ(Error::Success, res.error());
  11313. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11314. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11315. EXPECT_EQ(StatusCode::OK_200, res->status);
  11316. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11317. }
  11318. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11319. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11320. Client cli("https://cdnjs.cloudflare.com");
  11321. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11322. Headers{{"Accept-Encoding", "br"}});
  11323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11324. EXPECT_EQ(StatusCode::OK_200, res->status);
  11325. EXPECT_EQ(287630U, res->body.size());
  11326. EXPECT_EQ("application/javascript; charset=utf-8",
  11327. res->get_header_value("Content-Type"));
  11328. }
  11329. #endif
  11330. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11331. #undef REDIR_HOST // Silence compiler warning
  11332. #define REDIR_HOST "https://httpbingo.org"
  11333. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11334. Client cli(REDIR_HOST);
  11335. cli.set_follow_location(true);
  11336. auto res =
  11337. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11339. EXPECT_EQ(StatusCode::OK_200, res->status);
  11340. }
  11341. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11342. Client cli(REDIR_HOST);
  11343. cli.set_follow_location(true);
  11344. Params params;
  11345. params.emplace("url", "http://example.com");
  11346. params.emplace("status_code", "302");
  11347. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11349. EXPECT_EQ(StatusCode::OK_200, res->status);
  11350. }
  11351. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11352. Client cli(REDIR_HOST);
  11353. cli.set_follow_location(true);
  11354. Params params;
  11355. params.emplace("url", "http://example.com");
  11356. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11358. EXPECT_EQ(StatusCode::OK_200, res->status);
  11359. }
  11360. TEST(HttpToHttpsRedirectTest, CertFile) {
  11361. auto ssl_port = PORT + 1;
  11362. Server svr;
  11363. ASSERT_TRUE(svr.is_valid());
  11364. svr.Get("/index", [&](const Request &, Response &res) {
  11365. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11366. "/index");
  11367. svr.stop();
  11368. });
  11369. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11370. ASSERT_TRUE(ssl_svr.is_valid());
  11371. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11372. res.set_content("test", "text/plain");
  11373. ssl_svr.stop();
  11374. });
  11375. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11376. thread t2 =
  11377. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11378. auto se = detail::scope_exit([&] {
  11379. t2.join();
  11380. t.join();
  11381. ASSERT_FALSE(svr.is_running());
  11382. });
  11383. svr.wait_until_ready();
  11384. ssl_svr.wait_until_ready();
  11385. Client cli("127.0.0.1", PORT);
  11386. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11387. cli.enable_server_certificate_verification(true);
  11388. cli.set_follow_location(true);
  11389. cli.set_connection_timeout(30);
  11390. auto res = cli.Get("/index");
  11391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11392. ASSERT_EQ(StatusCode::OK_200, res->status);
  11393. }
  11394. TEST(SSLClientRedirectTest, CertFile) {
  11395. auto ssl_port = PORT + 1;
  11396. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11397. ASSERT_TRUE(ssl_svr1.is_valid());
  11398. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11399. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11400. "/index");
  11401. ssl_svr1.stop();
  11402. });
  11403. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11404. ASSERT_TRUE(ssl_svr2.is_valid());
  11405. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11406. res.set_content("test", "text/plain");
  11407. ssl_svr2.stop();
  11408. });
  11409. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11410. thread t2 =
  11411. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11412. auto se = detail::scope_exit([&] {
  11413. t2.join();
  11414. t.join();
  11415. ASSERT_FALSE(ssl_svr1.is_running());
  11416. });
  11417. ssl_svr1.wait_until_ready();
  11418. ssl_svr2.wait_until_ready();
  11419. SSLClient cli("127.0.0.1", PORT);
  11420. std::string cert;
  11421. read_file(SERVER_CERT2_FILE, cert);
  11422. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11423. cli.enable_server_certificate_verification(true);
  11424. cli.set_follow_location(true);
  11425. cli.set_connection_timeout(30);
  11426. auto res = cli.Get("/index");
  11427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11428. ASSERT_EQ(StatusCode::OK_200, res->status);
  11429. }
  11430. #endif
  11431. #ifdef CPPHTTPLIB_SSL_ENABLED
  11432. // Test that set_ca_cert_store() skips system certs (consistent with
  11433. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11434. // should be trusted - system certs should NOT be loaded.
  11435. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11436. // Load a specific cert that is NOT a system CA cert
  11437. std::string cert;
  11438. read_file(SERVER_CERT2_FILE, cert);
  11439. SSLClient cli("google.com");
  11440. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11441. cli.enable_server_certificate_verification(true);
  11442. // This should FAIL because:
  11443. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11444. // 2. System certs should NOT be loaded when custom store is set
  11445. // If system certs WERE loaded, this would succeed
  11446. auto res = cli.Get("/");
  11447. ASSERT_FALSE(res);
  11448. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11449. }
  11450. // Same as above, but through the native store handle path. Regression test:
  11451. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11452. // merged system certs into the user-provided store.
  11453. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11454. std::string cert;
  11455. read_file(SERVER_CERT2_FILE, cert);
  11456. SSLClient cli("google.com");
  11457. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11458. cli.enable_server_certificate_verification(true);
  11459. auto res = cli.Get("/");
  11460. ASSERT_FALSE(res);
  11461. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11462. }
  11463. // A custom store set via the native handle must still verify a server whose
  11464. // cert it does contain.
  11465. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11466. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11467. ASSERT_TRUE(svr.is_valid());
  11468. svr.Get("/test", [&](const Request &, Response &res) {
  11469. res.set_content("test", "text/plain");
  11470. });
  11471. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11472. auto se = detail::scope_exit([&] {
  11473. svr.stop();
  11474. t.join();
  11475. ASSERT_FALSE(svr.is_running());
  11476. });
  11477. svr.wait_until_ready();
  11478. SSLClient cli("127.0.0.1", PORT);
  11479. std::string cert;
  11480. read_file(SERVER_CERT2_FILE, cert);
  11481. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11482. cli.enable_server_certificate_verification(true);
  11483. cli.set_connection_timeout(30);
  11484. auto res = cli.Get("/test");
  11485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11486. ASSERT_EQ(StatusCode::OK_200, res->status);
  11487. }
  11488. // CA certs loaded through the universal Client must be transferred to the
  11489. // client created internally for following an HTTPS redirect. Regression test:
  11490. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11491. // the CA data for redirect transfer.
  11492. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11493. auto ssl_port = PORT + 1;
  11494. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11495. ASSERT_TRUE(ssl_svr1.is_valid());
  11496. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11497. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11498. "/index");
  11499. });
  11500. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11501. ASSERT_TRUE(ssl_svr2.is_valid());
  11502. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11503. res.set_content("test", "text/plain");
  11504. });
  11505. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11506. thread t2 =
  11507. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11508. auto se = detail::scope_exit([&] {
  11509. ssl_svr2.stop();
  11510. ssl_svr1.stop();
  11511. t2.join();
  11512. t.join();
  11513. ASSERT_FALSE(ssl_svr1.is_running());
  11514. });
  11515. ssl_svr1.wait_until_ready();
  11516. ssl_svr2.wait_until_ready();
  11517. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11518. std::string cert;
  11519. read_file(SERVER_CERT2_FILE, cert);
  11520. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11521. cli.enable_server_certificate_verification(true);
  11522. cli.set_follow_location(true);
  11523. cli.set_connection_timeout(30);
  11524. auto res = cli.Get("/index");
  11525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11526. ASSERT_EQ(StatusCode::OK_200, res->status);
  11527. }
  11528. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11529. // so a host signed by a system CA verifies even though a custom CA is set
  11530. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11531. std::string cert;
  11532. read_file(SERVER_CERT2_FILE, cert);
  11533. SSLClient cli("google.com");
  11534. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11535. cli.enable_system_ca(true);
  11536. cli.enable_server_certificate_verification(true);
  11537. auto res = cli.Get("/");
  11538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11539. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11540. }
  11541. // The custom CA remains effective when combined with the system CA
  11542. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11543. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11544. ASSERT_TRUE(svr.is_valid());
  11545. svr.Get("/test", [&](const Request &, Response &res) {
  11546. res.set_content("test", "text/plain");
  11547. });
  11548. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11549. auto se = detail::scope_exit([&] {
  11550. svr.stop();
  11551. t.join();
  11552. ASSERT_FALSE(svr.is_running());
  11553. });
  11554. svr.wait_until_ready();
  11555. SSLClient cli("127.0.0.1", PORT);
  11556. std::string cert;
  11557. read_file(SERVER_CERT2_FILE, cert);
  11558. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11559. cli.enable_system_ca(true);
  11560. cli.enable_server_certificate_verification(true);
  11561. cli.set_connection_timeout(30);
  11562. auto res = cli.Get("/test");
  11563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11564. ASSERT_EQ(StatusCode::OK_200, res->status);
  11565. }
  11566. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11567. // skip chain verification entirely (only the certificate identity was
  11568. // checked), so a server presenting an untrusted certificate with a matching
  11569. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11570. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11571. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11572. ASSERT_TRUE(svr.is_valid());
  11573. svr.Get("/test", [&](const Request &, Response &res) {
  11574. res.set_content("test", "text/plain");
  11575. });
  11576. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11577. auto se = detail::scope_exit([&] {
  11578. svr.stop();
  11579. t.join();
  11580. ASSERT_FALSE(svr.is_running());
  11581. });
  11582. svr.wait_until_ready();
  11583. SSLClient cli("127.0.0.1", PORT);
  11584. std::string cert;
  11585. // A trusted CA that did not sign the server certificate. The server cert
  11586. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11587. // this connection.
  11588. read_file(CLIENT_CA_CERT_FILE, cert);
  11589. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11590. cli.enable_server_certificate_verification(true);
  11591. cli.set_connection_timeout(30);
  11592. auto res = cli.Get("/test");
  11593. ASSERT_FALSE(res);
  11594. }
  11595. // enable_system_ca(false) prevents system CA loading entirely
  11596. TEST(SSLClientTest, DisableSystemCa_Online) {
  11597. SSLClient cli("google.com");
  11598. cli.enable_system_ca(false);
  11599. cli.enable_server_certificate_verification(true);
  11600. auto res = cli.Get("/");
  11601. ASSERT_FALSE(res);
  11602. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11603. // itself when the CA chain is empty
  11604. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11605. res.error() == Error::SSLConnection);
  11606. }
  11607. // The universal Client forwards enable_system_ca()
  11608. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11609. std::string cert;
  11610. read_file(SERVER_CERT2_FILE, cert);
  11611. Client cli("https://google.com");
  11612. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11613. cli.enable_system_ca(true);
  11614. cli.enable_server_certificate_verification(true);
  11615. auto res = cli.Get("/");
  11616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11617. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11618. }
  11619. // The system CA policy must carry over to the client created internally for
  11620. // following a cross-host HTTPS redirect
  11621. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11622. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11623. ASSERT_TRUE(svr.is_valid());
  11624. svr.Get("/index", [&](const Request &, Response &res) {
  11625. res.set_redirect("https://www.google.com/");
  11626. });
  11627. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11628. auto se = detail::scope_exit([&] {
  11629. svr.stop();
  11630. t.join();
  11631. ASSERT_FALSE(svr.is_running());
  11632. });
  11633. svr.wait_until_ready();
  11634. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11635. std::string cert;
  11636. read_file(SERVER_CERT2_FILE, cert);
  11637. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11638. cli.enable_system_ca(true);
  11639. cli.enable_server_certificate_verification(true);
  11640. cli.set_follow_location(true);
  11641. cli.set_connection_timeout(30);
  11642. // Receiving any response proves the redirect client completed the TLS
  11643. // handshake with a system-CA-signed host
  11644. auto res = cli.Get("/index");
  11645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11646. }
  11647. TEST(MultipartFormDataTest, LargeData) {
  11648. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11649. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11650. const ContentReader &content_reader) {
  11651. if (req.is_multipart_form_data()) {
  11652. std::vector<FormData> items;
  11653. content_reader(
  11654. [&](const FormData &file) {
  11655. items.push_back(file);
  11656. return true;
  11657. },
  11658. [&](const char *data, size_t data_length) {
  11659. items.back().content.append(data, data_length);
  11660. return true;
  11661. });
  11662. EXPECT_TRUE(std::string(items[0].name) == "document");
  11663. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11664. EXPECT_TRUE(items[0].filename == "2MB_data");
  11665. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11666. EXPECT_TRUE(items[1].name == "hello");
  11667. EXPECT_TRUE(items[1].content == "world");
  11668. EXPECT_TRUE(items[1].filename == "");
  11669. EXPECT_TRUE(items[1].content_type == "");
  11670. } else {
  11671. std::string body;
  11672. content_reader([&](const char *data, size_t data_length) {
  11673. body.append(data, data_length);
  11674. return true;
  11675. });
  11676. }
  11677. });
  11678. auto port = svr.bind_to_any_port(HOST);
  11679. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11680. auto se = detail::scope_exit([&] {
  11681. svr.stop();
  11682. t.join();
  11683. ASSERT_FALSE(svr.is_running());
  11684. });
  11685. svr.wait_until_ready();
  11686. {
  11687. std::string data(1024 * 1024 * 2, '.');
  11688. std::stringstream buffer;
  11689. buffer << data;
  11690. SSLClient cli(HOST, port);
  11691. cli.enable_server_certificate_verification(false);
  11692. UploadFormDataItems items{
  11693. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11694. {"hello", "world", "", ""},
  11695. };
  11696. auto res = cli.Post("/post", items);
  11697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11698. ASSERT_EQ(StatusCode::OK_200, res->status);
  11699. }
  11700. }
  11701. TEST(MultipartFormDataTest, DataProviderItems) {
  11702. std::random_device seed_gen;
  11703. std::mt19937 random(seed_gen());
  11704. std::string rand1;
  11705. rand1.resize(1000);
  11706. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11707. std::string rand2;
  11708. rand2.resize(3000);
  11709. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11710. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11711. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11712. const ContentReader &content_reader) {
  11713. ASSERT_FALSE(req.is_multipart_form_data());
  11714. std::string body;
  11715. content_reader([&](const char *data, size_t data_length) {
  11716. body.append(data, data_length);
  11717. return true;
  11718. });
  11719. EXPECT_EQ(body, "");
  11720. });
  11721. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11722. const ContentReader &content_reader) {
  11723. ASSERT_TRUE(req.is_multipart_form_data());
  11724. std::vector<FormData> items;
  11725. content_reader(
  11726. [&](const FormData &file) {
  11727. items.push_back(file);
  11728. return true;
  11729. },
  11730. [&](const char *data, size_t data_length) {
  11731. items.back().content.append(data, data_length);
  11732. return true;
  11733. });
  11734. ASSERT_TRUE(items.size() == 2);
  11735. EXPECT_EQ(std::string(items[0].name), "name1");
  11736. EXPECT_EQ(items[0].content, "Testing123");
  11737. EXPECT_EQ(items[0].filename, "filename1");
  11738. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11739. EXPECT_EQ(items[1].name, "name2");
  11740. EXPECT_EQ(items[1].content, "Testing456");
  11741. EXPECT_EQ(items[1].filename, "");
  11742. EXPECT_EQ(items[1].content_type, "");
  11743. });
  11744. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11745. const ContentReader &content_reader) {
  11746. ASSERT_TRUE(req.is_multipart_form_data());
  11747. std::vector<FormData> items;
  11748. content_reader(
  11749. [&](const FormData &file) {
  11750. items.push_back(file);
  11751. return true;
  11752. },
  11753. [&](const char *data, size_t data_length) {
  11754. items.back().content.append(data, data_length);
  11755. return true;
  11756. });
  11757. ASSERT_TRUE(items.size() == 2);
  11758. EXPECT_EQ(items[0].name, "name3");
  11759. EXPECT_EQ(items[0].content, rand1);
  11760. EXPECT_EQ(items[0].filename, "filename3");
  11761. EXPECT_EQ(items[0].content_type, "");
  11762. EXPECT_EQ(items[1].name, "name4");
  11763. EXPECT_EQ(items[1].content, rand2);
  11764. EXPECT_EQ(items[1].filename, "filename4");
  11765. EXPECT_EQ(items[1].content_type, "");
  11766. });
  11767. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11768. const ContentReader &content_reader) {
  11769. ASSERT_TRUE(req.is_multipart_form_data());
  11770. std::vector<FormData> items;
  11771. content_reader(
  11772. [&](const FormData &file) {
  11773. items.push_back(file);
  11774. return true;
  11775. },
  11776. [&](const char *data, size_t data_length) {
  11777. items.back().content.append(data, data_length);
  11778. return true;
  11779. });
  11780. ASSERT_TRUE(items.size() == 4);
  11781. EXPECT_EQ(std::string(items[0].name), "name1");
  11782. EXPECT_EQ(items[0].content, "Testing123");
  11783. EXPECT_EQ(items[0].filename, "filename1");
  11784. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11785. EXPECT_EQ(items[1].name, "name2");
  11786. EXPECT_EQ(items[1].content, "Testing456");
  11787. EXPECT_EQ(items[1].filename, "");
  11788. EXPECT_EQ(items[1].content_type, "");
  11789. EXPECT_EQ(items[2].name, "name3");
  11790. EXPECT_EQ(items[2].content, rand1);
  11791. EXPECT_EQ(items[2].filename, "filename3");
  11792. EXPECT_EQ(items[2].content_type, "");
  11793. EXPECT_EQ(items[3].name, "name4");
  11794. EXPECT_EQ(items[3].content, rand2);
  11795. EXPECT_EQ(items[3].filename, "filename4");
  11796. EXPECT_EQ(items[3].content_type, "");
  11797. });
  11798. auto port = svr.bind_to_any_port("localhost");
  11799. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11800. auto se = detail::scope_exit([&] {
  11801. svr.stop();
  11802. t.join();
  11803. ASSERT_FALSE(svr.is_running());
  11804. });
  11805. svr.wait_until_ready();
  11806. {
  11807. SSLClient cli("localhost", port);
  11808. cli.enable_server_certificate_verification(false);
  11809. UploadFormDataItems items{
  11810. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11811. {"name2", "Testing456", "", ""}, // not a file
  11812. };
  11813. {
  11814. auto res = cli.Post("/post-none", {}, {}, {});
  11815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11816. ASSERT_EQ(StatusCode::OK_200, res->status);
  11817. }
  11818. FormDataProviderItems providers;
  11819. {
  11820. auto res =
  11821. cli.Post("/post-items", {}, items, providers); // empty providers
  11822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11823. ASSERT_EQ(StatusCode::OK_200, res->status);
  11824. }
  11825. providers.push_back({"name3",
  11826. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11827. // test the offset is given correctly at each step
  11828. if (!offset)
  11829. sink.os.write(rand1.data(), 30);
  11830. else if (offset == 30)
  11831. sink.os.write(rand1.data() + 30, 300);
  11832. else if (offset == 330)
  11833. sink.os.write(rand1.data() + 330, 670);
  11834. else if (offset == rand1.size())
  11835. sink.done();
  11836. return true;
  11837. },
  11838. "filename3",
  11839. {}});
  11840. providers.push_back({"name4",
  11841. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11842. // test the offset is given correctly at each step
  11843. if (!offset)
  11844. sink.os.write(rand2.data(), 2000);
  11845. else if (offset == 2000)
  11846. sink.os.write(rand2.data() + 2000, 1);
  11847. else if (offset == 2001)
  11848. sink.os.write(rand2.data() + 2001, 999);
  11849. else if (offset == rand2.size())
  11850. sink.done();
  11851. return true;
  11852. },
  11853. "filename4",
  11854. {}});
  11855. {
  11856. auto res = cli.Post("/post-providers", {}, {}, providers);
  11857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11858. ASSERT_EQ(StatusCode::OK_200, res->status);
  11859. }
  11860. {
  11861. auto res = cli.Post("/post-both", {}, items, providers);
  11862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11863. ASSERT_EQ(StatusCode::OK_200, res->status);
  11864. }
  11865. }
  11866. }
  11867. TEST(MultipartFormDataTest, BadHeader) {
  11868. Server svr;
  11869. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11870. res.set_content("ok", "text/plain");
  11871. });
  11872. thread t = thread([&] { svr.listen(HOST, PORT); });
  11873. auto se = detail::scope_exit([&] {
  11874. svr.stop();
  11875. t.join();
  11876. ASSERT_FALSE(svr.is_running());
  11877. });
  11878. svr.wait_until_ready();
  11879. const std::string body =
  11880. "This is the preamble. It is to be ignored, though it\r\n"
  11881. "is a handy place for composition agents to include an\r\n"
  11882. "explanatory note to non-MIME conformant readers.\r\n"
  11883. "\r\n"
  11884. "\r\n"
  11885. "--simple boundary\r\n"
  11886. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11887. ": BAD...\r\n"
  11888. "\r\n"
  11889. "value1\r\n"
  11890. "--simple boundary\r\n"
  11891. "Content-Disposition: form-data; name=\"field2\"; "
  11892. "filename=\"example.txt\"\r\n"
  11893. "\r\n"
  11894. "value2\r\n"
  11895. "--simple boundary--\r\n"
  11896. "This is the epilogue. It is also to be ignored.\r\n";
  11897. std::string content_type =
  11898. R"(multipart/form-data; boundary="simple boundary")";
  11899. Client cli(HOST, PORT);
  11900. auto res = cli.Post("/post", body, content_type.c_str());
  11901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11902. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11903. }
  11904. TEST(MultipartFormDataTest, WithPreamble) {
  11905. Server svr;
  11906. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11907. res.set_content("ok", "text/plain");
  11908. });
  11909. thread t = thread([&] { svr.listen(HOST, PORT); });
  11910. auto se = detail::scope_exit([&] {
  11911. svr.stop();
  11912. t.join();
  11913. ASSERT_FALSE(svr.is_running());
  11914. });
  11915. svr.wait_until_ready();
  11916. const std::string body =
  11917. "This is the preamble. It is to be ignored, though it\r\n"
  11918. "is a handy place for composition agents to include an\r\n"
  11919. "explanatory note to non-MIME conformant readers.\r\n"
  11920. "\r\n"
  11921. "\r\n"
  11922. "--simple boundary\r\n"
  11923. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11924. "\r\n"
  11925. "value1\r\n"
  11926. "--simple boundary\r\n"
  11927. "Content-Disposition: form-data; name=\"field2\"; "
  11928. "filename=\"example.txt\"\r\n"
  11929. "\r\n"
  11930. "value2\r\n"
  11931. "--simple boundary--\r\n"
  11932. "This is the epilogue. It is also to be ignored.\r\n";
  11933. std::string content_type =
  11934. R"(multipart/form-data; boundary="simple boundary")";
  11935. Client cli(HOST, PORT);
  11936. auto res = cli.Post("/post", body, content_type.c_str());
  11937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11938. EXPECT_EQ(StatusCode::OK_200, res->status);
  11939. }
  11940. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11942. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11943. const ContentReader &content_reader) {
  11944. if (req.is_multipart_form_data()) {
  11945. std::vector<FormData> items;
  11946. content_reader(
  11947. [&](const FormData &file) {
  11948. items.push_back(file);
  11949. return true;
  11950. },
  11951. [&](const char *data, size_t data_length) {
  11952. items.back().content.append(data, data_length);
  11953. return true;
  11954. });
  11955. EXPECT_TRUE(std::string(items[0].name) == "document");
  11956. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11957. EXPECT_TRUE(items[0].filename == "2MB_data");
  11958. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11959. EXPECT_TRUE(items[1].name == "hello");
  11960. EXPECT_TRUE(items[1].content == "world");
  11961. EXPECT_TRUE(items[1].filename == "");
  11962. EXPECT_TRUE(items[1].content_type == "");
  11963. } else {
  11964. std::string body;
  11965. content_reader([&](const char *data, size_t data_length) {
  11966. body.append(data, data_length);
  11967. return true;
  11968. });
  11969. }
  11970. });
  11971. auto port = svr.bind_to_any_port("localhost");
  11972. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11973. auto se = detail::scope_exit([&] {
  11974. svr.stop();
  11975. t.join();
  11976. ASSERT_FALSE(svr.is_running());
  11977. });
  11978. svr.wait_until_ready();
  11979. {
  11980. std::string data(1024 * 1024 * 2, '.');
  11981. std::stringstream buffer;
  11982. buffer << data;
  11983. SSLClient cli("localhost", port);
  11984. cli.enable_server_certificate_verification(false);
  11985. UploadFormDataItems items{
  11986. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11987. {"hello", "world", "", ""},
  11988. };
  11989. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11991. ASSERT_EQ(StatusCode::OK_200, res->status);
  11992. }
  11993. }
  11994. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11995. std::string data(1024 * 1024 * 2, '&');
  11996. std::stringstream buffer;
  11997. buffer << data;
  11998. Client cli("https://localhost:8080");
  11999. UploadFormDataItems items{
  12000. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12001. {"hello", "world", "", ""},
  12002. };
  12003. for (const char &c : " \t\r\n") {
  12004. auto res =
  12005. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  12006. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12007. ASSERT_FALSE(res);
  12008. }
  12009. }
  12010. TEST(MultipartFormDataTest, PutFormData) {
  12011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12012. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  12013. const ContentReader &content_reader) {
  12014. if (req.is_multipart_form_data()) {
  12015. std::vector<FormData> items;
  12016. content_reader(
  12017. [&](const FormData &file) {
  12018. items.push_back(file);
  12019. return true;
  12020. },
  12021. [&](const char *data, size_t data_length) {
  12022. items.back().content.append(data, data_length);
  12023. return true;
  12024. });
  12025. EXPECT_TRUE(std::string(items[0].name) == "document");
  12026. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12027. EXPECT_TRUE(items[0].filename == "2MB_data");
  12028. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12029. EXPECT_TRUE(items[1].name == "hello");
  12030. EXPECT_TRUE(items[1].content == "world");
  12031. EXPECT_TRUE(items[1].filename == "");
  12032. EXPECT_TRUE(items[1].content_type == "");
  12033. } else {
  12034. std::string body;
  12035. content_reader([&](const char *data, size_t data_length) {
  12036. body.append(data, data_length);
  12037. return true;
  12038. });
  12039. }
  12040. });
  12041. auto port = svr.bind_to_any_port("localhost");
  12042. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12043. auto se = detail::scope_exit([&] {
  12044. svr.stop();
  12045. t.join();
  12046. ASSERT_FALSE(svr.is_running());
  12047. });
  12048. svr.wait_until_ready();
  12049. {
  12050. std::string data(1024 * 1024 * 2, '&');
  12051. std::stringstream buffer;
  12052. buffer << data;
  12053. SSLClient cli("localhost", port);
  12054. cli.enable_server_certificate_verification(false);
  12055. UploadFormDataItems items{
  12056. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12057. {"hello", "world", "", ""},
  12058. };
  12059. auto res = cli.Put("/put", items);
  12060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12061. ASSERT_EQ(StatusCode::OK_200, res->status);
  12062. }
  12063. }
  12064. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  12065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12066. svr.Put("/put_customboundary",
  12067. [&](const Request &req, const Response & /*res*/,
  12068. const ContentReader &content_reader) {
  12069. if (req.is_multipart_form_data()) {
  12070. std::vector<FormData> items;
  12071. content_reader(
  12072. [&](const FormData &file) {
  12073. items.push_back(file);
  12074. return true;
  12075. },
  12076. [&](const char *data, size_t data_length) {
  12077. items.back().content.append(data, data_length);
  12078. return true;
  12079. });
  12080. EXPECT_TRUE(std::string(items[0].name) == "document");
  12081. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12082. EXPECT_TRUE(items[0].filename == "2MB_data");
  12083. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12084. EXPECT_TRUE(items[1].name == "hello");
  12085. EXPECT_TRUE(items[1].content == "world");
  12086. EXPECT_TRUE(items[1].filename == "");
  12087. EXPECT_TRUE(items[1].content_type == "");
  12088. } else {
  12089. std::string body;
  12090. content_reader([&](const char *data, size_t data_length) {
  12091. body.append(data, data_length);
  12092. return true;
  12093. });
  12094. }
  12095. });
  12096. auto port = svr.bind_to_any_port("localhost");
  12097. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12098. auto se = detail::scope_exit([&] {
  12099. svr.stop();
  12100. t.join();
  12101. ASSERT_FALSE(svr.is_running());
  12102. });
  12103. svr.wait_until_ready();
  12104. {
  12105. std::string data(1024 * 1024 * 2, '&');
  12106. std::stringstream buffer;
  12107. buffer << data;
  12108. SSLClient cli("localhost", port);
  12109. cli.enable_server_certificate_verification(false);
  12110. UploadFormDataItems items{
  12111. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12112. {"hello", "world", "", ""},
  12113. };
  12114. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  12115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12116. ASSERT_EQ(StatusCode::OK_200, res->status);
  12117. }
  12118. }
  12119. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  12120. std::string data(1024 * 1024 * 2, '&');
  12121. std::stringstream buffer;
  12122. buffer << data;
  12123. Client cli("https://localhost:8080");
  12124. cli.enable_server_certificate_verification(false);
  12125. UploadFormDataItems items{
  12126. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12127. {"hello", "world", "", ""},
  12128. };
  12129. for (const char &c : " \t\r\n") {
  12130. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  12131. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12132. ASSERT_FALSE(res);
  12133. }
  12134. }
  12135. TEST(MultipartFormDataTest, AlternateFilename) {
  12136. auto handled = false;
  12137. Server svr;
  12138. svr.Post("/test", [&](const Request &req, Response &res) {
  12139. ASSERT_EQ(2u, req.form.files.size());
  12140. ASSERT_EQ(1u, req.form.fields.size());
  12141. // Test files
  12142. const auto &file1 = req.form.get_file("file1");
  12143. ASSERT_EQ("file1", file1.name);
  12144. ASSERT_EQ("A.txt", file1.filename);
  12145. ASSERT_EQ("text/plain", file1.content_type);
  12146. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  12147. const auto &file2 = req.form.get_file("file2");
  12148. ASSERT_EQ("file2", file2.name);
  12149. ASSERT_EQ("a.html", file2.filename);
  12150. ASSERT_EQ("text/html", file2.content_type);
  12151. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12152. file2.content);
  12153. // Test text field
  12154. const auto &text = req.form.get_field("text");
  12155. ASSERT_EQ("text default", text);
  12156. res.set_content("ok", "text/plain");
  12157. handled = true;
  12158. });
  12159. thread t = thread([&] { svr.listen(HOST, PORT); });
  12160. auto se = detail::scope_exit([&] {
  12161. svr.stop();
  12162. t.join();
  12163. ASSERT_FALSE(svr.is_running());
  12164. ASSERT_TRUE(handled);
  12165. });
  12166. svr.wait_until_ready();
  12167. auto req = "POST /test HTTP/1.1\r\n"
  12168. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12169. "Content-Length: 399\r\n"
  12170. "\r\n"
  12171. "----------\r\n"
  12172. "Content-Disposition: form-data; name=\"text\"\r\n"
  12173. "\r\n"
  12174. "text default\r\n"
  12175. "----------\r\n"
  12176. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12177. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12178. "Content-Type: text/plain\r\n"
  12179. "\r\n"
  12180. "Content of a.txt.\r\n"
  12181. "\r\n"
  12182. "----------\r\n"
  12183. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12184. "\"a.html\"\r\n"
  12185. "Content-Type: text/html\r\n"
  12186. "\r\n"
  12187. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12188. "\r\n"
  12189. "------------\r\n";
  12190. ASSERT_TRUE(send_request(1, req));
  12191. }
  12192. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12193. auto handled = false;
  12194. Server svr;
  12195. svr.Post("/test", [&](const Request &req, Response &res) {
  12196. // Case-insensitive "utf-8''" prefix with a long value
  12197. const auto &file = req.form.get_file("file1");
  12198. ASSERT_EQ("file1", file.name);
  12199. // 8000 chars exercises both the Content-Disposition parser and the
  12200. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12201. // Prior to the fix, std::regex_match on this header would cause O(N)
  12202. // stack recursion in libstdc++, leading to SIGSEGV.
  12203. std::string expected_filename(8000, 'A');
  12204. ASSERT_EQ(expected_filename, file.filename);
  12205. res.set_content("ok", "text/plain");
  12206. handled = true;
  12207. });
  12208. thread t = thread([&] { svr.listen(HOST, PORT); });
  12209. auto se = detail::scope_exit([&] {
  12210. svr.stop();
  12211. t.join();
  12212. ASSERT_FALSE(svr.is_running());
  12213. ASSERT_TRUE(handled);
  12214. });
  12215. svr.wait_until_ready();
  12216. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12217. // Regression test for GHSA-qq6v-r583-3h69
  12218. std::string long_filename(8000, 'A');
  12219. std::string body = "----------\r\n"
  12220. "Content-Disposition: form-data; name=\"file1\"; "
  12221. "filename*=\"Utf-8''" +
  12222. long_filename +
  12223. "\"\r\n"
  12224. "\r\n"
  12225. "hello\r\n"
  12226. "------------\r\n";
  12227. auto req = "POST /test HTTP/1.1\r\n"
  12228. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12229. "Content-Length: " +
  12230. std::to_string(body.size()) + "\r\n\r\n" + body;
  12231. ASSERT_TRUE(send_request(1, req));
  12232. }
  12233. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12234. auto handled = false;
  12235. Server svr;
  12236. svr.Post("/test", [&](const Request &req, Response &) {
  12237. ASSERT_EQ(2u, req.form.fields.size());
  12238. const auto &text1 = req.form.get_field("text1");
  12239. ASSERT_EQ("text1", text1);
  12240. const auto &text2 = req.form.get_field("text2");
  12241. ASSERT_EQ("text2", text2);
  12242. handled = true;
  12243. });
  12244. thread t = thread([&] { svr.listen(HOST, PORT); });
  12245. auto se = detail::scope_exit([&] {
  12246. svr.stop();
  12247. t.join();
  12248. ASSERT_FALSE(svr.is_running());
  12249. ASSERT_TRUE(handled);
  12250. });
  12251. svr.wait_until_ready();
  12252. auto req = "POST /test HTTP/1.1\r\n"
  12253. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12254. "Content-Length: 146\r\n"
  12255. "\r\n----------\r\n"
  12256. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12257. "\r\n"
  12258. "text1"
  12259. "\r\n----------\r\n"
  12260. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12261. "\r\n"
  12262. "text2"
  12263. "\r\n------------";
  12264. std::string response;
  12265. ASSERT_TRUE(send_request(1, req, &response));
  12266. ASSERT_EQ("200", response.substr(9, 3));
  12267. }
  12268. TEST(MultipartFormDataTest, ContentLength) {
  12269. auto handled = false;
  12270. Server svr;
  12271. svr.Post("/test", [&](const Request &req, Response &) {
  12272. ASSERT_EQ(2u, req.form.fields.size());
  12273. const auto &text1 = req.form.get_field("text1");
  12274. ASSERT_EQ("text1", text1);
  12275. const auto &text2 = req.form.get_field("text2");
  12276. ASSERT_EQ("text2", text2);
  12277. handled = true;
  12278. });
  12279. thread t = thread([&] { svr.listen(HOST, PORT); });
  12280. auto se = detail::scope_exit([&] {
  12281. svr.stop();
  12282. t.join();
  12283. ASSERT_FALSE(svr.is_running());
  12284. ASSERT_TRUE(handled);
  12285. });
  12286. svr.wait_until_ready();
  12287. auto req = "POST /test HTTP/1.1\r\n"
  12288. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12289. "Content-Length: 167\r\n"
  12290. "\r\n----------\r\n"
  12291. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12292. "Content-Length: 5\r\n"
  12293. "\r\n"
  12294. "text1"
  12295. "\r\n----------\r\n"
  12296. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12297. "\r\n"
  12298. "text2"
  12299. "\r\n------------\r\n";
  12300. std::string response;
  12301. ASSERT_TRUE(send_request(1, req, &response));
  12302. ASSERT_EQ("200", response.substr(9, 3));
  12303. }
  12304. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12305. auto handled = false;
  12306. Server svr;
  12307. svr.Post("/test", [&](const Request &req, Response &) {
  12308. ASSERT_EQ(2u, req.form.fields.size());
  12309. const auto &text1 = req.form.get_field("text1");
  12310. ASSERT_EQ("text1", text1);
  12311. // TODO: Add header access for text fields if needed
  12312. const auto &text2 = req.form.get_field("text2");
  12313. ASSERT_EQ("text2", text2);
  12314. // TODO: Header access for text fields needs to be implemented
  12315. // auto &headers = it->second.headers;
  12316. // ASSERT_EQ(3U, headers.size());
  12317. // auto custom_header = headers.find("x-whatever");
  12318. // ASSERT_TRUE(custom_header != headers.end());
  12319. // ASSERT_NE("customvalue", custom_header->second);
  12320. // ASSERT_EQ("CustomValue", custom_header->second);
  12321. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12322. handled = true;
  12323. });
  12324. thread t = thread([&] { svr.listen(HOST, PORT); });
  12325. auto se = detail::scope_exit([&] {
  12326. svr.stop();
  12327. t.join();
  12328. ASSERT_FALSE(svr.is_running());
  12329. ASSERT_TRUE(handled);
  12330. });
  12331. svr.wait_until_ready();
  12332. auto req = "POST /test HTTP/1.1\r\n"
  12333. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12334. "Content-Length: 232\r\n"
  12335. "\r\n----------\r\n"
  12336. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12337. "Content-Length: 5\r\n"
  12338. "X-Test: 1\r\n"
  12339. "\r\n"
  12340. "text1"
  12341. "\r\n----------\r\n"
  12342. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12343. "Content-Type: text/plain\r\n"
  12344. "X-Whatever: CustomValue\r\n"
  12345. "\r\n"
  12346. "text2"
  12347. "\r\n------------\r\n"
  12348. "That should be disregarded. Not even read";
  12349. std::string response;
  12350. ASSERT_TRUE(send_request(1, req, &response));
  12351. ASSERT_EQ("200", response.substr(9, 3));
  12352. }
  12353. TEST(MultipartFormDataTest, LargeHeader) {
  12354. auto handled = false;
  12355. Server svr;
  12356. svr.Post("/test", [&](const Request &req, Response &) {
  12357. ASSERT_EQ(1u, req.form.fields.size());
  12358. const auto &text = req.form.get_field("name1");
  12359. ASSERT_EQ("text1", text);
  12360. handled = true;
  12361. });
  12362. thread t = thread([&] { svr.listen(HOST, PORT); });
  12363. auto se = detail::scope_exit([&] {
  12364. svr.stop();
  12365. t.join();
  12366. ASSERT_FALSE(svr.is_running());
  12367. ASSERT_TRUE(handled);
  12368. });
  12369. svr.wait_until_ready();
  12370. auto boundary = std::string("cpp-httplib-multipart-data");
  12371. std::string content = "--" + boundary +
  12372. "\r\n"
  12373. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12374. "\r\n"
  12375. "text1\r\n"
  12376. "--" +
  12377. boundary + "--\r\n";
  12378. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12379. "Content-Type: multipart/form-data;boundary=" +
  12380. boundary +
  12381. "\r\n"
  12382. "Content-Length: " +
  12383. std::to_string(content.size()) +
  12384. "\r\n"
  12385. "Dummy-Header: ";
  12386. std::string header_suffix = "\r\n"
  12387. "\r\n";
  12388. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12389. size_t header_dummy_size =
  12390. read_buff_size -
  12391. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12392. auto header_dummy = std::string(header_dummy_size, '@');
  12393. auto req = header_prefix + header_dummy + header_suffix + content;
  12394. std::string response;
  12395. ASSERT_TRUE(send_request(1, req, &response));
  12396. ASSERT_EQ("200", response.substr(9, 3));
  12397. }
  12398. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12399. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12400. // (not chunked Transfer-Encoding) after the streaming refactor.
  12401. auto handled = false;
  12402. Server svr;
  12403. svr.Post("/upload", [&](const Request &req, Response &res) {
  12404. auto cl_it = req.headers.find("Content-Length");
  12405. EXPECT_TRUE(cl_it != req.headers.end());
  12406. auto te_it = req.headers.find("Transfer-Encoding");
  12407. EXPECT_TRUE(te_it == req.headers.end());
  12408. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12409. res.set_content("ok", "text/plain");
  12410. handled = true;
  12411. });
  12412. auto port = svr.bind_to_any_port(HOST);
  12413. auto t = thread([&] { svr.listen_after_bind(); });
  12414. auto se = detail::scope_exit([&] {
  12415. svr.stop();
  12416. t.join();
  12417. ASSERT_FALSE(svr.is_running());
  12418. ASSERT_TRUE(handled);
  12419. });
  12420. svr.wait_until_ready();
  12421. UploadFormDataItems items = {
  12422. {"field1", "hello", "", "text/plain"},
  12423. {"file1", "world", "test.txt", "application/octet-stream"},
  12424. };
  12425. Client cli(HOST, port);
  12426. auto res = cli.Post("/upload", {}, items);
  12427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12428. EXPECT_EQ(StatusCode::OK_200, res->status);
  12429. }
  12430. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12431. // Verify that make_multipart_content_provider coalesces many small segments
  12432. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12433. constexpr size_t kItemCount = 1000;
  12434. UploadFormDataItems items;
  12435. items.reserve(kItemCount);
  12436. for (size_t i = 0; i < kItemCount; i++) {
  12437. items.push_back(
  12438. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12439. }
  12440. const std::string boundary = "----test-boundary";
  12441. auto content_length = detail::get_multipart_content_length(items, boundary);
  12442. auto provider = detail::make_multipart_content_provider(items, boundary);
  12443. // Drive the provider the same way write_content_with_progress does
  12444. size_t write_count = 0;
  12445. size_t total_bytes = 0;
  12446. DataSink sink;
  12447. size_t offset = 0;
  12448. sink.write = [&](const char *d, size_t l) -> bool {
  12449. (void)d;
  12450. write_count++;
  12451. total_bytes += l;
  12452. offset += l;
  12453. return true;
  12454. };
  12455. sink.is_writable = []() -> bool { return true; };
  12456. while (offset < content_length) {
  12457. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12458. }
  12459. EXPECT_EQ(content_length, total_bytes);
  12460. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12461. // With buffering into 64KB blocks, write_count should be much smaller.
  12462. auto segment_count = 3 * kItemCount + 1;
  12463. EXPECT_LT(write_count, segment_count / 10);
  12464. }
  12465. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12466. // Integration test: send many UploadFormDataItems and verify the server
  12467. // receives all of them correctly (#2410).
  12468. constexpr size_t kItemCount = 500;
  12469. auto handled = false;
  12470. Server svr;
  12471. svr.Post("/upload", [&](const Request &req, Response &res) {
  12472. EXPECT_EQ(kItemCount, req.form.fields.size());
  12473. for (size_t i = 0; i < kItemCount; i++) {
  12474. auto key = "field" + std::to_string(i);
  12475. auto val = "value" + std::to_string(i);
  12476. auto it = req.form.fields.find(key);
  12477. if (it != req.form.fields.end()) {
  12478. EXPECT_EQ(val, it->second.content);
  12479. } else {
  12480. ADD_FAILURE() << "Missing field: " << key;
  12481. }
  12482. }
  12483. res.set_content("ok", "text/plain");
  12484. handled = true;
  12485. });
  12486. auto port = svr.bind_to_any_port(HOST);
  12487. auto t = thread([&] { svr.listen_after_bind(); });
  12488. auto se = detail::scope_exit([&] {
  12489. svr.stop();
  12490. t.join();
  12491. ASSERT_FALSE(svr.is_running());
  12492. ASSERT_TRUE(handled);
  12493. });
  12494. svr.wait_until_ready();
  12495. UploadFormDataItems items;
  12496. items.reserve(kItemCount);
  12497. for (size_t i = 0; i < kItemCount; i++) {
  12498. items.push_back(
  12499. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12500. }
  12501. Client cli(HOST, port);
  12502. auto res = cli.Post("/upload", items);
  12503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12504. EXPECT_EQ(StatusCode::OK_200, res->status);
  12505. }
  12506. TEST(MultipartFormDataTest, MakeFileProvider) {
  12507. // Verify make_file_provider sends a file's contents correctly.
  12508. const std::string file_content(4096, 'Z');
  12509. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12510. {
  12511. std::ofstream ofs(tmp_path, std::ios::binary);
  12512. ofs.write(file_content.data(),
  12513. static_cast<std::streamsize>(file_content.size()));
  12514. }
  12515. auto handled = false;
  12516. Server svr;
  12517. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12518. const ContentReader &content_reader) {
  12519. ASSERT_TRUE(req.is_multipart_form_data());
  12520. std::vector<FormData> items;
  12521. content_reader(
  12522. [&](const FormData &file) {
  12523. items.push_back(file);
  12524. return true;
  12525. },
  12526. [&](const char *data, size_t data_length) {
  12527. items.back().content.append(data, data_length);
  12528. return true;
  12529. });
  12530. ASSERT_EQ(1u, items.size());
  12531. EXPECT_EQ("myfile", items[0].name);
  12532. EXPECT_EQ("data.bin", items[0].filename);
  12533. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12534. EXPECT_EQ(file_content, items[0].content);
  12535. handled = true;
  12536. });
  12537. auto port = svr.bind_to_any_port(HOST);
  12538. auto t = thread([&] { svr.listen_after_bind(); });
  12539. auto se = detail::scope_exit([&] {
  12540. svr.stop();
  12541. t.join();
  12542. ASSERT_FALSE(svr.is_running());
  12543. ASSERT_TRUE(handled);
  12544. std::remove(tmp_path.c_str());
  12545. });
  12546. svr.wait_until_ready();
  12547. FormDataProviderItems providers;
  12548. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12549. "application/octet-stream"));
  12550. Client cli(HOST, port);
  12551. auto res = cli.Post("/upload", {}, {}, providers);
  12552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12553. EXPECT_EQ(StatusCode::OK_200, res->status);
  12554. }
  12555. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12556. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12557. // (100) headers is rejected with a 400 Bad Request response.
  12558. Server svr;
  12559. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12560. res.set_content("ok", "text/plain");
  12561. });
  12562. thread t = thread([&] { svr.listen(HOST, PORT); });
  12563. auto se = detail::scope_exit([&] {
  12564. svr.stop();
  12565. t.join();
  12566. ASSERT_FALSE(svr.is_running());
  12567. });
  12568. svr.wait_until_ready();
  12569. // Build a multipart part with 101 custom headers (exceeding
  12570. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12571. std::stringstream body;
  12572. body << "--simpleboundary\r\n"
  12573. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12574. for (int i = 0; i < 101; i++) {
  12575. body << "X-Custom-Header-" << i << ": value\r\n";
  12576. }
  12577. body << "\r\n"
  12578. << "value1\r\n"
  12579. << "--simpleboundary--\r\n";
  12580. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12581. Client cli(HOST, PORT);
  12582. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12584. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12585. }
  12586. TEST(MakeFileBodyTest, Basic) {
  12587. const std::string file_content(4096, 'Z');
  12588. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12589. {
  12590. std::ofstream ofs(tmp_path, std::ios::binary);
  12591. ofs.write(file_content.data(),
  12592. static_cast<std::streamsize>(file_content.size()));
  12593. }
  12594. auto handled = false;
  12595. Server svr;
  12596. svr.Post("/upload", [&](const Request &req, Response &res) {
  12597. EXPECT_EQ(file_content, req.body);
  12598. handled = true;
  12599. res.status = StatusCode::OK_200;
  12600. });
  12601. auto port = svr.bind_to_any_port(HOST);
  12602. auto t = thread([&] { svr.listen_after_bind(); });
  12603. auto se = detail::scope_exit([&] {
  12604. svr.stop();
  12605. t.join();
  12606. ASSERT_FALSE(svr.is_running());
  12607. ASSERT_TRUE(handled);
  12608. std::remove(tmp_path.c_str());
  12609. });
  12610. svr.wait_until_ready();
  12611. auto fb = make_file_body(tmp_path);
  12612. ASSERT_GT(fb.first, 0u);
  12613. Client cli(HOST, port);
  12614. auto res =
  12615. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12617. EXPECT_EQ(StatusCode::OK_200, res->status);
  12618. }
  12619. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12620. static constexpr unsigned int number_of_tasks{1000000};
  12621. std::atomic_uint count{0};
  12622. std::unique_ptr<TaskQueue> task_queue{
  12623. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12624. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12625. auto queued = task_queue->enqueue(
  12626. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12627. EXPECT_TRUE(queued);
  12628. }
  12629. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12630. task_queue->shutdown();
  12631. #else
  12632. EXPECT_NO_THROW(task_queue->shutdown());
  12633. #endif
  12634. EXPECT_EQ(number_of_tasks, count.load());
  12635. }
  12636. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12637. static constexpr unsigned int number_of_tasks{1000000};
  12638. static constexpr unsigned int qlimit{2};
  12639. unsigned int queued_count{0};
  12640. std::atomic_uint count{0};
  12641. std::unique_ptr<TaskQueue> task_queue{
  12642. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12643. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12644. if (task_queue->enqueue(
  12645. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12646. queued_count++;
  12647. }
  12648. }
  12649. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12650. task_queue->shutdown();
  12651. #else
  12652. EXPECT_NO_THROW(task_queue->shutdown());
  12653. #endif
  12654. EXPECT_EQ(queued_count, count.load());
  12655. EXPECT_TRUE(queued_count <= number_of_tasks);
  12656. EXPECT_TRUE(queued_count >= qlimit);
  12657. }
  12658. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12659. // Use a short idle timeout so a dynamic thread spawns, times out and
  12660. // exits during the test, and the pool keeps working afterwards.
  12661. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12662. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12663. /*idle_timeout_sec=*/1}};
  12664. std::atomic_uint count{0};
  12665. std::condition_variable cv;
  12666. std::mutex mtx;
  12667. bool release = false;
  12668. // Block the base thread so the second task spawns a dynamic thread.
  12669. EXPECT_TRUE(task_queue->enqueue([&] {
  12670. std::unique_lock<std::mutex> lock(mtx);
  12671. while (!release) {
  12672. cv.wait(lock);
  12673. }
  12674. count++;
  12675. }));
  12676. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12677. // Let the dynamic thread finish its task and exceed the idle timeout.
  12678. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12679. {
  12680. std::unique_lock<std::mutex> lock(mtx);
  12681. release = true;
  12682. }
  12683. cv.notify_all();
  12684. // The pool must still accept and run tasks after the dynamic thread exited.
  12685. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12686. task_queue->shutdown();
  12687. EXPECT_EQ(3u, count.load());
  12688. }
  12689. TEST(TaskQueueTest, MaxQueuedRequests) {
  12690. static constexpr unsigned int qlimit{3};
  12691. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12692. std::condition_variable sem_cv;
  12693. std::mutex sem_mtx;
  12694. int credits = 0;
  12695. bool queued;
  12696. /* Fill up the queue with tasks that will block until we give them credits to
  12697. * complete. */
  12698. for (unsigned int n = 0; n <= qlimit;) {
  12699. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12700. std::unique_lock<std::mutex> lock(sem_mtx);
  12701. while (credits <= 0) {
  12702. sem_cv.wait(lock);
  12703. }
  12704. /* Consume the credit and signal the test code if they are all gone. */
  12705. if (--credits == 0) { sem_cv.notify_one(); }
  12706. });
  12707. if (n < qlimit) {
  12708. /* The first qlimit enqueues must succeed. */
  12709. EXPECT_TRUE(queued);
  12710. } else {
  12711. /* The last one will succeed only when the worker thread
  12712. * starts and dequeues the first blocking task. Although
  12713. * not necessary for the correctness of this test, we sleep for
  12714. * a short while to avoid busy waiting. */
  12715. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12716. }
  12717. if (queued) { n++; }
  12718. }
  12719. /* Further enqueues must fail since the queue is full. */
  12720. for (auto i = 0; i < 4; i++) {
  12721. queued = task_queue->enqueue([] {});
  12722. EXPECT_FALSE(queued);
  12723. }
  12724. /* Give the credits to allow the previous tasks to complete. */
  12725. {
  12726. std::unique_lock<std::mutex> lock(sem_mtx);
  12727. credits += qlimit + 1;
  12728. }
  12729. sem_cv.notify_all();
  12730. /* Wait for all the credits to be consumed. */
  12731. {
  12732. std::unique_lock<std::mutex> lock(sem_mtx);
  12733. while (credits > 0) {
  12734. sem_cv.wait(lock);
  12735. }
  12736. }
  12737. /* Check that we are able again to enqueue at least qlimit tasks. */
  12738. for (unsigned int i = 0; i < qlimit; i++) {
  12739. queued = task_queue->enqueue([] {});
  12740. EXPECT_TRUE(queued);
  12741. }
  12742. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12743. task_queue->shutdown();
  12744. #else
  12745. EXPECT_NO_THROW(task_queue->shutdown());
  12746. #endif
  12747. }
  12748. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12749. Server svr;
  12750. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12751. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12752. });
  12753. svr.Get("/hello", [](const Request &req, Response &res) {
  12754. res.set_content(req.get_param_value("key"), "text/plain");
  12755. });
  12756. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12757. auto se = detail::scope_exit([&] {
  12758. svr.stop();
  12759. thread.join();
  12760. ASSERT_FALSE(svr.is_running());
  12761. });
  12762. svr.wait_until_ready();
  12763. {
  12764. Client cli(HOST, PORT);
  12765. cli.set_follow_location(true);
  12766. auto res = cli.Get("/");
  12767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12768. EXPECT_EQ(StatusCode::OK_200, res->status);
  12769. EXPECT_EQ("val&key2=val2", res->body);
  12770. }
  12771. }
  12772. #endif
  12773. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12774. Server svr;
  12775. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12776. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12777. });
  12778. svr.Get("/hello", [](const Request &req, Response &res) {
  12779. res.set_content(req.get_param_value("key"), "text/plain");
  12780. });
  12781. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12782. auto se = detail::scope_exit([&] {
  12783. svr.stop();
  12784. thread.join();
  12785. ASSERT_FALSE(svr.is_running());
  12786. });
  12787. svr.wait_until_ready();
  12788. {
  12789. Client cli(HOST, PORT);
  12790. cli.set_follow_location(true);
  12791. auto res = cli.Get("/");
  12792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12793. EXPECT_EQ(StatusCode::OK_200, res->status);
  12794. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12795. }
  12796. }
  12797. TEST(RedirectTest, RedirectWithPlusInPath) {
  12798. Server svr;
  12799. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12800. res.set_redirect("/a+b");
  12801. });
  12802. // Route pattern uses regex; escape + as \\+
  12803. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12804. res.set_content(req.path, "text/plain");
  12805. });
  12806. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12807. auto se = detail::scope_exit([&] {
  12808. svr.stop();
  12809. thread.join();
  12810. ASSERT_FALSE(svr.is_running());
  12811. });
  12812. svr.wait_until_ready();
  12813. {
  12814. Client cli(HOST, PORT);
  12815. cli.set_follow_location(true);
  12816. auto res = cli.Get("/");
  12817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12818. EXPECT_EQ(StatusCode::OK_200, res->status);
  12819. EXPECT_EQ("/a+b", res->body);
  12820. }
  12821. }
  12822. #ifdef CPPHTTPLIB_SSL_ENABLED
  12823. TEST(RedirectTest, Issue2185_Online) {
  12824. SSLClient client("github.com");
  12825. client.set_follow_location(true);
  12826. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12827. "Coollab-Windows.zip");
  12828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12829. EXPECT_EQ(StatusCode::OK_200, res->status);
  12830. EXPECT_EQ(9920427U, res->body.size());
  12831. }
  12832. #endif
  12833. TEST(VulnerabilityTest, CRLFInjection) {
  12834. Server svr;
  12835. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12836. res.set_content("Hello 1", "text/plain");
  12837. });
  12838. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12839. res.set_content("Hello 2", "text/plain");
  12840. });
  12841. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12842. res.set_content("Hello 3", "text/plain");
  12843. });
  12844. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12845. res.set_content("Hello 4", "text/plain");
  12846. });
  12847. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12848. for (const auto &x : req.headers) {
  12849. auto key = x.first;
  12850. EXPECT_STRNE("evil", key.c_str());
  12851. }
  12852. });
  12853. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12854. auto se = detail::scope_exit([&] {
  12855. svr.stop();
  12856. thread.join();
  12857. ASSERT_FALSE(svr.is_running());
  12858. });
  12859. svr.wait_until_ready();
  12860. {
  12861. Client cli(HOST, PORT);
  12862. cli.Post("/test1", "A=B",
  12863. "application/x-www-form-urlencoded\r\nevil: hello1");
  12864. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12865. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12866. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12867. }
  12868. }
  12869. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12870. auto server_thread = std::thread([] {
  12871. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12872. default_socket_options(srv);
  12873. sockaddr_in addr{};
  12874. addr.sin_family = AF_INET;
  12875. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12876. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12877. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12878. ::listen(srv, 1);
  12879. sockaddr_in cli_addr{};
  12880. socklen_t cli_len = sizeof(cli_addr);
  12881. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12882. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12883. std::string buf_all;
  12884. char buf[2048];
  12885. ssize_t n;
  12886. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12887. buf_all.append(buf, static_cast<size_t>(n));
  12888. size_t pos;
  12889. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12890. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12891. auto e = request_block.find("\r\n");
  12892. if (e != std::string::npos) {
  12893. auto request_line = request_block.substr(0, e);
  12894. std::string msg =
  12895. "CRLF injection detected in request line: '" + request_line + "'";
  12896. EXPECT_FALSE(true) << msg;
  12897. }
  12898. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12899. ::send(cli,
  12900. #ifdef _WIN32
  12901. static_cast<const char *>(resp.c_str()),
  12902. static_cast<int>(resp.size()),
  12903. #else
  12904. resp.c_str(), resp.size(),
  12905. #endif
  12906. 0);
  12907. buf_all.erase(0, pos + 4);
  12908. }
  12909. }
  12910. detail::close_socket(cli);
  12911. detail::close_socket(srv);
  12912. });
  12913. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12914. auto cli = Client("127.0.0.1", PORT + 1);
  12915. auto headers = Headers{
  12916. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12917. {"Connection", "keep-alive"}};
  12918. auto res = cli.Get("/hi", headers);
  12919. EXPECT_FALSE(res);
  12920. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12921. server_thread.join();
  12922. }
  12923. TEST(PathParamsTest, StaticMatch) {
  12924. const auto pattern = "/users/all";
  12925. detail::PathParamsMatcher matcher(pattern);
  12926. Request request;
  12927. request.path = "/users/all";
  12928. ASSERT_TRUE(matcher.match(request));
  12929. std::unordered_map<std::string, std::string> expected_params = {};
  12930. EXPECT_EQ(request.path_params, expected_params);
  12931. }
  12932. TEST(PathParamsTest, StaticMismatch) {
  12933. const auto pattern = "/users/all";
  12934. detail::PathParamsMatcher matcher(pattern);
  12935. Request request;
  12936. request.path = "/users/1";
  12937. ASSERT_FALSE(matcher.match(request));
  12938. }
  12939. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12940. const auto pattern = "/users/:id/subscriptions";
  12941. detail::PathParamsMatcher matcher(pattern);
  12942. Request request;
  12943. request.path = "/users/42/subscriptions";
  12944. ASSERT_TRUE(matcher.match(request));
  12945. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12946. EXPECT_EQ(request.path_params, expected_params);
  12947. }
  12948. TEST(PathParamsTest, SingleParamInTheEnd) {
  12949. const auto pattern = "/users/:id";
  12950. detail::PathParamsMatcher matcher(pattern);
  12951. Request request;
  12952. request.path = "/users/24";
  12953. ASSERT_TRUE(matcher.match(request));
  12954. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12955. EXPECT_EQ(request.path_params, expected_params);
  12956. }
  12957. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12958. const auto pattern = "/users/:id/";
  12959. detail::PathParamsMatcher matcher(pattern);
  12960. Request request;
  12961. request.path = "/users/42/";
  12962. ASSERT_TRUE(matcher.match(request));
  12963. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12964. EXPECT_EQ(request.path_params, expected_params);
  12965. }
  12966. TEST(PathParamsTest, EmptyParam) {
  12967. const auto pattern = "/users/:id/";
  12968. detail::PathParamsMatcher matcher(pattern);
  12969. Request request;
  12970. request.path = "/users//";
  12971. ASSERT_TRUE(matcher.match(request));
  12972. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12973. EXPECT_EQ(request.path_params, expected_params);
  12974. }
  12975. TEST(PathParamsTest, FragmentMismatch) {
  12976. const auto pattern = "/users/:id/";
  12977. detail::PathParamsMatcher matcher(pattern);
  12978. Request request;
  12979. request.path = "/admins/24/";
  12980. ASSERT_FALSE(matcher.match(request));
  12981. }
  12982. TEST(PathParamsTest, ExtraFragments) {
  12983. const auto pattern = "/users/:id";
  12984. detail::PathParamsMatcher matcher(pattern);
  12985. Request request;
  12986. request.path = "/users/42/subscriptions";
  12987. ASSERT_FALSE(matcher.match(request));
  12988. }
  12989. TEST(PathParamsTest, MissingTrailingParam) {
  12990. const auto pattern = "/users/:id";
  12991. detail::PathParamsMatcher matcher(pattern);
  12992. Request request;
  12993. request.path = "/users";
  12994. ASSERT_FALSE(matcher.match(request));
  12995. }
  12996. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12997. const auto pattern = "/users/:id/subscriptions";
  12998. detail::PathParamsMatcher matcher(pattern);
  12999. Request request;
  13000. request.path = "/users/subscriptions";
  13001. ASSERT_FALSE(matcher.match(request));
  13002. }
  13003. TEST(PathParamsTest, MultipleParams) {
  13004. const auto pattern = "/users/:userid/subscriptions/:subid";
  13005. detail::PathParamsMatcher matcher(pattern);
  13006. Request request;
  13007. request.path = "/users/42/subscriptions/2";
  13008. ASSERT_TRUE(matcher.match(request));
  13009. std::unordered_map<std::string, std::string> expected_params = {
  13010. {"userid", "42"}, {"subid", "2"}};
  13011. EXPECT_EQ(request.path_params, expected_params);
  13012. }
  13013. TEST(PathParamsTest, SequenceOfParams) {
  13014. const auto pattern = "/values/:x/:y/:z";
  13015. detail::PathParamsMatcher matcher(pattern);
  13016. Request request;
  13017. request.path = "/values/1/2/3";
  13018. ASSERT_TRUE(matcher.match(request));
  13019. std::unordered_map<std::string, std::string> expected_params = {
  13020. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  13021. EXPECT_EQ(request.path_params, expected_params);
  13022. }
  13023. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  13024. const auto pattern = "/prefix:suffix";
  13025. detail::PathParamsMatcher matcher(pattern);
  13026. Request request;
  13027. request.path = "/prefix:suffix";
  13028. ASSERT_TRUE(matcher.match(request));
  13029. const std::unordered_map<std::string, std::string> expected_params = {};
  13030. EXPECT_EQ(request.path_params, expected_params);
  13031. }
  13032. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  13033. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  13034. // calling thread's stack on a long enough path for a quantified pattern;
  13035. // RegexMatcher must refuse to run regex matching on paths beyond
  13036. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  13037. detail::RegexMatcher matcher("/files/(.*)");
  13038. Request within_limit;
  13039. within_limit.path = "/files/" + std::string(10, 'A');
  13040. EXPECT_TRUE(matcher.match(within_limit));
  13041. Request over_limit;
  13042. over_limit.path =
  13043. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  13044. EXPECT_FALSE(matcher.match(over_limit));
  13045. }
  13046. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  13047. Server svr;
  13048. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  13049. res.set_content("ok", "text/plain");
  13050. });
  13051. auto port = svr.bind_to_any_port(HOST);
  13052. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13053. auto se = detail::scope_exit([&] {
  13054. svr.stop();
  13055. thread.join();
  13056. ASSERT_FALSE(svr.is_running());
  13057. });
  13058. svr.wait_until_ready();
  13059. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  13060. // request URI limit; this used to be able to crash the process.
  13061. std::string path =
  13062. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  13063. std::string req = "GET " + path +
  13064. " HTTP/1.1\r\n"
  13065. "Host: " +
  13066. std::string(HOST) + ":" + std::to_string(port) +
  13067. "\r\n"
  13068. "Connection: close\r\n"
  13069. "\r\n";
  13070. std::string response;
  13071. ASSERT_TRUE(send_request(5, req, &response, port));
  13072. EXPECT_NE(std::string::npos, response.find("404"));
  13073. }
  13074. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  13075. Server svr;
  13076. auto handler = [](const Request & /*req*/, Response &res) {
  13077. res.set_content("hit", "text/plain");
  13078. };
  13079. // No regex metacharacter, so this one is compared literally
  13080. svr.Get("/literal/route", handler);
  13081. // '.' is a regex metacharacter, so this one must keep regex semantics
  13082. svr.Get("/a.c", handler);
  13083. auto port = svr.bind_to_any_port(HOST);
  13084. std::thread t([&]() { svr.listen_after_bind(); });
  13085. auto se = detail::scope_exit([&] {
  13086. svr.stop();
  13087. t.join();
  13088. ASSERT_FALSE(svr.is_running());
  13089. });
  13090. svr.wait_until_ready();
  13091. Client cli(HOST, port);
  13092. struct {
  13093. const char *path;
  13094. int status;
  13095. } cases[] = {
  13096. {"/literal/route", StatusCode::OK_200},
  13097. {"/literal/routes", StatusCode::NotFound_404},
  13098. {"/literal/rout", StatusCode::NotFound_404},
  13099. {"/abc", StatusCode::OK_200},
  13100. {"/a.c", StatusCode::OK_200},
  13101. };
  13102. for (const auto &x : cases) {
  13103. auto res = cli.Get(x.path);
  13104. ASSERT_TRUE(res) << x.path;
  13105. EXPECT_EQ(x.status, res->status) << x.path;
  13106. }
  13107. }
  13108. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  13109. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  13110. // from exhausting the stack, so it must only constrain routes that actually
  13111. // run a regular expression. A literal route is matched by comparison and
  13112. // stays usable at any length.
  13113. Server svr;
  13114. const std::string pattern =
  13115. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  13116. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  13117. res.set_content("hit", "text/plain");
  13118. });
  13119. auto port = svr.bind_to_any_port(HOST);
  13120. std::thread t([&]() { svr.listen_after_bind(); });
  13121. auto se = detail::scope_exit([&] {
  13122. svr.stop();
  13123. t.join();
  13124. ASSERT_FALSE(svr.is_running());
  13125. });
  13126. svr.wait_until_ready();
  13127. Client cli(HOST, port);
  13128. auto res = cli.Get(pattern);
  13129. ASSERT_TRUE(res);
  13130. EXPECT_EQ(StatusCode::OK_200, res->status);
  13131. }
  13132. TEST(ParseUrlTest, VariousPatterns) {
  13133. {
  13134. detail::UrlComponents uc;
  13135. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  13136. EXPECT_EQ("http", uc.scheme);
  13137. EXPECT_EQ("example.com", uc.host);
  13138. EXPECT_EQ("8080", uc.port);
  13139. EXPECT_EQ("/path", uc.path);
  13140. EXPECT_EQ("?q=1", uc.query);
  13141. }
  13142. {
  13143. detail::UrlComponents uc;
  13144. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  13145. EXPECT_EQ("https", uc.scheme);
  13146. EXPECT_EQ("example.com", uc.host);
  13147. EXPECT_TRUE(uc.port.empty());
  13148. EXPECT_EQ("/path", uc.path);
  13149. }
  13150. {
  13151. detail::UrlComponents uc;
  13152. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  13153. EXPECT_EQ("::1", uc.host);
  13154. EXPECT_EQ("8080", uc.port);
  13155. EXPECT_EQ("/path", uc.path);
  13156. }
  13157. {
  13158. detail::UrlComponents uc;
  13159. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  13160. }
  13161. {
  13162. // Bytes after the IPv6 literal must be a delimiter, not folded into
  13163. // the path while the connection still targets the bracketed host.
  13164. detail::UrlComponents uc;
  13165. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  13166. }
  13167. {
  13168. detail::UrlComponents uc;
  13169. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  13170. }
  13171. {
  13172. detail::UrlComponents uc;
  13173. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  13174. EXPECT_EQ("::1", uc.host);
  13175. EXPECT_TRUE(uc.port.empty());
  13176. EXPECT_EQ("/path", uc.path);
  13177. }
  13178. {
  13179. detail::UrlComponents uc;
  13180. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  13181. EXPECT_TRUE(uc.scheme.empty());
  13182. EXPECT_EQ("example.com", uc.host);
  13183. EXPECT_EQ("/path", uc.path);
  13184. EXPECT_EQ("?q=1", uc.query);
  13185. }
  13186. {
  13187. detail::UrlComponents uc;
  13188. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  13189. EXPECT_TRUE(uc.host.empty());
  13190. EXPECT_EQ("/path", uc.path);
  13191. EXPECT_EQ("?q=1", uc.query);
  13192. }
  13193. {
  13194. detail::UrlComponents uc;
  13195. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  13196. EXPECT_EQ("example.com", uc.host);
  13197. EXPECT_EQ("8080", uc.port);
  13198. }
  13199. {
  13200. // Unix socket path — must not be parsed as host
  13201. detail::UrlComponents uc;
  13202. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  13203. EXPECT_TRUE(uc.host.empty());
  13204. }
  13205. {
  13206. detail::UrlComponents uc;
  13207. ASSERT_TRUE(detail::parse_url("", uc));
  13208. EXPECT_TRUE(uc.host.empty());
  13209. EXPECT_TRUE(uc.path.empty());
  13210. }
  13211. {
  13212. detail::UrlComponents uc;
  13213. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  13214. }
  13215. {
  13216. detail::UrlComponents uc;
  13217. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  13218. }
  13219. {
  13220. // Accepted by parse_url; callers restrict to http/https
  13221. detail::UrlComponents uc;
  13222. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  13223. EXPECT_EQ("ftp", uc.scheme);
  13224. }
  13225. {
  13226. detail::UrlComponents uc;
  13227. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  13228. }
  13229. {
  13230. detail::UrlComponents uc;
  13231. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  13232. }
  13233. }
  13234. TEST(ParseUrlTest, FragmentHandling) {
  13235. {
  13236. detail::UrlComponents uc;
  13237. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  13238. EXPECT_EQ("/path", uc.path);
  13239. EXPECT_TRUE(uc.query.empty());
  13240. }
  13241. {
  13242. detail::UrlComponents uc;
  13243. ASSERT_TRUE(detail::parse_url("#frag", uc));
  13244. EXPECT_TRUE(uc.path.empty());
  13245. EXPECT_TRUE(uc.query.empty());
  13246. }
  13247. }
  13248. TEST(ParseUrlTest, UserinfoHandling) {
  13249. // Userinfo with @ but no colon — host includes @
  13250. detail::UrlComponents uc;
  13251. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  13252. EXPECT_EQ("user@host.com", uc.host);
  13253. EXPECT_EQ("/path", uc.path);
  13254. }
  13255. TEST(ParseUrlTest, IPv6EdgeCases) {
  13256. {
  13257. detail::UrlComponents uc;
  13258. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  13259. EXPECT_TRUE(uc.scheme.empty());
  13260. EXPECT_EQ("::1", uc.host);
  13261. EXPECT_EQ("8080", uc.port);
  13262. }
  13263. {
  13264. // Zone ID '%25' is not in [a-fA-F0-9:]
  13265. detail::UrlComponents uc;
  13266. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  13267. }
  13268. }
  13269. TEST(ParseUrlTest, SchemeEdgeCases) {
  13270. {
  13271. detail::UrlComponents uc;
  13272. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  13273. }
  13274. {
  13275. detail::UrlComponents uc;
  13276. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  13277. }
  13278. {
  13279. detail::UrlComponents uc;
  13280. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  13281. }
  13282. }
  13283. TEST(ParseUrlTest, PortEdgeCases) {
  13284. {
  13285. detail::UrlComponents uc;
  13286. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  13287. EXPECT_TRUE(uc.port.empty());
  13288. EXPECT_EQ("/path", uc.path);
  13289. }
  13290. {
  13291. // parse_url accepts any port string; validation is done by parse_port
  13292. detail::UrlComponents uc;
  13293. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  13294. EXPECT_EQ("abc", uc.port);
  13295. }
  13296. }
  13297. TEST(ParseUrlTest, WebSocketPatterns) {
  13298. {
  13299. detail::UrlComponents uc;
  13300. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  13301. EXPECT_EQ("ws", uc.scheme);
  13302. EXPECT_EQ("echo.example.com", uc.host);
  13303. EXPECT_EQ("8080", uc.port);
  13304. EXPECT_EQ("/ws", uc.path);
  13305. }
  13306. {
  13307. detail::UrlComponents uc;
  13308. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  13309. EXPECT_EQ("wss", uc.scheme);
  13310. EXPECT_EQ("echo.example.com", uc.host);
  13311. EXPECT_TRUE(uc.port.empty());
  13312. EXPECT_EQ("/ws", uc.path);
  13313. }
  13314. }
  13315. TEST(ParseUrlTest, QueryOnly) {
  13316. detail::UrlComponents uc;
  13317. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  13318. EXPECT_TRUE(uc.host.empty());
  13319. EXPECT_TRUE(uc.path.empty());
  13320. EXPECT_EQ("?q=1&r=2", uc.query);
  13321. }
  13322. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13323. detail::UrlComponents uc;
  13324. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13325. EXPECT_TRUE(uc.scheme.empty());
  13326. EXPECT_EQ("example.com", uc.host);
  13327. EXPECT_EQ("443", uc.port);
  13328. EXPECT_EQ("/path", uc.path);
  13329. }
  13330. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13331. // If ipv6 regex working, regex match codepath is taken.
  13332. // else port will default to 80 in Client impl
  13333. int clientImplMagicPort = 80;
  13334. int port = 4321;
  13335. // above ports must be different to avoid false negative
  13336. EXPECT_NE(clientImplMagicPort, port);
  13337. std::string ipV6TestURL = "http://[ff06::c3]";
  13338. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13339. CLIENT_PRIVATE_KEY_FILE);
  13340. EXPECT_EQ(cli.port(), port);
  13341. }
  13342. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13343. auto file_path = "./www/dir/index.html";
  13344. auto dir_path = "./www/dir";
  13345. detail::FileStat stat_file(file_path);
  13346. EXPECT_TRUE(stat_file.is_file());
  13347. EXPECT_FALSE(stat_file.is_dir());
  13348. detail::FileStat stat_dir(dir_path);
  13349. EXPECT_FALSE(stat_dir.is_file());
  13350. EXPECT_TRUE(stat_dir.is_dir());
  13351. }
  13352. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13353. // IPv4 with default HTTP port (80)
  13354. EXPECT_EQ("example.com",
  13355. detail::make_host_and_port_string("example.com", 80, false));
  13356. // IPv4 with default HTTPS port (443)
  13357. EXPECT_EQ("example.com",
  13358. detail::make_host_and_port_string("example.com", 443, true));
  13359. // IPv4 with non-default HTTP port
  13360. EXPECT_EQ("example.com:8080",
  13361. detail::make_host_and_port_string("example.com", 8080, false));
  13362. // IPv4 with non-default HTTPS port
  13363. EXPECT_EQ("example.com:8443",
  13364. detail::make_host_and_port_string("example.com", 8443, true));
  13365. // IPv6 with default HTTP port (80)
  13366. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13367. // IPv6 with default HTTPS port (443)
  13368. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13369. // IPv6 with non-default HTTP port
  13370. EXPECT_EQ("[::1]:8080",
  13371. detail::make_host_and_port_string("::1", 8080, false));
  13372. // IPv6 with non-default HTTPS port
  13373. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13374. // IPv6 full address with default port
  13375. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13376. detail::make_host_and_port_string(
  13377. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13378. // IPv6 full address with non-default port
  13379. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13380. detail::make_host_and_port_string(
  13381. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13382. // IPv6 localhost with non-default port
  13383. EXPECT_EQ("[::1]:3000",
  13384. detail::make_host_and_port_string("::1", 3000, false));
  13385. // IPv6 with zone ID (link-local address) with default port
  13386. EXPECT_EQ("[fe80::1%eth0]",
  13387. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13388. // IPv6 with zone ID (link-local address) with non-default port
  13389. EXPECT_EQ("[fe80::1%eth0]:8080",
  13390. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13391. // Edge case: Port 443 with is_ssl=false (should add port)
  13392. EXPECT_EQ("example.com:443",
  13393. detail::make_host_and_port_string("example.com", 443, false));
  13394. // Edge case: Port 80 with is_ssl=true (should add port)
  13395. EXPECT_EQ("example.com:80",
  13396. detail::make_host_and_port_string("example.com", 80, true));
  13397. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13398. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13399. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13400. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13401. // Security fix: Already bracketed IPv6 should not get double brackets
  13402. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13403. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13404. EXPECT_EQ("[::1]:8080",
  13405. detail::make_host_and_port_string("[::1]", 8080, false));
  13406. EXPECT_EQ("[2001:db8::1]:8080",
  13407. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13408. EXPECT_EQ("[fe80::1%eth0]",
  13409. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13410. EXPECT_EQ("[fe80::1%eth0]:8080",
  13411. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13412. // Edge case: Empty host (should return as-is)
  13413. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13414. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13415. // This is a known limitation but shouldn't crash
  13416. EXPECT_EQ("[host:name]",
  13417. detail::make_host_and_port_string("host:name", 80, false));
  13418. // Port number edge cases (no validation, but should not crash)
  13419. EXPECT_EQ("example.com:0",
  13420. detail::make_host_and_port_string("example.com", 0, false));
  13421. EXPECT_EQ("example.com:-1",
  13422. detail::make_host_and_port_string("example.com", -1, false));
  13423. EXPECT_EQ("example.com:65535",
  13424. detail::make_host_and_port_string("example.com", 65535, false));
  13425. EXPECT_EQ("example.com:65536",
  13426. detail::make_host_and_port_string("example.com", 65536, false));
  13427. }
  13428. #ifdef CPPHTTPLIB_SSL_ENABLED
  13429. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13430. httplib::SSLClient cli("roblox.com", 443);
  13431. cli.set_follow_location(true);
  13432. auto res = cli.Get("/");
  13433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13434. EXPECT_EQ(StatusCode::OK_200, res->status);
  13435. }
  13436. #endif
  13437. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13438. Server svr;
  13439. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13440. EXPECT_EQ(res.status, 400);
  13441. });
  13442. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13443. auto se = detail::scope_exit([&] {
  13444. svr.stop();
  13445. thread.join();
  13446. ASSERT_FALSE(svr.is_running());
  13447. });
  13448. svr.wait_until_ready();
  13449. Client cli(HOST, PORT);
  13450. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13451. }
  13452. TEST(InvalidHeaderCharsTest, is_field_name) {
  13453. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13454. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13455. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13456. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13457. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13458. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13459. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13460. EXPECT_FALSE(detail::fields::is_field_name(""));
  13461. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13462. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13463. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13464. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13465. }
  13466. TEST(InvalidHeaderCharsTest, is_field_value) {
  13467. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13468. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13469. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13470. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13471. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13472. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13473. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13474. EXPECT_TRUE(detail::fields::is_field_value(""));
  13475. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13476. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13477. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13478. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13479. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13480. }
  13481. TEST(InvalidHeaderCharsTest, OnServer) {
  13482. Server svr;
  13483. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13484. std::string header = "Not Set";
  13485. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13486. res.set_header(header, "value");
  13487. res.set_content("Page Content Page Content", "text/plain");
  13488. });
  13489. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13490. std::string header = "Not Set";
  13491. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13492. res.set_header("X-Test", header);
  13493. res.set_content("Page Content Page Content", "text/plain");
  13494. });
  13495. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13496. auto se = detail::scope_exit([&] {
  13497. svr.stop();
  13498. thread.join();
  13499. ASSERT_FALSE(svr.is_running());
  13500. });
  13501. svr.wait_until_ready();
  13502. Client cli(HOST, PORT);
  13503. {
  13504. auto res = cli.Get(
  13505. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13507. EXPECT_EQ("Page Content Page Content", res->body);
  13508. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13509. }
  13510. {
  13511. auto res = cli.Get(
  13512. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13514. EXPECT_EQ("Page Content Page Content", res->body);
  13515. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13516. }
  13517. }
  13518. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13519. auto handled = false;
  13520. Server svr;
  13521. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13522. thread t = thread([&] { svr.listen(HOST, PORT); });
  13523. auto se = detail::scope_exit([&] {
  13524. svr.stop();
  13525. t.join();
  13526. ASSERT_FALSE(svr.is_running());
  13527. ASSERT_FALSE(handled);
  13528. });
  13529. svr.wait_until_ready();
  13530. auto req = "POST /test HTTP/1.1\r\n"
  13531. "Content-Length: x\r\n"
  13532. "\r\n";
  13533. std::string response;
  13534. ASSERT_TRUE(send_request(1, req, &response));
  13535. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13536. response.substr(0, response.find("\r\n")));
  13537. }
  13538. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  13539. // case-insensitive, and a server that receives a 100-continue expectation in
  13540. // an HTTP/1.0 request MUST ignore it.
  13541. static void probe_expect(int port, const std::string &req, bool *got_100) {
  13542. std::string response;
  13543. ASSERT_TRUE(send_request(1, req, &response, port));
  13544. *got_100 = response.find("100 Continue") != std::string::npos;
  13545. }
  13546. class ExpectTokenTest : public ::testing::Test {
  13547. protected:
  13548. void SetUp() override {
  13549. svr_.Post("/p", [](const Request &, Response &res) {
  13550. res.set_content("ok", "text/plain");
  13551. });
  13552. port_ = svr_.bind_to_any_port(HOST);
  13553. thread_ = thread([&]() { svr_.listen_after_bind(); });
  13554. svr_.wait_until_ready();
  13555. }
  13556. void TearDown() override {
  13557. svr_.stop();
  13558. if (thread_.joinable()) { thread_.join(); }
  13559. }
  13560. std::string request(const char *version, const char *expect_value) const {
  13561. return std::string("POST /p ") + version +
  13562. "\r\n"
  13563. "Host: localhost\r\n"
  13564. "Content-Length: 2\r\n"
  13565. "Connection: close\r\n"
  13566. "Expect: " +
  13567. expect_value +
  13568. "\r\n"
  13569. "\r\n"
  13570. "hi";
  13571. }
  13572. Server svr_;
  13573. int port_ = 0;
  13574. thread thread_;
  13575. };
  13576. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  13577. bool got_100 = false;
  13578. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  13579. EXPECT_TRUE(got_100);
  13580. }
  13581. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  13582. bool got_100 = true;
  13583. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  13584. EXPECT_FALSE(got_100);
  13585. }
  13586. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  13587. bool got_100 = false;
  13588. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  13589. EXPECT_TRUE(got_100);
  13590. }
  13591. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  13592. bool got_100 = false;
  13593. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  13594. EXPECT_TRUE(got_100);
  13595. }
  13596. #ifndef _WIN32
  13597. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13598. static constexpr char reject[] = "Unauthorized";
  13599. static constexpr char accept[] = "Upload accepted";
  13600. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  13601. Server svr;
  13602. svr.set_expect_100_continue_handler(
  13603. [](const Request & /*req*/, Response &res) {
  13604. res.status = StatusCode::Unauthorized_401;
  13605. res.set_content(reject, "text/plain");
  13606. return res.status;
  13607. });
  13608. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13609. res.set_content(accept, "text/plain");
  13610. });
  13611. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13612. auto se = detail::scope_exit([&] {
  13613. svr.stop();
  13614. thread.join();
  13615. ASSERT_FALSE(svr.is_running());
  13616. });
  13617. svr.wait_until_ready();
  13618. {
  13619. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13620. curl_easy_init(), &curl_easy_cleanup};
  13621. ASSERT_NE(curl, nullptr);
  13622. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13623. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13624. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13625. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13626. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13627. &curl_slist_free_all};
  13628. ASSERT_NE(list, nullptr);
  13629. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13630. struct read_data {
  13631. size_t read_size;
  13632. size_t total_size;
  13633. } data = {0, total_size};
  13634. using read_callback_t =
  13635. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13636. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13637. void *userdata) -> size_t {
  13638. read_data *d = (read_data *)userdata;
  13639. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13640. std::fill_n(ptr, size * nmemb, 'A');
  13641. d->read_size += size * nmemb;
  13642. return size * nmemb;
  13643. };
  13644. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13645. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13646. std::vector<char> buffer;
  13647. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13648. using write_callback_t =
  13649. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13650. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13651. void *userdata) -> size_t {
  13652. std::vector<char> *buf = (std::vector<char> *)userdata;
  13653. buf->reserve(buf->size() + size * nmemb + 1);
  13654. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13655. return size * nmemb;
  13656. };
  13657. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13658. {
  13659. const auto res = curl_easy_perform(curl.get());
  13660. ASSERT_EQ(res, CURLE_OK);
  13661. }
  13662. {
  13663. auto response_code = long{};
  13664. const auto res =
  13665. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13666. ASSERT_EQ(res, CURLE_OK);
  13667. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13668. }
  13669. {
  13670. auto dl = curl_off_t{};
  13671. const auto res =
  13672. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13673. ASSERT_EQ(res, CURLE_OK);
  13674. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13675. }
  13676. {
  13677. buffer.push_back('\0');
  13678. ASSERT_STRCASEEQ(buffer.data(), reject);
  13679. }
  13680. }
  13681. }
  13682. #endif
  13683. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13684. // Regression test for #2458.
  13685. //
  13686. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13687. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13688. // ticket can make the client socket spuriously readable during the
  13689. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13690. // the client withholds the body and then blocks reading a response that never
  13691. // comes, failing with `Failed to read connection`.
  13692. //
  13693. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13694. // within the timeout. This raw OpenSSL server deliberately never sends
  13695. // `100 Continue`; the client must still deliver the body and receive 200.
  13696. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13697. signal(SIGPIPE, SIG_IGN);
  13698. const auto port = PORT + 4;
  13699. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13700. ASSERT_NE(srv, INVALID_SOCKET);
  13701. int opt = 1;
  13702. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13703. sockaddr_in addr{};
  13704. addr.sin_family = AF_INET;
  13705. addr.sin_port = htons(static_cast<uint16_t>(port));
  13706. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13707. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13708. ASSERT_EQ(0, ::listen(srv, 1));
  13709. std::atomic<size_t> server_body_bytes{0};
  13710. auto server_thread = std::thread([&] {
  13711. sockaddr_in cli_addr{};
  13712. socklen_t cli_len = sizeof(cli_addr);
  13713. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13714. if (cli == INVALID_SOCKET) { return; }
  13715. // Bound the lifetime of the server side so a buggy client (which never
  13716. // sends the body) cannot make this thread block forever on join.
  13717. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13718. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13719. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13720. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13721. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13722. SSL *ssl = SSL_new(ctx);
  13723. SSL_set_fd(ssl, static_cast<int>(cli));
  13724. if (SSL_accept(ssl) > 0) {
  13725. // Read the request headers. Reading here also flushes the TLS 1.3
  13726. // session tickets to the client. Deliberately do NOT send
  13727. // `100 Continue`.
  13728. std::string buf;
  13729. char tmp[1024];
  13730. while (buf.find("\r\n\r\n") == std::string::npos) {
  13731. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13732. if (n <= 0) { break; }
  13733. buf.append(tmp, static_cast<size_t>(n));
  13734. }
  13735. // A correct client sends the body now; count what arrives.
  13736. auto pos = buf.find("\r\n\r\n");
  13737. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13738. while (body < 4096) {
  13739. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13740. if (n <= 0) { break; }
  13741. body += static_cast<size_t>(n);
  13742. }
  13743. server_body_bytes = body;
  13744. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13745. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13746. SSL_shutdown(ssl);
  13747. }
  13748. SSL_free(ssl);
  13749. detail::close_socket(cli);
  13750. SSL_CTX_free(ctx);
  13751. });
  13752. auto se = detail::scope_exit([&] {
  13753. server_thread.join();
  13754. detail::close_socket(srv);
  13755. });
  13756. SSLClient cli("127.0.0.1", port);
  13757. cli.enable_server_certificate_verification(false);
  13758. cli.set_connection_timeout(5, 0);
  13759. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13760. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13761. std::string body(4096, 'A');
  13762. auto res = cli.Put("/api/test", body, "application/json");
  13763. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13764. EXPECT_EQ(StatusCode::OK_200, res->status);
  13765. EXPECT_EQ(body.size(), server_body_bytes.load());
  13766. }
  13767. #endif
  13768. template <typename S, typename C>
  13769. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13770. svr.Get("/stream", [&](const Request &, Response &res) {
  13771. auto data = new std::string("01234567890123456789");
  13772. res.set_content_provider(
  13773. data->size(), "text/plain",
  13774. [&, data](size_t offset, size_t length, DataSink &sink) {
  13775. const size_t DATA_CHUNK_SIZE = 4;
  13776. const auto &d = *data;
  13777. std::this_thread::sleep_for(std::chrono::seconds(1));
  13778. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13779. return true;
  13780. },
  13781. [data](bool success) {
  13782. EXPECT_FALSE(success);
  13783. delete data;
  13784. });
  13785. });
  13786. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13787. auto i = new size_t(0);
  13788. res.set_content_provider(
  13789. "text/plain",
  13790. [i](size_t, DataSink &sink) {
  13791. if (*i < 5) {
  13792. std::this_thread::sleep_for(std::chrono::seconds(1));
  13793. sink.write("abcd", 4);
  13794. (*i)++;
  13795. } else {
  13796. sink.done();
  13797. }
  13798. return true;
  13799. },
  13800. [i](bool success) {
  13801. EXPECT_FALSE(success);
  13802. delete i;
  13803. });
  13804. });
  13805. svr.Get("/chunked", [&](const Request &, Response &res) {
  13806. auto i = new size_t(0);
  13807. res.set_chunked_content_provider(
  13808. "text/plain",
  13809. [i](size_t, DataSink &sink) {
  13810. if (*i < 5) {
  13811. std::this_thread::sleep_for(std::chrono::seconds(1));
  13812. sink.os << "abcd";
  13813. (*i)++;
  13814. } else {
  13815. sink.done();
  13816. }
  13817. return true;
  13818. },
  13819. [i](bool success) {
  13820. EXPECT_FALSE(success);
  13821. delete i;
  13822. });
  13823. });
  13824. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13825. auto se = detail::scope_exit([&] {
  13826. svr.stop();
  13827. listen_thread.join();
  13828. ASSERT_FALSE(svr.is_running());
  13829. });
  13830. svr.wait_until_ready();
  13831. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13832. {
  13833. auto start = std::chrono::steady_clock::now();
  13834. auto res = cli.Get("/stream");
  13835. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13836. std::chrono::steady_clock::now() - start)
  13837. .count();
  13838. ASSERT_FALSE(res);
  13839. EXPECT_EQ(Error::Read, res.error());
  13840. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13841. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13842. }
  13843. {
  13844. auto start = std::chrono::steady_clock::now();
  13845. auto res = cli.Get("/stream_without_length");
  13846. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13847. std::chrono::steady_clock::now() - start)
  13848. .count();
  13849. ASSERT_FALSE(res);
  13850. EXPECT_EQ(Error::Read, res.error());
  13851. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13852. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13853. }
  13854. {
  13855. auto start = std::chrono::steady_clock::now();
  13856. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13857. EXPECT_EQ("abcd", string(data, data_length));
  13858. return true;
  13859. });
  13860. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13861. std::chrono::steady_clock::now() - start)
  13862. .count();
  13863. ASSERT_FALSE(res);
  13864. EXPECT_EQ(Error::Read, res.error());
  13865. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13866. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13867. }
  13868. }
  13869. TEST(MaxTimeoutTest, ContentStream) {
  13870. time_t timeout = 2000;
  13871. time_t threshold = 200;
  13872. Server svr;
  13873. Client cli("localhost", PORT);
  13874. max_timeout_test(svr, cli, timeout, threshold);
  13875. }
  13876. #ifdef CPPHTTPLIB_SSL_ENABLED
  13877. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13878. time_t timeout = 2000;
  13879. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13881. SSLClient cli("localhost", PORT);
  13882. cli.enable_server_certificate_verification(false);
  13883. max_timeout_test(svr, cli, timeout, threshold);
  13884. }
  13885. #endif
  13886. class EventDispatcher {
  13887. public:
  13888. EventDispatcher() {}
  13889. bool wait_event(DataSink *sink) {
  13890. unique_lock<mutex> lk(m_);
  13891. int id = id_;
  13892. // Wait with timeout to prevent hanging if client disconnects
  13893. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13894. [&] { return cid_ == id; })) {
  13895. return false; // Timeout occurred
  13896. }
  13897. sink->write(message_.data(), message_.size());
  13898. return true;
  13899. }
  13900. void send_event(const string &message) {
  13901. lock_guard<mutex> lk(m_);
  13902. cid_ = id_++;
  13903. message_ = message;
  13904. cv_.notify_all();
  13905. }
  13906. private:
  13907. mutex m_;
  13908. condition_variable cv_;
  13909. atomic_int id_{0};
  13910. atomic_int cid_{-1};
  13911. string message_;
  13912. };
  13913. TEST(ClientInThreadTest, Issue2068) {
  13914. EventDispatcher ed;
  13915. Server svr;
  13916. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13917. res.set_chunked_content_provider("text/event-stream",
  13918. [&](size_t /*offset*/, DataSink &sink) {
  13919. return ed.wait_event(&sink);
  13920. });
  13921. });
  13922. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13923. svr.wait_until_ready();
  13924. thread event_thread([&] {
  13925. int id = 0;
  13926. while (svr.is_running()) {
  13927. this_thread::sleep_for(chrono::milliseconds(500));
  13928. std::stringstream ss;
  13929. ss << "data: " << id << "\n\n";
  13930. ed.send_event(ss.str());
  13931. id++;
  13932. }
  13933. });
  13934. auto se = detail::scope_exit([&] {
  13935. svr.stop();
  13936. listen_thread.join();
  13937. event_thread.join();
  13938. ASSERT_FALSE(svr.is_running());
  13939. });
  13940. {
  13941. auto client = detail::make_unique<Client>(HOST, PORT);
  13942. client->set_read_timeout(std::chrono::minutes(10));
  13943. std::atomic<bool> stop{false};
  13944. std::thread t([&] {
  13945. client->Get("/event1",
  13946. [&](const char *, size_t) -> bool { return !stop; });
  13947. });
  13948. std::this_thread::sleep_for(std::chrono::seconds(2));
  13949. stop = true;
  13950. client->stop();
  13951. t.join();
  13952. // Reset client after thread has finished
  13953. client.reset();
  13954. }
  13955. }
  13956. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13957. auto handled = false;
  13958. Server svr;
  13959. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13960. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13961. auto se = detail::scope_exit([&] {
  13962. svr.stop();
  13963. t.join();
  13964. ASSERT_FALSE(svr.is_running());
  13965. ASSERT_FALSE(handled);
  13966. });
  13967. svr.wait_until_ready();
  13968. // Two Content-Length headers with different values — must be rejected
  13969. auto req = "POST /test HTTP/1.1\r\n"
  13970. "Content-Length: 5\r\n"
  13971. "Content-Length: 10\r\n"
  13972. "\r\n"
  13973. "hello";
  13974. std::string response;
  13975. ASSERT_TRUE(send_request(1, req, &response));
  13976. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13977. response.substr(0, response.find("\r\n")));
  13978. }
  13979. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13980. auto handled = false;
  13981. Server svr;
  13982. svr.Post("/test", [&](const Request &, Response &res) {
  13983. handled = true;
  13984. res.set_content("ok", "text/plain");
  13985. });
  13986. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13987. auto se = detail::scope_exit([&] {
  13988. svr.stop();
  13989. t.join();
  13990. ASSERT_FALSE(svr.is_running());
  13991. ASSERT_TRUE(handled);
  13992. });
  13993. svr.wait_until_ready();
  13994. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13995. auto req = "POST /test HTTP/1.1\r\n"
  13996. "Content-Length: 5\r\n"
  13997. "Content-Length: 5\r\n"
  13998. "\r\n"
  13999. "hello";
  14000. std::string response;
  14001. ASSERT_TRUE(send_request(1, req, &response));
  14002. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  14003. }
  14004. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  14005. Server svr;
  14006. svr.Get("/", [](const Request &req, Response &res) {
  14007. EXPECT_EQ(2U, req.trailers.size());
  14008. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  14009. // Denied
  14010. EXPECT_FALSE(req.has_trailer("Content-Length"));
  14011. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  14012. // Accepted
  14013. EXPECT_TRUE(req.has_trailer("X-Hello"));
  14014. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  14015. EXPECT_TRUE(req.has_trailer("X-World"));
  14016. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  14017. res.set_content("ok", "text/plain");
  14018. });
  14019. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14020. auto se = detail::scope_exit([&] {
  14021. svr.stop();
  14022. t.join();
  14023. ASSERT_FALSE(svr.is_running());
  14024. });
  14025. svr.wait_until_ready();
  14026. const std::string req = "GET / HTTP/1.1\r\n"
  14027. "Transfer-Encoding: chunked\r\n"
  14028. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  14029. "\r\n"
  14030. "0\r\n"
  14031. "Content-Length: 10\r\n"
  14032. "Host: internal.local\r\n"
  14033. "Content-Type: malicious/content\r\n"
  14034. "Cookie: any\r\n"
  14035. "Set-Cookie: any\r\n"
  14036. "X-Forwarded-For: attacker.com\r\n"
  14037. "X-Real-Ip: 1.1.1.1\r\n"
  14038. "X-Hello: hello\r\n"
  14039. "X-World: world\r\n"
  14040. "\r\n";
  14041. std::string res;
  14042. ASSERT_TRUE(send_request(1, req, &res));
  14043. }
  14044. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  14045. // several field lines, and the combined value is what has to be parsed. A
  14046. // Trailer field split across lines therefore declares every name it lists;
  14047. // reading only the first line silently drops the trailers the later lines
  14048. // declare. The prohibited-trailer filter still applies to every line.
  14049. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  14050. Server svr;
  14051. size_t observed_trailer_count = 0;
  14052. std::string observed_hello;
  14053. std::string observed_world;
  14054. bool observed_content_length = true;
  14055. svr.Get("/", [&](const Request &req, Response &res) {
  14056. observed_trailer_count = req.trailers.size();
  14057. observed_hello = req.get_trailer_value("X-Hello");
  14058. observed_world = req.get_trailer_value("X-World");
  14059. observed_content_length = req.has_trailer("Content-Length");
  14060. res.set_content("ok", "text/plain");
  14061. });
  14062. auto port = svr.bind_to_any_port(HOST);
  14063. thread t = thread([&]() { svr.listen_after_bind(); });
  14064. auto se = detail::scope_exit([&] {
  14065. svr.stop();
  14066. t.join();
  14067. ASSERT_FALSE(svr.is_running());
  14068. });
  14069. svr.wait_until_ready();
  14070. const std::string req = "GET / HTTP/1.1\r\n"
  14071. "Transfer-Encoding: chunked\r\n"
  14072. "Trailer: X-Hello\r\n"
  14073. "Trailer: X-World, Content-Length\r\n"
  14074. "\r\n"
  14075. "0\r\n"
  14076. "X-Hello: hello\r\n"
  14077. "X-World: world\r\n"
  14078. "Content-Length: 10\r\n"
  14079. "\r\n";
  14080. std::string res;
  14081. ASSERT_TRUE(send_request(1, req, &res, port));
  14082. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  14083. // Accepted: both field lines contribute to the declared set
  14084. EXPECT_EQ(2U, observed_trailer_count);
  14085. EXPECT_EQ(observed_hello, "hello");
  14086. EXPECT_EQ(observed_world, "world");
  14087. // Denied: a prohibited name stays prohibited on a later field line
  14088. EXPECT_FALSE(observed_content_length);
  14089. }
  14090. // A direct client that is not listed in trusted_proxies must not be able to
  14091. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  14092. // the peer address on the actual TCP connection determines whether the
  14093. // header is honored.
  14094. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  14095. Server svr;
  14096. // Deliberately does NOT include the loopback address the test client
  14097. // actually connects from, so the direct connection is not a trusted proxy.
  14098. svr.set_trusted_proxies({"203.0.113.66"});
  14099. std::string observed_remote_addr;
  14100. svr.Get("/ip", [&](const Request &req, Response &res) {
  14101. observed_remote_addr = req.remote_addr;
  14102. res.set_content("ok", "text/plain");
  14103. });
  14104. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14105. auto se = detail::scope_exit([&] {
  14106. svr.stop();
  14107. t.join();
  14108. ASSERT_FALSE(svr.is_running());
  14109. });
  14110. svr.wait_until_ready();
  14111. Client cli(HOST, PORT);
  14112. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  14113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14114. EXPECT_EQ(StatusCode::OK_200, res->status);
  14115. // The connecting peer is not a trusted proxy, so the spoofed header must be
  14116. // ignored entirely and the real connection-level address retained.
  14117. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14118. observed_remote_addr == "127.0.0.1");
  14119. }
  14120. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  14121. Server svr;
  14122. std::string observed_remote_addr;
  14123. std::string observed_xff;
  14124. svr.Get("/ip", [&](const Request &req, Response &res) {
  14125. observed_remote_addr = req.remote_addr;
  14126. observed_xff = req.get_header_value("X-Forwarded-For");
  14127. res.set_content("ok", "text/plain");
  14128. });
  14129. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14130. auto se = detail::scope_exit([&] {
  14131. svr.stop();
  14132. t.join();
  14133. ASSERT_FALSE(svr.is_running());
  14134. });
  14135. svr.wait_until_ready();
  14136. Client cli(HOST, PORT);
  14137. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  14138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14139. EXPECT_EQ(StatusCode::OK_200, res->status);
  14140. EXPECT_EQ(observed_xff, "203.0.113.66");
  14141. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14142. observed_remote_addr == "127.0.0.1");
  14143. }
  14144. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  14145. Server svr;
  14146. svr.set_trusted_proxies({"203.0.113.66"});
  14147. std::string observed_remote_addr;
  14148. std::string observed_xff;
  14149. svr.Get("/ip", [&](const Request &req, Response &res) {
  14150. observed_remote_addr = req.remote_addr;
  14151. observed_xff = req.get_header_value("X-Forwarded-For");
  14152. res.set_content("ok", "text/plain");
  14153. });
  14154. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14155. auto se = detail::scope_exit([&] {
  14156. svr.stop();
  14157. t.join();
  14158. ASSERT_FALSE(svr.is_running());
  14159. });
  14160. svr.wait_until_ready();
  14161. Client cli(HOST, PORT);
  14162. auto res = cli.Get("/ip");
  14163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14164. EXPECT_EQ(StatusCode::OK_200, res->status);
  14165. EXPECT_EQ(observed_xff, "");
  14166. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14167. observed_remote_addr == "127.0.0.1");
  14168. }
  14169. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  14170. Server svr;
  14171. // Include the loopback address the test client actually connects from, so
  14172. // the direct connection itself is recognized as the trusted proxy hop.
  14173. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  14174. std::string observed_remote_addr;
  14175. std::string observed_xff;
  14176. svr.Get("/ip", [&](const Request &req, Response &res) {
  14177. observed_remote_addr = req.remote_addr;
  14178. observed_xff = req.get_header_value("X-Forwarded-For");
  14179. res.set_content("ok", "text/plain");
  14180. });
  14181. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14182. auto se = detail::scope_exit([&] {
  14183. svr.stop();
  14184. t.join();
  14185. ASSERT_FALSE(svr.is_running());
  14186. });
  14187. svr.wait_until_ready();
  14188. Client cli(HOST, PORT);
  14189. auto res = cli.Get(
  14190. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  14191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14192. EXPECT_EQ(StatusCode::OK_200, res->status);
  14193. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  14194. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14195. }
  14196. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  14197. Server svr;
  14198. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  14199. std::string observed_remote_addr;
  14200. std::string observed_xff;
  14201. svr.Get("/ip", [&](const Request &req, Response &res) {
  14202. observed_remote_addr = req.remote_addr;
  14203. observed_xff = req.get_header_value("X-Forwarded-For");
  14204. res.set_content("ok", "text/plain");
  14205. });
  14206. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14207. auto se = detail::scope_exit([&] {
  14208. svr.stop();
  14209. t.join();
  14210. ASSERT_FALSE(svr.is_running());
  14211. });
  14212. svr.wait_until_ready();
  14213. Client cli(HOST, PORT);
  14214. auto res = cli.Get(
  14215. "/ip",
  14216. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14218. EXPECT_EQ(StatusCode::OK_200, res->status);
  14219. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14220. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14221. }
  14222. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  14223. Server svr;
  14224. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14225. std::string observed_remote_addr;
  14226. std::string observed_xff;
  14227. svr.Get("/ip", [&](const Request &req, Response &res) {
  14228. observed_remote_addr = req.remote_addr;
  14229. observed_xff = req.get_header_value("X-Forwarded-For");
  14230. res.set_content("ok", "text/plain");
  14231. });
  14232. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14233. auto se = detail::scope_exit([&] {
  14234. svr.stop();
  14235. t.join();
  14236. ASSERT_FALSE(svr.is_running());
  14237. });
  14238. svr.wait_until_ready();
  14239. Client cli(HOST, PORT);
  14240. auto res = cli.Get(
  14241. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  14242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14243. EXPECT_EQ(StatusCode::OK_200, res->status);
  14244. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  14245. // by the closest hop) is used. The leftmost entry is fully client-controlled
  14246. // and must not be selected.
  14247. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  14248. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  14249. }
  14250. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  14251. Server svr;
  14252. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  14253. std::string observed_remote_addr;
  14254. svr.Get("/ip", [&](const Request &req, Response &res) {
  14255. observed_remote_addr = req.remote_addr;
  14256. res.set_content("ok", "text/plain");
  14257. });
  14258. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14259. auto se = detail::scope_exit([&] {
  14260. svr.stop();
  14261. t.join();
  14262. ASSERT_FALSE(svr.is_running());
  14263. });
  14264. svr.wait_until_ready();
  14265. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  14266. // a forged address and the trusted proxy's own address; the forged value must
  14267. // not win over the address the trusted proxy actually recorded.
  14268. Client cli(HOST, PORT);
  14269. auto res = cli.Get(
  14270. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  14271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14272. EXPECT_EQ(StatusCode::OK_200, res->status);
  14273. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  14274. }
  14275. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  14276. Server svr;
  14277. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14278. std::string observed_remote_addr;
  14279. std::string observed_xff;
  14280. svr.Get("/ip", [&](const Request &req, Response &res) {
  14281. observed_remote_addr = req.remote_addr;
  14282. observed_xff = req.get_header_value("X-Forwarded-For");
  14283. res.set_content("ok", "text/plain");
  14284. });
  14285. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14286. auto se = detail::scope_exit([&] {
  14287. svr.stop();
  14288. t.join();
  14289. ASSERT_FALSE(svr.is_running());
  14290. });
  14291. svr.wait_until_ready();
  14292. Client cli(HOST, PORT);
  14293. auto res = cli.Get(
  14294. "/ip",
  14295. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14297. EXPECT_EQ(StatusCode::OK_200, res->status);
  14298. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14299. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14300. }
  14301. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  14302. Server svr;
  14303. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14304. std::string observed_remote_addr;
  14305. std::string observed_xff;
  14306. svr.Get("/ip", [&](const Request &req, Response &res) {
  14307. observed_remote_addr = req.remote_addr;
  14308. observed_xff = req.get_header_value("X-Forwarded-For");
  14309. res.set_content("ok", "text/plain");
  14310. });
  14311. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14312. auto se = detail::scope_exit([&] {
  14313. svr.stop();
  14314. t.join();
  14315. ASSERT_FALSE(svr.is_running());
  14316. });
  14317. svr.wait_until_ready();
  14318. std::string raw_req =
  14319. "GET /ip HTTP/1.1\r\n"
  14320. "Host: localhost\r\n"
  14321. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  14322. "Connection: close\r\n"
  14323. "\r\n";
  14324. std::string out;
  14325. ASSERT_TRUE(send_request(5, raw_req, &out));
  14326. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14327. // Header parser trims surrounding whitespace of the header value
  14328. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  14329. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14330. }
  14331. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  14332. // one comma-joined value, in the order received. Proxies such as HAProxy append
  14333. // their own X-Forwarded-For as a separate field line rather than extending the
  14334. // one the client sent, so every occurrence has to be taken into account.
  14335. // Reading only the first one hands back the address the client chose.
  14336. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  14337. Server svr;
  14338. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14339. std::string observed_remote_addr;
  14340. size_t observed_xff_count = 0;
  14341. svr.Get("/ip", [&](const Request &req, Response &res) {
  14342. observed_remote_addr = req.remote_addr;
  14343. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  14344. res.set_content("ok", "text/plain");
  14345. });
  14346. auto port = svr.bind_to_any_port(HOST);
  14347. thread t = thread([&]() { svr.listen_after_bind(); });
  14348. auto se = detail::scope_exit([&] {
  14349. svr.stop();
  14350. t.join();
  14351. ASSERT_FALSE(svr.is_running());
  14352. });
  14353. svr.wait_until_ready();
  14354. // The client supplies the first field line; the trusted proxy appends the
  14355. // address it observed as a second one.
  14356. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  14357. "Host: localhost\r\n"
  14358. "X-Forwarded-For: 1.2.3.4\r\n"
  14359. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  14360. "Connection: close\r\n"
  14361. "\r\n";
  14362. std::string out;
  14363. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14364. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14365. EXPECT_EQ(observed_xff_count, 2U);
  14366. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14367. // The same chain spread over one field line per hop derives the same client
  14368. // address, i.e. the split and the comma-joined representations agree.
  14369. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  14370. "Host: localhost\r\n"
  14371. "X-Forwarded-For: 1.2.3.4\r\n"
  14372. "X-Forwarded-For: 198.51.100.23\r\n"
  14373. "X-Forwarded-For: 192.0.2.45\r\n"
  14374. "Connection: close\r\n"
  14375. "\r\n";
  14376. out.clear();
  14377. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  14378. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14379. EXPECT_EQ(observed_xff_count, 3U);
  14380. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14381. }
  14382. // An X-Forwarded-For header whose value parses to zero IP segments must not
  14383. // crash the server (it used to call front() on an empty vector inside
  14384. // get_client_ip). The connection-level remote address must be retained instead.
  14385. static void run_malformed_xff_test(const std::string &xff_value) {
  14386. Server svr;
  14387. svr.set_trusted_proxies({"192.0.2.45"});
  14388. std::string observed_remote_addr;
  14389. svr.Get("/ip", [&](const Request &req, Response &res) {
  14390. observed_remote_addr = req.remote_addr;
  14391. res.set_content("ok", "text/plain");
  14392. });
  14393. int port = 0;
  14394. thread t = thread([&]() {
  14395. port = svr.bind_to_any_port(HOST);
  14396. svr.listen_after_bind();
  14397. });
  14398. auto se = detail::scope_exit([&] {
  14399. svr.stop();
  14400. t.join();
  14401. ASSERT_FALSE(svr.is_running());
  14402. });
  14403. svr.wait_until_ready();
  14404. Client cli(HOST, port);
  14405. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  14406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14407. EXPECT_EQ(StatusCode::OK_200, res->status);
  14408. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14409. observed_remote_addr == "127.0.0.1");
  14410. }
  14411. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  14412. run_malformed_xff_test("");
  14413. }
  14414. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  14415. run_malformed_xff_test(",");
  14416. }
  14417. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  14418. run_malformed_xff_test(", , ,");
  14419. }
  14420. // The same rule applies to Accept: a request whose acceptable types are spread
  14421. // over several field lines must be negotiated against all of them.
  14422. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  14423. // case-insensitive connection options. Comparing the whole field value against
  14424. // one option misses a client that sends several of them, and misses every
  14425. // casing but the one written in the comparison.
  14426. //
  14427. // Sends req, reads the response, then reuses the same socket for a second
  14428. // request to find out whether the server kept the connection.
  14429. static void probe_connection_reuse(int port, const std::string &req,
  14430. bool *announced_close, bool *reusable) {
  14431. auto error = Error::Success;
  14432. auto sock = detail::create_client_socket(
  14433. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  14434. /*connection_timeout_sec=*/5, 0,
  14435. /*read_timeout_sec=*/1, 0,
  14436. /*write_timeout_sec=*/5, 0, std::string(), error);
  14437. ASSERT_NE(sock, INVALID_SOCKET);
  14438. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  14439. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  14440. "Host: localhost\r\n"
  14441. "Connection: close\r\n"
  14442. "\r\n";
  14443. std::string first_response;
  14444. std::string second_response;
  14445. detail::process_client_socket(
  14446. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  14447. [&](Stream &strm) {
  14448. if (strm.write(req.data(), req.size()) !=
  14449. static_cast<ssize_t>(req.size())) {
  14450. return false;
  14451. }
  14452. char buf[512];
  14453. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  14454. // Headers plus the two-byte body of the handler below
  14455. while (reader.getline()) {
  14456. first_response += reader.ptr();
  14457. if (first_response.find("ok") != std::string::npos) { break; }
  14458. }
  14459. if (strm.write(second.data(), second.size()) !=
  14460. static_cast<ssize_t>(second.size())) {
  14461. return true;
  14462. }
  14463. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  14464. while (reader2.getline()) {
  14465. second_response += reader2.ptr();
  14466. if (second_response.find("ok") != std::string::npos) { break; }
  14467. }
  14468. return true;
  14469. });
  14470. *announced_close =
  14471. first_response.find("Connection: close") != std::string::npos;
  14472. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  14473. }
  14474. class ConnectionTokenTest : public ::testing::Test {
  14475. protected:
  14476. void SetUp() override {
  14477. svr_.Get("/keepalive", [](const Request &, Response &res) {
  14478. res.set_content("ok", "text/plain");
  14479. });
  14480. port_ = svr_.bind_to_any_port(HOST);
  14481. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14482. svr_.wait_until_ready();
  14483. }
  14484. void TearDown() override {
  14485. svr_.stop();
  14486. if (thread_.joinable()) { thread_.join(); }
  14487. }
  14488. Server svr_;
  14489. int port_ = 0;
  14490. thread thread_;
  14491. };
  14492. // "close" alongside another option still closes the connection, and the
  14493. // response says so rather than leaving the peer to discover it.
  14494. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  14495. bool announced_close = false;
  14496. bool reusable = true;
  14497. probe_connection_reuse(port_,
  14498. "GET /keepalive HTTP/1.1\r\n"
  14499. "Host: localhost\r\n"
  14500. "Connection: keep-alive, close\r\n"
  14501. "\r\n",
  14502. &announced_close, &reusable);
  14503. EXPECT_TRUE(announced_close);
  14504. EXPECT_FALSE(reusable);
  14505. }
  14506. // "close" split over two field lines is the same list, so it is honored too.
  14507. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  14508. bool announced_close = false;
  14509. bool reusable = true;
  14510. probe_connection_reuse(port_,
  14511. "GET /keepalive HTTP/1.1\r\n"
  14512. "Host: localhost\r\n"
  14513. "Connection: keep-alive\r\n"
  14514. "Connection: close\r\n"
  14515. "\r\n",
  14516. &announced_close, &reusable);
  14517. EXPECT_TRUE(announced_close);
  14518. EXPECT_FALSE(reusable);
  14519. }
  14520. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  14521. // keep-alive in the spelling everyone actually sends keeps its connection.
  14522. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  14523. bool announced_close = false;
  14524. bool reusable = false;
  14525. probe_connection_reuse(port_,
  14526. "GET /keepalive HTTP/1.0\r\n"
  14527. "Host: localhost\r\n"
  14528. "Connection: keep-alive\r\n"
  14529. "\r\n",
  14530. &announced_close, &reusable);
  14531. EXPECT_FALSE(announced_close);
  14532. EXPECT_TRUE(reusable);
  14533. }
  14534. // A token the value merely contains is not the token itself.
  14535. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  14536. bool announced_close = false;
  14537. bool reusable = false;
  14538. probe_connection_reuse(port_,
  14539. "GET /keepalive HTTP/1.1\r\n"
  14540. "Host: localhost\r\n"
  14541. "Connection: notclose\r\n"
  14542. "\r\n",
  14543. &announced_close, &reusable);
  14544. EXPECT_FALSE(announced_close);
  14545. EXPECT_TRUE(reusable);
  14546. }
  14547. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  14548. Server svr;
  14549. std::vector<std::string> observed_types;
  14550. svr.Get("/", [&](const Request &req, Response &res) {
  14551. observed_types = req.accept_content_types;
  14552. res.set_content("ok", "text/plain");
  14553. });
  14554. auto port = svr.bind_to_any_port(HOST);
  14555. thread t = thread([&]() { svr.listen_after_bind(); });
  14556. auto se = detail::scope_exit([&] {
  14557. svr.stop();
  14558. t.join();
  14559. ASSERT_FALSE(svr.is_running());
  14560. });
  14561. svr.wait_until_ready();
  14562. Client cli(HOST, port);
  14563. Headers headers;
  14564. headers.emplace("Accept", "text/plain;q=0.5");
  14565. headers.emplace("Accept", "application/json");
  14566. auto res = cli.Get("/", headers);
  14567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14568. EXPECT_EQ(StatusCode::OK_200, res->status);
  14569. // Sorted by q-value, so the second field line's type comes first
  14570. ASSERT_EQ(2U, observed_types.size());
  14571. EXPECT_EQ("application/json", observed_types[0]);
  14572. EXPECT_EQ("text/plain", observed_types[1]);
  14573. }
  14574. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  14575. // empty field line must not contribute a bare comma to the combined value.
  14576. // parse_accept_header() rejects a leading comma outright, so a stray one would
  14577. // turn a legal request into 400 Bad Request.
  14578. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  14579. Server svr;
  14580. std::vector<std::string> observed_types;
  14581. svr.Get("/", [&](const Request &req, Response &res) {
  14582. observed_types = req.accept_content_types;
  14583. res.set_content("ok", "text/plain");
  14584. });
  14585. auto port = svr.bind_to_any_port(HOST);
  14586. thread t = thread([&]() { svr.listen_after_bind(); });
  14587. auto se = detail::scope_exit([&] {
  14588. svr.stop();
  14589. t.join();
  14590. ASSERT_FALSE(svr.is_running());
  14591. });
  14592. svr.wait_until_ready();
  14593. // Empty first field line, then a real one
  14594. std::string raw_req = "GET / HTTP/1.1\r\n"
  14595. "Host: localhost\r\n"
  14596. "Accept:\r\n"
  14597. "Accept: application/json\r\n"
  14598. "Connection: close\r\n"
  14599. "\r\n";
  14600. std::string out;
  14601. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14602. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14603. ASSERT_EQ(1U, observed_types.size());
  14604. EXPECT_EQ("application/json", observed_types[0]);
  14605. }
  14606. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14607. // An encoding offered on a later Accept-Encoding field line is still offered.
  14608. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  14609. Server svr;
  14610. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14611. res.set_content(std::string(1024, 'x'), "text/plain");
  14612. });
  14613. auto port = svr.bind_to_any_port(HOST);
  14614. thread t = thread([&]() { svr.listen_after_bind(); });
  14615. auto se = detail::scope_exit([&] {
  14616. svr.stop();
  14617. t.join();
  14618. ASSERT_FALSE(svr.is_running());
  14619. });
  14620. svr.wait_until_ready();
  14621. Client cli(HOST, port);
  14622. cli.set_decompress(false);
  14623. Headers headers;
  14624. headers.emplace("Accept-Encoding", "identity");
  14625. headers.emplace("Accept-Encoding", "gzip");
  14626. auto res = cli.Get("/", headers);
  14627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14628. EXPECT_EQ(StatusCode::OK_200, res->status);
  14629. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  14630. }
  14631. #endif
  14632. #ifndef _WIN32
  14633. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  14634. Server svr;
  14635. svr.Post("/post", [&](const Request &req, Response &res) {
  14636. res.set_content(req.body, "text/plain");
  14637. });
  14638. svr.Put("/put", [&](const Request &req, Response &res) {
  14639. res.set_content(req.body, "text/plain");
  14640. });
  14641. svr.Patch("/patch", [&](const Request &req, Response &res) {
  14642. res.set_content(req.body, "text/plain");
  14643. });
  14644. svr.Delete("/delete", [&](const Request &req, Response &res) {
  14645. res.set_content(req.body, "text/plain");
  14646. });
  14647. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14648. auto se = detail::scope_exit([&] {
  14649. svr.stop();
  14650. t.join();
  14651. ASSERT_FALSE(svr.is_running());
  14652. });
  14653. svr.wait_until_ready();
  14654. std::string resp;
  14655. // POST without Content-Length
  14656. ASSERT_TRUE(send_request(5,
  14657. "POST /post HTTP/1.1\r\n"
  14658. "Host: localhost\r\n"
  14659. "Connection: close\r\n"
  14660. "\r\n",
  14661. &resp));
  14662. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14663. // PUT without Content-Length
  14664. resp.clear();
  14665. ASSERT_TRUE(send_request(5,
  14666. "PUT /put HTTP/1.1\r\n"
  14667. "Host: localhost\r\n"
  14668. "Connection: close\r\n"
  14669. "\r\n",
  14670. &resp));
  14671. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14672. // PATCH without Content-Length
  14673. resp.clear();
  14674. ASSERT_TRUE(send_request(5,
  14675. "PATCH /patch HTTP/1.1\r\n"
  14676. "Host: localhost\r\n"
  14677. "Connection: close\r\n"
  14678. "\r\n",
  14679. &resp));
  14680. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14681. // DELETE without Content-Length
  14682. resp.clear();
  14683. ASSERT_TRUE(send_request(5,
  14684. "DELETE /delete HTTP/1.1\r\n"
  14685. "Host: localhost\r\n"
  14686. "Connection: close\r\n"
  14687. "\r\n",
  14688. &resp));
  14689. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14690. }
  14691. #endif
  14692. //==============================================================================
  14693. // open_stream() Tests
  14694. //==============================================================================
  14695. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  14696. std::string result;
  14697. char buf[8192];
  14698. ssize_t n;
  14699. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14700. result.append(buf, static_cast<size_t>(n));
  14701. }
  14702. return result;
  14703. }
  14704. // Mock stream for unit tests
  14705. class MockStream : public Stream {
  14706. public:
  14707. std::string data;
  14708. size_t pos = 0;
  14709. ssize_t error_after = -1; // -1 = no error
  14710. explicit MockStream(const std::string &d, ssize_t err = -1)
  14711. : data(d), error_after(err) {}
  14712. bool is_readable() const override { return true; }
  14713. bool wait_readable() const override { return true; }
  14714. bool wait_writable() const override { return true; }
  14715. ssize_t read(char *ptr, size_t size) override {
  14716. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  14717. if (pos >= data.size()) return 0;
  14718. size_t limit =
  14719. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  14720. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  14721. std::memcpy(ptr, data.data() + pos, to_read);
  14722. pos += to_read;
  14723. return static_cast<ssize_t>(to_read);
  14724. }
  14725. ssize_t write(const char *, size_t) override { return -1; }
  14726. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  14727. ip = "127.0.0.1";
  14728. port = 0;
  14729. }
  14730. void get_local_ip_and_port(std::string &ip, int &port) const override {
  14731. ip = "127.0.0.1";
  14732. port = 0;
  14733. }
  14734. socket_t socket() const override { return INVALID_SOCKET; }
  14735. time_t duration() const override { return 0; }
  14736. };
  14737. TEST(StreamHandleTest, Basic) {
  14738. ClientImpl::StreamHandle handle;
  14739. EXPECT_FALSE(handle.is_valid());
  14740. handle.response = detail::make_unique<Response>();
  14741. handle.error = Error::Connection;
  14742. EXPECT_FALSE(handle.is_valid());
  14743. handle.error = Error::Success;
  14744. EXPECT_TRUE(handle.is_valid());
  14745. }
  14746. TEST(BodyReaderTest, Basic) {
  14747. MockStream stream("Hello, World!");
  14748. detail::BodyReader reader;
  14749. reader.stream = &stream;
  14750. reader.content_length = 13;
  14751. char buf[32];
  14752. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  14753. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  14754. EXPECT_TRUE(reader.eof);
  14755. }
  14756. TEST(BodyReaderTest, NoStream) {
  14757. detail::BodyReader reader;
  14758. char buf[32];
  14759. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14760. EXPECT_EQ(Error::Connection, reader.last_error);
  14761. }
  14762. TEST(BodyReaderTest, Error) {
  14763. MockStream stream("Hello, World!", 5);
  14764. detail::BodyReader reader;
  14765. reader.stream = &stream;
  14766. reader.content_length = 13;
  14767. char buf[32];
  14768. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  14769. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14770. EXPECT_EQ(Error::Read, reader.last_error);
  14771. }
  14772. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  14773. // Mock-based StreamHandle tests relying on private internals are removed.
  14774. class OpenStreamTest : public ::testing::Test {
  14775. protected:
  14776. void SetUp() override {
  14777. svr_.Get("/hello", [](const Request &, Response &res) {
  14778. res.set_content("Hello World!", "text/plain");
  14779. });
  14780. svr_.Get("/large", [](const Request &, Response &res) {
  14781. res.set_content(std::string(10000, 'X'), "text/plain");
  14782. });
  14783. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  14784. res.set_content("Hello World!", "image/jpeg");
  14785. res.set_header("Content-Encoding", "UTF-8");
  14786. });
  14787. svr_.Get("/chunked", [](const Request &, Response &res) {
  14788. res.set_chunked_content_provider("text/plain",
  14789. [](size_t offset, DataSink &sink) {
  14790. if (offset < 15) {
  14791. sink.write("chunk", 5);
  14792. return true;
  14793. }
  14794. sink.done();
  14795. return true;
  14796. });
  14797. });
  14798. svr_.Get("/compressible", [](const Request &, Response &res) {
  14799. res.set_chunked_content_provider("text/plain", [](size_t offset,
  14800. DataSink &sink) {
  14801. if (offset < 100 * 1024) {
  14802. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  14803. sink.write(chunk.data(), chunk.size());
  14804. return true;
  14805. }
  14806. sink.done();
  14807. return true;
  14808. });
  14809. });
  14810. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  14811. [](const Request & /*req*/, Response &res) {
  14812. auto i = new int(0);
  14813. res.set_header("Trailer", "Content-Length, X-Allowed");
  14814. res.set_chunked_content_provider(
  14815. "text/plain",
  14816. [i](size_t /*offset*/, DataSink &sink) {
  14817. switch (*i) {
  14818. case 0: sink.os << "123"; break;
  14819. case 1: sink.os << "456"; break;
  14820. case 2: sink.os << "789"; break;
  14821. case 3: {
  14822. sink.done_with_trailer(
  14823. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  14824. } break;
  14825. }
  14826. (*i)++;
  14827. return true;
  14828. },
  14829. [i](bool success) {
  14830. EXPECT_TRUE(success);
  14831. delete i;
  14832. });
  14833. });
  14834. // Echo headers endpoint for header-related tests
  14835. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  14836. std::string body;
  14837. for (const auto &h : req.headers) {
  14838. body.append(h.first);
  14839. body.push_back(':');
  14840. body.append(h.second);
  14841. body.push_back('\n');
  14842. }
  14843. res.set_content(body, "text/plain");
  14844. });
  14845. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  14846. std::string body;
  14847. for (const auto &h : req.headers) {
  14848. body.append(h.first);
  14849. body.push_back(':');
  14850. body.append(h.second);
  14851. body.push_back('\n');
  14852. }
  14853. res.set_content(body, "text/plain");
  14854. });
  14855. port_ = svr_.bind_to_any_port("127.0.0.1");
  14856. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14857. svr_.wait_until_ready();
  14858. }
  14859. void TearDown() override {
  14860. svr_.stop();
  14861. if (thread_.joinable()) thread_.join();
  14862. }
  14863. Server svr_;
  14864. std::thread thread_;
  14865. int port_ = 0;
  14866. };
  14867. TEST_F(OpenStreamTest, Basic) {
  14868. Client cli("127.0.0.1", port_);
  14869. auto handle = cli.open_stream("GET", "/hello");
  14870. EXPECT_TRUE(handle.is_valid());
  14871. EXPECT_EQ("Hello World!", read_all(handle));
  14872. }
  14873. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  14874. Client cli("127.0.0.1", port_);
  14875. auto handle = cli.open_stream("GET", "/unknown-encoding");
  14876. ASSERT_TRUE(handle.is_valid());
  14877. EXPECT_EQ("Hello World!", read_all(handle));
  14878. }
  14879. TEST_F(OpenStreamTest, SmallBuffer) {
  14880. Client cli("127.0.0.1", port_);
  14881. auto handle = cli.open_stream("GET", "/hello");
  14882. std::string result;
  14883. char buf[4];
  14884. ssize_t n;
  14885. while ((n = handle.read(buf, sizeof(buf))) > 0)
  14886. result.append(buf, static_cast<size_t>(n));
  14887. EXPECT_EQ("Hello World!", result);
  14888. }
  14889. TEST_F(OpenStreamTest, DefaultHeaders) {
  14890. Client cli("127.0.0.1", port_);
  14891. // open_stream GET should include Host, User-Agent and Accept-Encoding
  14892. {
  14893. auto handle = cli.open_stream("GET", "/echo-headers");
  14894. ASSERT_TRUE(handle.is_valid());
  14895. auto body = read_all(handle);
  14896. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  14897. std::string::npos);
  14898. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  14899. std::string::npos);
  14900. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  14901. }
  14902. // open_stream POST with body and no explicit content_type should NOT add
  14903. // text/plain Content-Type (behavior differs from non-streaming path), but
  14904. // should include Content-Length
  14905. {
  14906. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  14907. ASSERT_TRUE(handle.is_valid());
  14908. auto body = read_all(handle);
  14909. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  14910. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  14911. }
  14912. // open_stream POST with explicit Content-Type should preserve it
  14913. {
  14914. auto handle = cli.open_stream("POST", "/echo-headers", {},
  14915. {{"Content-Type", "application/custom"}},
  14916. "{}", "application/custom");
  14917. ASSERT_TRUE(handle.is_valid());
  14918. auto body = read_all(handle);
  14919. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  14920. }
  14921. // User-specified User-Agent must not be overwritten for stream API
  14922. {
  14923. auto handle = cli.open_stream("GET", "/echo-headers", {},
  14924. {{"User-Agent", "MyAgent/1.2"}});
  14925. ASSERT_TRUE(handle.is_valid());
  14926. auto body = read_all(handle);
  14927. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  14928. }
  14929. }
  14930. TEST_F(OpenStreamTest, Large) {
  14931. Client cli("127.0.0.1", port_);
  14932. auto handle = cli.open_stream("GET", "/large");
  14933. EXPECT_EQ(10000u, read_all(handle).size());
  14934. }
  14935. TEST_F(OpenStreamTest, ConnectionError) {
  14936. Client cli("127.0.0.1", 9999);
  14937. auto handle = cli.open_stream("GET", "/hello");
  14938. EXPECT_FALSE(handle.is_valid());
  14939. }
  14940. TEST_F(OpenStreamTest, Chunked) {
  14941. Client cli("127.0.0.1", port_);
  14942. auto handle = cli.open_stream("GET", "/chunked");
  14943. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14944. "Transfer-Encoding") == "chunked");
  14945. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  14946. }
  14947. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  14948. Client cli("127.0.0.1", port_);
  14949. auto handle =
  14950. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  14951. ASSERT_TRUE(handle.is_valid());
  14952. // Consume body to allow trailers to be received/parsed
  14953. auto body = read_all(handle);
  14954. // Explicitly parse trailers (ensure trailers are available for assertion)
  14955. handle.parse_trailers_if_needed();
  14956. EXPECT_EQ(std::string("123456789"), body);
  14957. // The response should include a Trailer header declaring both names
  14958. ASSERT_TRUE(handle.response);
  14959. EXPECT_TRUE(handle.response->has_header("Trailer"));
  14960. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  14961. handle.response->get_header_value("Trailer"));
  14962. // Prohibited trailer must not be present
  14963. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  14964. // Allowed trailer should be present
  14965. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  14966. EXPECT_EQ(std::string("yes"),
  14967. handle.response->get_trailer_value("X-Allowed"));
  14968. // Verify trailers are NOT present as regular headers
  14969. EXPECT_EQ(std::string(""),
  14970. handle.response->get_header_value("Content-Length"));
  14971. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  14972. }
  14973. static std::thread serve_single_response(std::promise<int> &port_promise,
  14974. const std::string &response) {
  14975. return std::thread([&port_promise, response] {
  14976. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14977. default_socket_options(srv);
  14978. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14979. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14980. sockaddr_in addr{};
  14981. addr.sin_family = AF_INET;
  14982. addr.sin_port = htons(0); // Let OS assign a free port
  14983. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14984. int opt = 1;
  14985. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14986. #ifdef _WIN32
  14987. reinterpret_cast<const char *>(&opt),
  14988. #else
  14989. &opt,
  14990. #endif
  14991. sizeof(opt));
  14992. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  14993. ::listen(srv, 1) != 0) {
  14994. port_promise.set_value(-1);
  14995. detail::close_socket(srv);
  14996. return;
  14997. }
  14998. socklen_t addr_len = sizeof(addr);
  14999. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  15000. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  15001. sockaddr_in cli_addr{};
  15002. socklen_t cli_len = sizeof(cli_addr);
  15003. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15004. if (cli != INVALID_SOCKET) {
  15005. // Read the complete HTTP request (until the blank line that terminates
  15006. // headers) before sending the response. If the server closes the socket
  15007. // while the client's request data is still unread in the kernel receive
  15008. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  15009. // connection on both sides: it discards the client's receive buffer
  15010. // (which already holds our response) and causes any in-progress write on
  15011. // the client to fail with ECONNRESET. Reading all request data first
  15012. // ensures close() emits a graceful FIN.
  15013. {
  15014. char rbuf[256];
  15015. std::string req;
  15016. while (req.find("\r\n\r\n") == std::string::npos) {
  15017. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  15018. if (n <= 0) { break; }
  15019. req.append(rbuf, static_cast<size_t>(n));
  15020. }
  15021. }
  15022. ::send(cli,
  15023. #ifdef _WIN32
  15024. static_cast<const char *>(response.c_str()),
  15025. static_cast<int>(response.size()),
  15026. #else
  15027. response.c_str(), response.size(),
  15028. #endif
  15029. 0);
  15030. detail::close_socket(cli);
  15031. }
  15032. detail::close_socket(srv);
  15033. });
  15034. }
  15035. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  15036. #ifndef _WIN32
  15037. signal(SIGPIPE, SIG_IGN);
  15038. #endif
  15039. std::promise<int> port_promise;
  15040. auto port_future = port_promise.get_future();
  15041. auto server_thread =
  15042. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  15043. "Content-Type: text/plain\r\n"
  15044. "Content-Length: not-a-number\r\n"
  15045. "Connection: close\r\n"
  15046. "\r\n"
  15047. "hello");
  15048. auto port = port_future.get();
  15049. ASSERT_GT(port, 0);
  15050. Client cli("127.0.0.1", port);
  15051. auto handle = cli.open_stream("GET", "/");
  15052. EXPECT_FALSE(handle.is_valid());
  15053. server_thread.join();
  15054. }
  15055. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  15056. #ifndef _WIN32
  15057. signal(SIGPIPE, SIG_IGN);
  15058. #endif
  15059. std::promise<int> port_promise;
  15060. auto port_future = port_promise.get_future();
  15061. auto server_thread = serve_single_response(
  15062. port_promise, "HTTP/1.1 200 OK\r\n"
  15063. "Content-Type: text/plain\r\n"
  15064. "Content-Length: 99999999999999999999999999\r\n"
  15065. "Connection: close\r\n"
  15066. "\r\n"
  15067. "hello");
  15068. auto port = port_future.get();
  15069. ASSERT_GT(port, 0);
  15070. // Historically std::stoull would throw std::out_of_range here and crash
  15071. // the process, then parsing silently clamped to a bogus framing length and
  15072. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  15073. // so the stream fails to open, matching the not-a-number case above. The
  15074. // process still must NOT terminate.
  15075. Client cli("127.0.0.1", port);
  15076. auto handle = cli.open_stream("GET", "/");
  15077. EXPECT_FALSE(handle.is_valid());
  15078. server_thread.join();
  15079. }
  15080. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15081. TEST_F(OpenStreamTest, Gzip) {
  15082. Client cli("127.0.0.1", port_);
  15083. auto handle = cli.open_stream("GET", "/compressible", {},
  15084. {{"Accept-Encoding", "gzip"}});
  15085. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  15086. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15087. }
  15088. #endif
  15089. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15090. TEST_F(OpenStreamTest, Brotli) {
  15091. Client cli("127.0.0.1", port_);
  15092. auto handle =
  15093. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  15094. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  15095. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15096. }
  15097. #endif
  15098. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15099. TEST_F(OpenStreamTest, Zstd) {
  15100. Client cli("127.0.0.1", port_);
  15101. auto handle = cli.open_stream("GET", "/compressible", {},
  15102. {{"Accept-Encoding", "zstd"}});
  15103. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  15104. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15105. }
  15106. #endif
  15107. #ifdef CPPHTTPLIB_SSL_ENABLED
  15108. class SSLOpenStreamTest : public ::testing::Test {
  15109. protected:
  15110. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  15111. void SetUp() override {
  15112. svr_.Get("/hello", [](const Request &, Response &res) {
  15113. res.set_content("Hello SSL World!", "text/plain");
  15114. });
  15115. svr_.Get("/chunked", [](const Request &, Response &res) {
  15116. res.set_chunked_content_provider("text/plain",
  15117. [](size_t offset, DataSink &sink) {
  15118. if (offset < 15) {
  15119. sink.write("chunk", 5);
  15120. return true;
  15121. }
  15122. sink.done();
  15123. return true;
  15124. });
  15125. });
  15126. svr_.Post("/echo", [](const Request &req, Response &res) {
  15127. res.set_content(req.body, req.get_header_value("Content-Type"));
  15128. });
  15129. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  15130. std::string body = req.body;
  15131. res.set_chunked_content_provider(
  15132. "text/plain", [body](size_t offset, DataSink &sink) {
  15133. if (offset < body.size()) {
  15134. sink.write(body.data() + offset, body.size() - offset);
  15135. }
  15136. sink.done();
  15137. return true;
  15138. });
  15139. });
  15140. port_ = svr_.bind_to_any_port("127.0.0.1");
  15141. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15142. svr_.wait_until_ready();
  15143. }
  15144. void TearDown() override {
  15145. svr_.stop();
  15146. if (thread_.joinable()) thread_.join();
  15147. }
  15148. SSLServer svr_;
  15149. std::thread thread_;
  15150. int port_ = 0;
  15151. };
  15152. TEST_F(SSLOpenStreamTest, Basic) {
  15153. SSLClient cli("127.0.0.1", port_);
  15154. cli.enable_server_certificate_verification(false);
  15155. auto handle = cli.open_stream("GET", "/hello");
  15156. ASSERT_TRUE(handle.is_valid());
  15157. EXPECT_EQ("Hello SSL World!", read_all(handle));
  15158. }
  15159. TEST_F(SSLOpenStreamTest, Chunked) {
  15160. SSLClient cli("127.0.0.1", port_);
  15161. cli.enable_server_certificate_verification(false);
  15162. auto handle = cli.open_stream("GET", "/chunked");
  15163. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15164. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15165. "Transfer-Encoding") == "chunked");
  15166. auto body = read_all(handle);
  15167. EXPECT_EQ("chunkchunkchunk", body);
  15168. }
  15169. TEST_F(SSLOpenStreamTest, Post) {
  15170. SSLClient cli("127.0.0.1", port_);
  15171. cli.enable_server_certificate_verification(false);
  15172. auto handle =
  15173. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  15174. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15175. EXPECT_EQ(200, handle.response->status);
  15176. auto body = read_all(handle);
  15177. EXPECT_EQ("Hello SSL POST", body);
  15178. }
  15179. TEST_F(SSLOpenStreamTest, PostChunked) {
  15180. SSLClient cli("127.0.0.1", port_);
  15181. cli.enable_server_certificate_verification(false);
  15182. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  15183. "Chunked SSL Data", "text/plain");
  15184. ASSERT_TRUE(handle.is_valid());
  15185. EXPECT_EQ(200, handle.response->status);
  15186. auto body = read_all(handle);
  15187. EXPECT_EQ("Chunked SSL Data", body);
  15188. }
  15189. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  15190. // Content-Length is terminated by the server closing the connection. When the
  15191. // SSL peer sends a close_notify after the body, the client must treat it as a
  15192. // clean EOF and return a successful response rather than an error.
  15193. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  15194. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15195. ASSERT_TRUE(svr.is_valid());
  15196. svr.set_keep_alive_max_count(1);
  15197. const std::string expected_body = "Hello from connection-close response!";
  15198. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  15199. res.set_content_provider("text/plain",
  15200. [&](size_t offset, DataSink &sink) -> bool {
  15201. if (offset < expected_body.size()) {
  15202. sink.write(expected_body.data() + offset,
  15203. expected_body.size() - offset);
  15204. }
  15205. sink.done();
  15206. return true;
  15207. });
  15208. });
  15209. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  15210. auto se = detail::scope_exit([&] {
  15211. svr.stop();
  15212. listen_thread.join();
  15213. ASSERT_FALSE(svr.is_running());
  15214. });
  15215. svr.wait_until_ready();
  15216. SSLClient cli(HOST, PORT);
  15217. cli.enable_server_certificate_verification(false);
  15218. auto res = cli.Get("/no-content-length");
  15219. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  15220. EXPECT_EQ(StatusCode::OK_200, res->status);
  15221. EXPECT_EQ(expected_body, res->body);
  15222. }
  15223. #endif // CPPHTTPLIB_SSL_ENABLED
  15224. //==============================================================================
  15225. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  15226. // results for various scenarios.
  15227. //==============================================================================
  15228. TEST(ParityTest, GetVsOpenStream) {
  15229. Server svr;
  15230. const std::string path = "/parity";
  15231. const std::string content = "Parity test content: hello world";
  15232. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15233. res.set_content(content, "text/plain");
  15234. });
  15235. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15236. auto se = detail::scope_exit([&] {
  15237. svr.stop();
  15238. t.join();
  15239. ASSERT_FALSE(svr.is_running());
  15240. });
  15241. svr.wait_until_ready();
  15242. Client cli(HOST, PORT);
  15243. // Non-stream path
  15244. auto r1 = cli.Get(path);
  15245. ASSERT_TRUE(r1);
  15246. EXPECT_EQ(StatusCode::OK_200, r1->status);
  15247. // Stream path
  15248. auto h = cli.open_stream("GET", path);
  15249. ASSERT_TRUE(h.is_valid());
  15250. EXPECT_EQ(r1->body, read_all(h));
  15251. }
  15252. // Helper to compress data with provided compressor type T
  15253. template <typename Compressor>
  15254. static std::string compress_payload_for_parity(const std::string &in) {
  15255. std::string out;
  15256. Compressor compressor;
  15257. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  15258. [&](const char *data, size_t n) {
  15259. out.append(data, n);
  15260. return true;
  15261. });
  15262. EXPECT_TRUE(ok);
  15263. return out;
  15264. }
  15265. // Helper function for compression parity tests
  15266. template <typename Compressor>
  15267. static void test_compression_parity(const std::string &original,
  15268. const std::string &path,
  15269. const std::string &encoding) {
  15270. const std::string compressed =
  15271. compress_payload_for_parity<Compressor>(original);
  15272. Server svr;
  15273. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15274. res.set_content(compressed, "application/octet-stream");
  15275. res.set_header("Content-Encoding", encoding);
  15276. });
  15277. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  15278. auto se = detail::scope_exit([&] {
  15279. svr.stop();
  15280. t.join();
  15281. ASSERT_FALSE(svr.is_running());
  15282. });
  15283. svr.wait_until_ready();
  15284. Client cli(HOST, PORT);
  15285. // Non-streaming
  15286. {
  15287. auto res = cli.Get(path);
  15288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15289. EXPECT_EQ(StatusCode::OK_200, res->status);
  15290. EXPECT_EQ(original, res->body);
  15291. }
  15292. // Streaming
  15293. {
  15294. auto h = cli.open_stream("GET", path);
  15295. ASSERT_TRUE(h.is_valid());
  15296. EXPECT_EQ(original, read_all(h));
  15297. }
  15298. }
  15299. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15300. TEST(ParityTest, Gzip) {
  15301. test_compression_parity<detail::gzip_compressor>(
  15302. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  15303. }
  15304. #endif
  15305. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15306. TEST(ParityTest, Brotli) {
  15307. test_compression_parity<detail::brotli_compressor>(
  15308. "Hello, brotli parity test payload", "/parity-br", "br");
  15309. }
  15310. #endif
  15311. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15312. TEST(ParityTest, Zstd) {
  15313. test_compression_parity<detail::zstd_compressor>(
  15314. "Zstandard parity test payload", "/parity-zstd", "zstd");
  15315. }
  15316. #endif
  15317. //==============================================================================
  15318. // New Stream API Tests
  15319. //==============================================================================
  15320. inline std::string read_body(httplib::stream::Result &result) {
  15321. std::string body;
  15322. while (result.next()) {
  15323. body.append(result.data(), result.size());
  15324. }
  15325. return body;
  15326. }
  15327. TEST(ClientConnectionTest, Basic) {
  15328. httplib::ClientConnection conn;
  15329. EXPECT_FALSE(conn.is_open());
  15330. conn.sock = 1;
  15331. EXPECT_TRUE(conn.is_open());
  15332. httplib::ClientConnection conn2(std::move(conn));
  15333. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  15334. conn2.sock = INVALID_SOCKET;
  15335. }
  15336. // Unified test server for all stream::* tests
  15337. class StreamApiTest : public ::testing::Test {
  15338. protected:
  15339. void SetUp() override {
  15340. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15341. res.set_content("Hello World!", "text/plain");
  15342. });
  15343. svr_.Get("/echo-params",
  15344. [](const httplib::Request &req, httplib::Response &res) {
  15345. std::string r;
  15346. for (const auto &p : req.params) {
  15347. if (!r.empty()) r += "&";
  15348. r += p.first + "=" + p.second;
  15349. }
  15350. res.set_content(r, "text/plain");
  15351. });
  15352. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15353. res.set_content(req.body, req.get_header_value("Content-Type"));
  15354. });
  15355. svr_.Post("/echo-headers",
  15356. [](const httplib::Request &req, httplib::Response &res) {
  15357. std::string r;
  15358. for (const auto &h : req.headers)
  15359. r += h.first + ": " + h.second + "\n";
  15360. res.set_content(r, "text/plain");
  15361. });
  15362. svr_.Post("/echo-params",
  15363. [](const httplib::Request &req, httplib::Response &res) {
  15364. std::string r = "params:";
  15365. for (const auto &p : req.params)
  15366. r += p.first + "=" + p.second + ";";
  15367. res.set_content(r + " body:" + req.body, "text/plain");
  15368. });
  15369. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  15370. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  15371. });
  15372. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15373. res.set_content("PUT:" + req.body, "text/plain");
  15374. });
  15375. svr_.Patch("/echo",
  15376. [](const httplib::Request &req, httplib::Response &res) {
  15377. res.set_content("PATCH:" + req.body, "text/plain");
  15378. });
  15379. svr_.Delete(
  15380. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  15381. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  15382. "text/plain");
  15383. });
  15384. svr_.Get("/head-test",
  15385. [](const httplib::Request &, httplib::Response &res) {
  15386. res.set_content("body for HEAD", "text/plain");
  15387. });
  15388. svr_.Options("/options",
  15389. [](const httplib::Request &, httplib::Response &res) {
  15390. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  15391. });
  15392. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  15393. svr_.wait_until_ready();
  15394. }
  15395. void TearDown() override {
  15396. svr_.stop();
  15397. if (thread_.joinable()) thread_.join();
  15398. }
  15399. httplib::Server svr_;
  15400. std::thread thread_;
  15401. };
  15402. // stream::Get tests
  15403. TEST_F(StreamApiTest, GetBasic) {
  15404. httplib::Client cli(HOST, PORT);
  15405. auto result = httplib::stream::Get(cli, "/hello");
  15406. ASSERT_TRUE(result.is_valid());
  15407. EXPECT_EQ(200, result.status());
  15408. EXPECT_EQ("Hello World!", read_body(result));
  15409. }
  15410. TEST_F(StreamApiTest, GetWithParams) {
  15411. httplib::Client cli(HOST, PORT);
  15412. httplib::Params params{{"foo", "bar"}};
  15413. auto result = httplib::stream::Get(cli, "/echo-params", params);
  15414. ASSERT_TRUE(result.is_valid());
  15415. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  15416. }
  15417. TEST_F(StreamApiTest, GetConnectionError) {
  15418. httplib::Client cli(HOST, 9999);
  15419. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  15420. }
  15421. TEST_F(StreamApiTest, Get404) {
  15422. httplib::Client cli(HOST, PORT);
  15423. auto result = httplib::stream::Get(cli, "/nonexistent");
  15424. EXPECT_TRUE(result.is_valid());
  15425. EXPECT_EQ(404, result.status());
  15426. }
  15427. // stream::Post tests
  15428. TEST_F(StreamApiTest, PostBasic) {
  15429. httplib::Client cli(HOST, PORT);
  15430. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  15431. "application/json");
  15432. ASSERT_TRUE(result.is_valid());
  15433. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  15434. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  15435. }
  15436. TEST_F(StreamApiTest, PostWithHeaders) {
  15437. httplib::Client cli(HOST, PORT);
  15438. httplib::Headers headers{{"X-Custom", "value"}};
  15439. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  15440. "text/plain");
  15441. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  15442. }
  15443. TEST_F(StreamApiTest, PostWithParams) {
  15444. httplib::Client cli(HOST, PORT);
  15445. httplib::Params params{{"k", "v"}};
  15446. auto result =
  15447. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  15448. auto body = read_body(result);
  15449. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  15450. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  15451. }
  15452. TEST_F(StreamApiTest, PostLarge) {
  15453. httplib::Client cli(HOST, PORT);
  15454. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  15455. size_t total = 0;
  15456. while (result.next()) {
  15457. total += result.size();
  15458. }
  15459. EXPECT_EQ(100u * 1024u, total);
  15460. }
  15461. // stream::Put/Patch tests
  15462. TEST_F(StreamApiTest, PutAndPatch) {
  15463. httplib::Client cli(HOST, PORT);
  15464. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  15465. EXPECT_EQ("PUT:test", read_body(put));
  15466. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  15467. EXPECT_EQ("PATCH:test", read_body(patch));
  15468. }
  15469. // stream::Delete tests
  15470. TEST_F(StreamApiTest, Delete) {
  15471. httplib::Client cli(HOST, PORT);
  15472. auto del1 = httplib::stream::Delete(cli, "/resource");
  15473. EXPECT_EQ("Deleted", read_body(del1));
  15474. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  15475. EXPECT_EQ("Deleted:data", read_body(del2));
  15476. }
  15477. // stream::Head/Options tests
  15478. TEST_F(StreamApiTest, HeadAndOptions) {
  15479. httplib::Client cli(HOST, PORT);
  15480. auto head = httplib::stream::Head(cli, "/head-test");
  15481. EXPECT_TRUE(head.is_valid());
  15482. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  15483. auto opts = httplib::stream::Options(cli, "/options");
  15484. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  15485. }
  15486. // SSL stream::* tests
  15487. #ifdef CPPHTTPLIB_SSL_ENABLED
  15488. class SSLStreamApiTest : public ::testing::Test {
  15489. protected:
  15490. void SetUp() override {
  15491. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15492. res.set_content("Hello SSL!", "text/plain");
  15493. });
  15494. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15495. res.set_content(req.body, "text/plain");
  15496. });
  15497. port_ = svr_.bind_to_any_port("127.0.0.1");
  15498. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15499. svr_.wait_until_ready();
  15500. }
  15501. void TearDown() override {
  15502. svr_.stop();
  15503. if (thread_.joinable()) thread_.join();
  15504. }
  15505. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  15506. std::thread thread_;
  15507. int port_ = 0;
  15508. };
  15509. TEST_F(SSLStreamApiTest, GetAndPost) {
  15510. httplib::SSLClient cli("127.0.0.1", port_);
  15511. cli.enable_server_certificate_verification(false);
  15512. auto get = httplib::stream::Get(cli, "/hello");
  15513. EXPECT_EQ("Hello SSL!", read_body(get));
  15514. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  15515. EXPECT_EQ("test", read_body(post));
  15516. }
  15517. #endif
  15518. // Tests for Error::Timeout and Error::ConnectionClosed error types
  15519. // These errors are set in SocketStream/SSLSocketStream and propagated through
  15520. // BodyReader
  15521. TEST(ErrorHandlingTest, StreamReadTimeout) {
  15522. // Test that read timeout during streaming is detected
  15523. // Use a large content-length response where server delays mid-stream
  15524. Server svr;
  15525. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15526. // Send a large response with delay in the middle
  15527. res.set_content_provider(
  15528. 1000, // content_length
  15529. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  15530. if (offset < 100) {
  15531. // Send first 100 bytes immediately
  15532. std::string data(100, 'A');
  15533. sink.write(data.c_str(), data.size());
  15534. return true;
  15535. }
  15536. // Then delay longer than client timeout
  15537. std::this_thread::sleep_for(std::chrono::seconds(3));
  15538. std::string data(900, 'B');
  15539. sink.write(data.c_str(), data.size());
  15540. return true;
  15541. });
  15542. });
  15543. auto port = 8091;
  15544. std::thread t([&]() { svr.listen("localhost", port); });
  15545. svr.wait_until_ready();
  15546. Client cli("localhost", port);
  15547. cli.set_read_timeout(1, 0); // 1 second timeout
  15548. auto handle = cli.open_stream("GET", "/slow-stream");
  15549. ASSERT_TRUE(handle.is_valid());
  15550. char buf[256];
  15551. ssize_t total = 0;
  15552. ssize_t n;
  15553. bool got_error = false;
  15554. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15555. total += n;
  15556. }
  15557. if (n < 0) {
  15558. got_error = true;
  15559. // Should be timeout or read error
  15560. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15561. handle.get_read_error() == Error::Read)
  15562. << "Actual error: " << to_string(handle.get_read_error());
  15563. }
  15564. // Either we got an error, or we got less data than expected
  15565. EXPECT_TRUE(got_error || total < 1000)
  15566. << "Expected timeout but got all " << total << " bytes";
  15567. svr.stop();
  15568. t.join();
  15569. }
  15570. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  15571. // Test connection closed detection via BodyReader
  15572. Server svr;
  15573. std::atomic<bool> close_now{false};
  15574. svr.Get("/will-close", [&](const Request &, Response &res) {
  15575. res.set_content_provider(
  15576. 10000, // Large content_length that we won't fully send
  15577. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15578. if (offset < 100) {
  15579. std::string data(100, 'X');
  15580. sink.write(data.c_str(), data.size());
  15581. return true;
  15582. }
  15583. // Wait for signal then abort
  15584. while (!close_now) {
  15585. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15586. }
  15587. return false; // Abort - server will close connection
  15588. });
  15589. });
  15590. auto port = 8092;
  15591. std::thread t([&]() { svr.listen("localhost", port); });
  15592. svr.wait_until_ready();
  15593. Client cli("localhost", port);
  15594. auto handle = cli.open_stream("GET", "/will-close");
  15595. ASSERT_TRUE(handle.is_valid());
  15596. char buf[256];
  15597. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15598. EXPECT_GT(n, 0) << "First read should succeed";
  15599. // Signal server to close
  15600. close_now = true;
  15601. // Keep reading until error or EOF
  15602. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15603. // Keep reading
  15604. }
  15605. // Should get an error since content_length wasn't satisfied
  15606. if (n < 0) {
  15607. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15608. handle.get_read_error() == Error::Read)
  15609. << "Actual error: " << to_string(handle.get_read_error());
  15610. }
  15611. svr.stop();
  15612. t.join();
  15613. }
  15614. #ifdef CPPHTTPLIB_SSL_ENABLED
  15615. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  15616. // Test that read timeout during SSL streaming is detected
  15617. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15618. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15619. res.set_content_provider(
  15620. 1000, "text/plain",
  15621. [](size_t offset, size_t /*length*/, DataSink &sink) {
  15622. if (offset < 100) {
  15623. std::string data(100, 'A');
  15624. sink.write(data.c_str(), data.size());
  15625. return true;
  15626. }
  15627. std::this_thread::sleep_for(std::chrono::seconds(3));
  15628. std::string data(900, 'B');
  15629. sink.write(data.c_str(), data.size());
  15630. return true;
  15631. });
  15632. });
  15633. auto port = 8093;
  15634. std::thread t([&]() { svr.listen("localhost", port); });
  15635. svr.wait_until_ready();
  15636. SSLClient cli("localhost", port);
  15637. cli.enable_server_certificate_verification(false);
  15638. cli.set_read_timeout(1, 0); // 1 second timeout
  15639. auto handle = cli.open_stream("GET", "/slow-stream");
  15640. ASSERT_TRUE(handle.is_valid());
  15641. char buf[256];
  15642. ssize_t total = 0;
  15643. ssize_t n;
  15644. bool got_error = false;
  15645. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15646. total += n;
  15647. }
  15648. if (n < 0) {
  15649. got_error = true;
  15650. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15651. handle.get_read_error() == Error::Read)
  15652. << "Actual error: " << to_string(handle.get_read_error());
  15653. }
  15654. EXPECT_TRUE(got_error || total < 1000)
  15655. << "Expected timeout but got all " << total << " bytes";
  15656. svr.stop();
  15657. t.join();
  15658. }
  15659. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  15660. // Test SSL connection closed detection
  15661. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15662. std::atomic<bool> close_now{false};
  15663. svr.Get("/will-close", [&](const Request &, Response &res) {
  15664. res.set_content_provider(
  15665. 10000, "text/plain",
  15666. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15667. if (offset < 100) {
  15668. std::string data(100, 'X');
  15669. sink.write(data.c_str(), data.size());
  15670. return true;
  15671. }
  15672. while (!close_now) {
  15673. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15674. }
  15675. return false;
  15676. });
  15677. });
  15678. auto port = 8094;
  15679. std::thread t([&]() { svr.listen("localhost", port); });
  15680. svr.wait_until_ready();
  15681. SSLClient cli("localhost", port);
  15682. cli.enable_server_certificate_verification(false);
  15683. auto handle = cli.open_stream("GET", "/will-close");
  15684. ASSERT_TRUE(handle.is_valid());
  15685. char buf[256];
  15686. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15687. EXPECT_GT(n, 0);
  15688. // Signal server to close
  15689. close_now = true;
  15690. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15691. // Keep reading
  15692. }
  15693. if (n < 0) {
  15694. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15695. handle.get_read_error() == Error::Read)
  15696. << "Actual error: " << to_string(handle.get_read_error());
  15697. }
  15698. svr.stop();
  15699. t.join();
  15700. }
  15701. #endif
  15702. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  15703. using namespace httplib;
  15704. // Create a test file
  15705. const char *fname = "etag_testfile.txt";
  15706. const char *content = "etag-content";
  15707. {
  15708. std::ofstream ofs(fname);
  15709. ofs << content;
  15710. ASSERT_TRUE(ofs.good());
  15711. }
  15712. Server svr;
  15713. svr.set_mount_point("/static", ".");
  15714. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15715. svr.wait_until_ready();
  15716. Client cli(HOST, PORT);
  15717. // First request: should get 200 with ETag header
  15718. auto res1 = cli.Get("/static/etag_testfile.txt");
  15719. ASSERT_TRUE(res1);
  15720. ASSERT_EQ(200, res1->status);
  15721. ASSERT_TRUE(res1->has_header("ETag"));
  15722. std::string etag = res1->get_header_value("ETag");
  15723. EXPECT_FALSE(etag.empty());
  15724. // Verify ETag format: W/"hex-hex"
  15725. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  15726. EXPECT_EQ('W', etag[0]);
  15727. EXPECT_EQ('/', etag[1]);
  15728. EXPECT_EQ('"', etag[2]);
  15729. EXPECT_EQ('"', etag.back());
  15730. // Exact match: expect 304 Not Modified
  15731. Headers h2 = {{"If-None-Match", etag}};
  15732. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  15733. ASSERT_TRUE(res2);
  15734. EXPECT_EQ(304, res2->status);
  15735. // Wildcard match: expect 304 Not Modified
  15736. Headers h3 = {{"If-None-Match", "*"}};
  15737. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  15738. ASSERT_TRUE(res3);
  15739. EXPECT_EQ(304, res3->status);
  15740. // Non-matching ETag: expect 200
  15741. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  15742. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  15743. ASSERT_TRUE(res4);
  15744. EXPECT_EQ(200, res4->status);
  15745. // Multiple ETags with one matching: expect 304
  15746. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  15747. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  15748. ASSERT_TRUE(res5);
  15749. EXPECT_EQ(304, res5->status);
  15750. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  15751. // that equivalent to the single comma-separated list above, so the match on
  15752. // the second line must still be found.
  15753. Headers h6;
  15754. h6.emplace("If-None-Match", "W/\"other\"");
  15755. h6.emplace("If-None-Match", etag);
  15756. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  15757. ASSERT_TRUE(res6);
  15758. EXPECT_EQ(304, res6->status);
  15759. svr.stop();
  15760. t.join();
  15761. std::remove(fname);
  15762. }
  15763. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  15764. using namespace httplib;
  15765. Server svr;
  15766. svr.set_mount_point("/static", ".");
  15767. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15768. svr.wait_until_ready();
  15769. Client cli(HOST, PORT);
  15770. // Send If-None-Match: * to a non-existent file
  15771. Headers h = {{"If-None-Match", "*"}};
  15772. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  15773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15774. EXPECT_EQ(404, res->status);
  15775. svr.stop();
  15776. t.join();
  15777. }
  15778. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  15779. using namespace httplib;
  15780. // Create a test file
  15781. const char *fname = "etag_boundary_testfile.txt";
  15782. const char *content = "boundary-test";
  15783. {
  15784. std::ofstream ofs(fname);
  15785. ofs << content;
  15786. ASSERT_TRUE(ofs.good());
  15787. }
  15788. Server svr;
  15789. svr.set_mount_point("/static", ".");
  15790. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15791. svr.wait_until_ready();
  15792. Client cli(HOST, PORT);
  15793. // Get the actual ETag
  15794. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  15795. ASSERT_TRUE(res1);
  15796. ASSERT_EQ(200, res1->status);
  15797. ASSERT_TRUE(res1->has_header("ETag"));
  15798. std::string etag = res1->get_header_value("ETag");
  15799. // Test 1: Very long ETag value (longer than actual ETag)
  15800. // Should NOT match and return 200 (not trigger out-of-bounds read)
  15801. Headers h1 = {{"If-None-Match", "W/"
  15802. "\"very-long-etag-value-that-is-much-longer-"
  15803. "than-the-actual-etag-value\""}};
  15804. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  15805. ASSERT_TRUE(res2);
  15806. EXPECT_EQ(200, res2->status); // Should not match
  15807. // Test 2: Long string followed by wildcard
  15808. // Should match on "*" and return 304 (without out-of-bounds read on the long
  15809. // string)
  15810. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  15811. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  15812. ASSERT_TRUE(res3);
  15813. EXPECT_EQ(304, res3->status); // Should match on "*"
  15814. // Test 3: Wildcard followed by long string
  15815. // Should match on "*" immediately and return 304
  15816. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  15817. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  15818. ASSERT_TRUE(res4);
  15819. EXPECT_EQ(304, res4->status); // Should match on "*"
  15820. // Test 4: Multiple long non-matching values
  15821. // Should NOT match and return 200 (test that all comparisons are safe)
  15822. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  15823. "W/\"second-long-non-matching-value\", "
  15824. "W/\"third-long-non-matching-value\""}};
  15825. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  15826. ASSERT_TRUE(res5);
  15827. EXPECT_EQ(200, res5->status); // Should not match
  15828. // Test 5: Single character that is not "*" (edge case)
  15829. Headers h5 = {{"If-None-Match", "X"}};
  15830. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  15831. ASSERT_TRUE(res6);
  15832. EXPECT_EQ(200, res6->status); // Should not match
  15833. svr.stop();
  15834. t.join();
  15835. std::remove(fname);
  15836. }
  15837. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  15838. using namespace httplib;
  15839. // Create a test file
  15840. const char *fname = "ims_testfile.txt";
  15841. const char *content = "if-modified-since-test";
  15842. {
  15843. std::ofstream ofs(fname);
  15844. ofs << content;
  15845. ASSERT_TRUE(ofs.good());
  15846. }
  15847. Server svr;
  15848. svr.set_mount_point("/static", ".");
  15849. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15850. svr.wait_until_ready();
  15851. Client cli(HOST, PORT);
  15852. // First request: should get 200 with Last-Modified header
  15853. auto res1 = cli.Get("/static/ims_testfile.txt");
  15854. ASSERT_TRUE(res1);
  15855. ASSERT_EQ(200, res1->status);
  15856. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15857. std::string last_modified = res1->get_header_value("Last-Modified");
  15858. EXPECT_FALSE(last_modified.empty());
  15859. // If-Modified-Since with same time: expect 304
  15860. Headers h2 = {{"If-Modified-Since", last_modified}};
  15861. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  15862. ASSERT_TRUE(res2);
  15863. EXPECT_EQ(304, res2->status);
  15864. // If-Modified-Since with future time: expect 304
  15865. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15866. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  15867. ASSERT_TRUE(res3);
  15868. EXPECT_EQ(304, res3->status);
  15869. // If-Modified-Since with past time: expect 200
  15870. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15871. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  15872. ASSERT_TRUE(res4);
  15873. EXPECT_EQ(200, res4->status);
  15874. // If-None-Match takes precedence over If-Modified-Since
  15875. // (send matching ETag with old If-Modified-Since -> should still be 304)
  15876. ASSERT_TRUE(res1->has_header("ETag"));
  15877. std::string etag = res1->get_header_value("ETag");
  15878. Headers h5 = {{"If-None-Match", etag},
  15879. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15880. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  15881. ASSERT_TRUE(res5);
  15882. EXPECT_EQ(304, res5->status);
  15883. svr.stop();
  15884. t.join();
  15885. std::remove(fname);
  15886. }
  15887. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  15888. using namespace httplib;
  15889. Server svr;
  15890. // Endpoint that returns compressible content
  15891. svr.Get("/compressible", [](const Request &, Response &res) {
  15892. // Return a large enough body to trigger compression
  15893. std::string body(1000, 'a');
  15894. res.set_content(body, "text/plain");
  15895. });
  15896. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15897. svr.wait_until_ready();
  15898. Client cli(HOST, PORT);
  15899. // Request with gzip support: should get Vary header when compressed
  15900. cli.set_compress(true);
  15901. auto res1 = cli.Get("/compressible");
  15902. ASSERT_TRUE(res1);
  15903. EXPECT_EQ(200, res1->status);
  15904. // If Content-Encoding is set, Vary should also be set
  15905. if (res1->has_header("Content-Encoding")) {
  15906. EXPECT_TRUE(res1->has_header("Vary"));
  15907. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  15908. }
  15909. // Request without Accept-Encoding header: should not have compression
  15910. Headers h_no_compress;
  15911. auto res2 = cli.Get("/compressible", h_no_compress);
  15912. ASSERT_TRUE(res2);
  15913. EXPECT_EQ(200, res2->status);
  15914. // Verify Vary header is present when compression is applied
  15915. // (the exact behavior depends on server configuration)
  15916. svr.stop();
  15917. t.join();
  15918. }
  15919. TEST(ETagTest, IfRangeWithETag) {
  15920. using namespace httplib;
  15921. // Create a test file with known content
  15922. const char *fname = "if_range_testfile.txt";
  15923. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  15924. {
  15925. std::ofstream ofs(fname);
  15926. ofs << content;
  15927. ASSERT_TRUE(ofs.good());
  15928. }
  15929. Server svr;
  15930. svr.set_mount_point("/static", ".");
  15931. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15932. svr.wait_until_ready();
  15933. Client cli(HOST, PORT);
  15934. // First request: get ETag
  15935. auto res1 = cli.Get("/static/if_range_testfile.txt");
  15936. ASSERT_TRUE(res1);
  15937. ASSERT_EQ(200, res1->status);
  15938. ASSERT_TRUE(res1->has_header("ETag"));
  15939. std::string etag = res1->get_header_value("ETag");
  15940. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  15941. // Since our server generates weak ETags (W/"..."), If-Range with our
  15942. // ETag should NOT result in partial content - it should return full content.
  15943. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  15944. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  15945. ASSERT_TRUE(res2);
  15946. // Weak ETag in If-Range -> full content (200), not partial (206)
  15947. EXPECT_EQ(200, res2->status);
  15948. EXPECT_EQ(content, res2->body);
  15949. EXPECT_FALSE(res2->has_header("Content-Range"));
  15950. // Range request with non-matching If-Range (ETag): should get 200 (full
  15951. // content)
  15952. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  15953. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  15954. ASSERT_TRUE(res3);
  15955. EXPECT_EQ(200, res3->status);
  15956. EXPECT_EQ(content, res3->body);
  15957. EXPECT_FALSE(res3->has_header("Content-Range"));
  15958. // Range request with strong ETag (hypothetical - our server doesn't generate
  15959. // strong ETags, but if client sends a strong ETag that doesn't match, it
  15960. // should return full content)
  15961. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  15962. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  15963. ASSERT_TRUE(res4);
  15964. EXPECT_EQ(200, res4->status);
  15965. EXPECT_EQ(content, res4->body);
  15966. EXPECT_FALSE(res4->has_header("Content-Range"));
  15967. svr.stop();
  15968. t.join();
  15969. std::remove(fname);
  15970. }
  15971. TEST(ETagTest, IfRangeWithDate) {
  15972. using namespace httplib;
  15973. // Create a test file
  15974. const char *fname = "if_range_date_testfile.txt";
  15975. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  15976. {
  15977. std::ofstream ofs(fname);
  15978. ofs << content;
  15979. ASSERT_TRUE(ofs.good());
  15980. }
  15981. Server svr;
  15982. svr.set_mount_point("/static", ".");
  15983. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15984. svr.wait_until_ready();
  15985. Client cli(HOST, PORT);
  15986. // First request: get Last-Modified
  15987. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  15988. ASSERT_TRUE(res1);
  15989. ASSERT_EQ(200, res1->status);
  15990. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15991. std::string last_modified = res1->get_header_value("Last-Modified");
  15992. // Range request with matching If-Range (date): should get 206
  15993. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  15994. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  15995. ASSERT_TRUE(res2);
  15996. EXPECT_EQ(206, res2->status);
  15997. EXPECT_EQ("FGHIJ", res2->body);
  15998. // Range request with old If-Range date: should get 200 (full content)
  15999. Headers h3 = {{"Range", "bytes=5-9"},
  16000. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16001. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  16002. ASSERT_TRUE(res3);
  16003. EXPECT_EQ(200, res3->status);
  16004. EXPECT_EQ(content, res3->body);
  16005. // Range request with future If-Range date: should get 206
  16006. Headers h4 = {{"Range", "bytes=0-4"},
  16007. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16008. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  16009. ASSERT_TRUE(res4);
  16010. EXPECT_EQ(206, res4->status);
  16011. EXPECT_EQ("ABCDE", res4->body);
  16012. svr.stop();
  16013. t.join();
  16014. std::remove(fname);
  16015. }
  16016. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  16017. using namespace httplib;
  16018. const char *fname = "etag_malformed.txt";
  16019. const char *content = "malformed-etag";
  16020. {
  16021. std::ofstream ofs(fname);
  16022. ofs << content;
  16023. ASSERT_TRUE(ofs.good());
  16024. }
  16025. Server svr;
  16026. svr.set_mount_point("/static", ".");
  16027. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16028. svr.wait_until_ready();
  16029. Client cli(HOST, PORT);
  16030. // baseline: should get 200 and an ETag
  16031. auto res1 = cli.Get("/static/etag_malformed.txt");
  16032. ASSERT_TRUE(res1);
  16033. ASSERT_EQ(200, res1->status);
  16034. ASSERT_TRUE(res1->has_header("ETag"));
  16035. // Malformed ETag value (missing quotes) should be treated as non-matching
  16036. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  16037. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  16038. ASSERT_TRUE(res_bad);
  16039. EXPECT_EQ(200, res_bad->status);
  16040. // Whitespace-only header value should be considered invalid / non-matching
  16041. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  16042. "Host: localhost\r\n"
  16043. "If-None-Match: \r\n"
  16044. "Connection: close\r\n"
  16045. "\r\n";
  16046. std::string out;
  16047. ASSERT_TRUE(send_request(5, raw_req, &out));
  16048. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16049. svr.stop();
  16050. t.join();
  16051. std::remove(fname);
  16052. }
  16053. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  16054. using namespace httplib;
  16055. const char *fname = "ims_invalid_format.txt";
  16056. const char *content = "ims-bad-format";
  16057. {
  16058. std::ofstream ofs(fname);
  16059. ofs << content;
  16060. ASSERT_TRUE(ofs.good());
  16061. }
  16062. Server svr;
  16063. svr.set_mount_point("/static", ".");
  16064. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16065. svr.wait_until_ready();
  16066. Client cli(HOST, PORT);
  16067. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  16068. ASSERT_TRUE(res1);
  16069. ASSERT_EQ(200, res1->status);
  16070. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16071. // If-Modified-Since with invalid format should not result in 304
  16072. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  16073. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  16074. ASSERT_TRUE(res_bad);
  16075. EXPECT_EQ(200, res_bad->status);
  16076. // If-Range with invalid date format should be treated as mismatch -> full
  16077. // content (200)
  16078. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  16079. {"If-Range", "invalid-date"}};
  16080. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  16081. ASSERT_TRUE(res_ifrange);
  16082. EXPECT_EQ(200, res_ifrange->status);
  16083. svr.stop();
  16084. t.join();
  16085. std::remove(fname);
  16086. }
  16087. TEST(ETagTest, IfRangeWithMalformedETag) {
  16088. using namespace httplib;
  16089. const char *fname = "ifrange_malformed.txt";
  16090. const std::string content = "0123456789";
  16091. {
  16092. std::ofstream ofs(fname);
  16093. ofs << content;
  16094. ASSERT_TRUE(ofs.good());
  16095. }
  16096. Server svr;
  16097. svr.set_mount_point("/static", ".");
  16098. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16099. svr.wait_until_ready();
  16100. Client cli(HOST, PORT);
  16101. // First request: get ETag
  16102. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  16103. ASSERT_TRUE(res1);
  16104. ASSERT_EQ(200, res1->status);
  16105. ASSERT_TRUE(res1->has_header("ETag"));
  16106. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  16107. // full content (200)
  16108. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  16109. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  16110. ASSERT_TRUE(res2);
  16111. EXPECT_EQ(200, res2->status);
  16112. EXPECT_EQ(content, res2->body);
  16113. svr.stop();
  16114. t.join();
  16115. std::remove(fname);
  16116. }
  16117. TEST(ETagTest, ExtremeLargeDateValues) {
  16118. using namespace httplib;
  16119. const char *fname = "ims_extreme_date.txt";
  16120. const char *content = "ims-extreme-date";
  16121. {
  16122. std::ofstream ofs(fname);
  16123. ofs << content;
  16124. ASSERT_TRUE(ofs.good());
  16125. }
  16126. Server svr;
  16127. svr.set_mount_point("/static", ".");
  16128. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16129. svr.wait_until_ready();
  16130. Client cli(HOST, PORT);
  16131. auto res1 = cli.Get(std::string("/static/") + fname);
  16132. ASSERT_TRUE(res1);
  16133. ASSERT_EQ(200, res1->status);
  16134. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16135. // Extremely large year that may overflow date parsing routines.
  16136. Headers h_large_date = {
  16137. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16138. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  16139. ASSERT_TRUE(res_bad);
  16140. // Expect server to treat this as invalid/mismatch and return full content
  16141. EXPECT_EQ(200, res_bad->status);
  16142. // If-Range with extremely large date should be treated as mismatch -> full
  16143. // content (200)
  16144. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  16145. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16146. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  16147. ASSERT_TRUE(res_ifrange);
  16148. EXPECT_EQ(200, res_ifrange->status);
  16149. svr.stop();
  16150. t.join();
  16151. std::remove(fname);
  16152. }
  16153. TEST(ETagTest, NegativeFileModificationTime) {
  16154. using namespace httplib;
  16155. const char *fname = "ims_negative_mtime.txt";
  16156. const std::string content = "negative-mtime";
  16157. {
  16158. std::ofstream ofs(fname);
  16159. ofs << content;
  16160. ASSERT_TRUE(ofs.good());
  16161. }
  16162. // Try to set file mtime to a negative value. This may fail on some
  16163. // platforms/filesystems; if it fails, the test will still verify server
  16164. // behaves safely by performing a regular conditional request.
  16165. #if defined(__APPLE__) || defined(__linux__)
  16166. bool set_negative = false;
  16167. do {
  16168. struct timeval times[2];
  16169. // access time: now
  16170. times[0].tv_sec = time(nullptr);
  16171. times[0].tv_usec = 0;
  16172. // modification time: negative (e.g., -1)
  16173. times[1].tv_sec = -1;
  16174. times[1].tv_usec = 0;
  16175. if (utimes(fname, times) == 0) { set_negative = true; }
  16176. } while (0);
  16177. #else
  16178. bool set_negative = false;
  16179. #endif
  16180. Server svr;
  16181. svr.set_mount_point("/static", ".");
  16182. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16183. svr.wait_until_ready();
  16184. Client cli(HOST, PORT);
  16185. auto res1 = cli.Get(std::string("/static/") + fname);
  16186. ASSERT_TRUE(res1);
  16187. ASSERT_EQ(200, res1->status);
  16188. bool has_last_modified = res1->has_header("Last-Modified");
  16189. std::string last_modified;
  16190. if (has_last_modified) {
  16191. last_modified = res1->get_header_value("Last-Modified");
  16192. }
  16193. if (set_negative) {
  16194. // If we successfully set a negative mtime, ensure server returns a
  16195. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  16196. // with an old date and ensure server handles it without crash.
  16197. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  16198. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  16199. ASSERT_TRUE(res2);
  16200. // Behavior may vary; at minimum ensure server responds (200 or 304).
  16201. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  16202. } else {
  16203. // Could not set negative mtime on this platform; fall back to verifying
  16204. // that normal invalid/malformed dates are treated safely (non-304).
  16205. Headers h_bad_date = {
  16206. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16207. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  16208. ASSERT_TRUE(res_bad);
  16209. EXPECT_EQ(200, res_bad->status);
  16210. }
  16211. svr.stop();
  16212. t.join();
  16213. std::remove(fname);
  16214. }
  16215. //==============================================================================
  16216. // SSE Parsing Tests
  16217. //==============================================================================
  16218. class SSEParsingTest : public ::testing::Test {
  16219. protected:
  16220. // Test helper that mimics SSE parsing behavior
  16221. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  16222. int &retry_ms) {
  16223. // Blank line signals end of event
  16224. if (line.empty() || line == "\r") { return true; }
  16225. // Lines starting with ':' are comments (ignored)
  16226. if (!line.empty() && line[0] == ':') { return false; }
  16227. // Find the colon separator
  16228. auto colon_pos = line.find(':');
  16229. if (colon_pos == std::string::npos) {
  16230. // Line with no colon is treated as field name with empty value
  16231. return false;
  16232. }
  16233. std::string field = line.substr(0, colon_pos);
  16234. std::string value;
  16235. // Value starts after colon, skip optional single space
  16236. if (colon_pos + 1 < line.size()) {
  16237. size_t value_start = colon_pos + 1;
  16238. if (line[value_start] == ' ') { value_start++; }
  16239. value = line.substr(value_start);
  16240. // Remove trailing \r if present
  16241. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  16242. }
  16243. // Handle known fields
  16244. if (field == "event") {
  16245. msg.event = value;
  16246. } else if (field == "data") {
  16247. // Multiple data lines are concatenated with newlines
  16248. if (!msg.data.empty()) { msg.data += "\n"; }
  16249. msg.data += value;
  16250. } else if (field == "id") {
  16251. // Empty id is valid (clears the last event ID)
  16252. msg.id = value;
  16253. } else if (field == "retry") {
  16254. // Parse retry interval in milliseconds
  16255. {
  16256. int v = 0;
  16257. auto res =
  16258. detail::from_chars(value.data(), value.data() + value.size(), v);
  16259. if (res.ec == std::errc{}) { retry_ms = v; }
  16260. }
  16261. }
  16262. // Unknown fields are ignored per SSE spec
  16263. return false;
  16264. }
  16265. };
  16266. // Test: Single-line data
  16267. TEST_F(SSEParsingTest, SingleLineData) {
  16268. sse::SSEMessage msg;
  16269. int retry_ms = 3000;
  16270. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  16271. EXPECT_EQ(msg.data, "hello");
  16272. EXPECT_EQ(msg.event, "message");
  16273. // Blank line ends event
  16274. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16275. }
  16276. // Test: Multi-line data
  16277. TEST_F(SSEParsingTest, MultiLineData) {
  16278. sse::SSEMessage msg;
  16279. int retry_ms = 3000;
  16280. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  16281. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  16282. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  16283. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  16284. }
  16285. // Test: Custom event types
  16286. TEST_F(SSEParsingTest, CustomEventType) {
  16287. sse::SSEMessage msg;
  16288. int retry_ms = 3000;
  16289. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  16290. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  16291. EXPECT_EQ(msg.event, "update");
  16292. EXPECT_EQ(msg.data, "payload");
  16293. }
  16294. // Test: Event ID handling
  16295. TEST_F(SSEParsingTest, EventIdHandling) {
  16296. sse::SSEMessage msg;
  16297. int retry_ms = 3000;
  16298. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  16299. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  16300. EXPECT_EQ(msg.id, "12345");
  16301. }
  16302. // Test: Empty event ID (clears last event ID)
  16303. TEST_F(SSEParsingTest, EmptyEventId) {
  16304. sse::SSEMessage msg;
  16305. msg.id = "previous";
  16306. int retry_ms = 3000;
  16307. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  16308. EXPECT_EQ(msg.id, "");
  16309. }
  16310. // Test: Retry field parsing
  16311. TEST_F(SSEParsingTest, RetryFieldParsing) {
  16312. sse::SSEMessage msg;
  16313. int retry_ms = 3000;
  16314. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  16315. EXPECT_EQ(retry_ms, 5000);
  16316. }
  16317. // Test: Invalid retry value
  16318. TEST_F(SSEParsingTest, InvalidRetryValue) {
  16319. sse::SSEMessage msg;
  16320. int retry_ms = 3000;
  16321. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  16322. EXPECT_EQ(retry_ms, 3000); // Unchanged
  16323. }
  16324. // Test: Comments (lines starting with :)
  16325. TEST_F(SSEParsingTest, CommentsIgnored) {
  16326. sse::SSEMessage msg;
  16327. int retry_ms = 3000;
  16328. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  16329. EXPECT_EQ(msg.data, "");
  16330. EXPECT_EQ(msg.event, "message");
  16331. }
  16332. // Test: Colon in value
  16333. TEST_F(SSEParsingTest, ColonInValue) {
  16334. sse::SSEMessage msg;
  16335. int retry_ms = 3000;
  16336. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  16337. EXPECT_EQ(msg.data, "hello:world:test");
  16338. }
  16339. // Test: Line with no colon (field name only)
  16340. TEST_F(SSEParsingTest, FieldNameOnly) {
  16341. sse::SSEMessage msg;
  16342. int retry_ms = 3000;
  16343. // According to SSE spec, this is treated as field name with empty value
  16344. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  16345. // Since we don't recognize "data" without colon, data should be empty
  16346. EXPECT_EQ(msg.data, "");
  16347. }
  16348. // Test: Trailing \r handling
  16349. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  16350. sse::SSEMessage msg;
  16351. int retry_ms = 3000;
  16352. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  16353. EXPECT_EQ(msg.data, "hello");
  16354. }
  16355. // Test: Unknown fields ignored
  16356. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  16357. sse::SSEMessage msg;
  16358. int retry_ms = 3000;
  16359. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  16360. EXPECT_EQ(msg.data, "");
  16361. EXPECT_EQ(msg.event, "message");
  16362. }
  16363. // Test: Space after colon is optional
  16364. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  16365. sse::SSEMessage msg1, msg2;
  16366. int retry_ms = 3000;
  16367. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  16368. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  16369. EXPECT_EQ(msg1.data, "hello");
  16370. EXPECT_EQ(msg2.data, "hello");
  16371. }
  16372. // Test: SSEMessage clear
  16373. TEST_F(SSEParsingTest, MessageClear) {
  16374. sse::SSEMessage msg;
  16375. msg.event = "custom";
  16376. msg.data = "some data";
  16377. msg.id = "123";
  16378. msg.clear();
  16379. EXPECT_EQ(msg.event, "message");
  16380. EXPECT_EQ(msg.data, "");
  16381. EXPECT_EQ(msg.id, "");
  16382. }
  16383. // Test: Complete event parsing
  16384. TEST_F(SSEParsingTest, CompleteEventParsing) {
  16385. sse::SSEMessage msg;
  16386. int retry_ms = 3000;
  16387. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  16388. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  16389. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  16390. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  16391. // Blank line ends event
  16392. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16393. EXPECT_EQ(msg.event, "notification");
  16394. EXPECT_EQ(msg.id, "evt-42");
  16395. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  16396. EXPECT_EQ(retry_ms, 1000);
  16397. }
  16398. //==============================================================================
  16399. // Integration Tests with Server
  16400. //==============================================================================
  16401. class SSEIntegrationTest : public ::testing::Test {
  16402. protected:
  16403. void SetUp() override {
  16404. stop_server_.store(false);
  16405. events_.clear();
  16406. server_ = httplib::detail::make_unique<Server>();
  16407. setup_server();
  16408. start_server();
  16409. }
  16410. void TearDown() override {
  16411. stop_server_.store(true);
  16412. event_cv_.notify_all();
  16413. server_->stop();
  16414. if (server_thread_.joinable()) { server_thread_.join(); }
  16415. }
  16416. void setup_server() {
  16417. // Simple SSE endpoint
  16418. server_->Get("/events", [this](const Request &req, Response &res) {
  16419. auto last_id = req.get_header_value("Last-Event-ID");
  16420. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  16421. res.set_chunked_content_provider(
  16422. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  16423. std::unique_lock<std::mutex> lock(event_mutex_);
  16424. if (event_cv_.wait_for(
  16425. lock, std::chrono::milliseconds(200), [this] {
  16426. return !events_.empty() || stop_server_.load();
  16427. })) {
  16428. if (stop_server_.load()) { return false; }
  16429. if (!events_.empty()) {
  16430. std::string event = events_.front();
  16431. events_.erase(events_.begin());
  16432. sink.write(event.data(), event.size());
  16433. return true;
  16434. }
  16435. }
  16436. return !stop_server_.load();
  16437. });
  16438. });
  16439. // Endpoint that returns error
  16440. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  16441. res.status = 500;
  16442. res.set_content("Internal Server Error", "text/plain");
  16443. });
  16444. // Endpoint for custom event types
  16445. server_->Get("/custom-events", [](const Request &, Response &res) {
  16446. res.set_chunked_content_provider(
  16447. "text/event-stream", [](size_t offset, DataSink &sink) {
  16448. if (offset == 0) {
  16449. std::string event = "event: update\ndata: updated\n\n"
  16450. "event: delete\ndata: deleted\n\n";
  16451. sink.write(event.data(), event.size());
  16452. }
  16453. return false; // End stream after sending
  16454. });
  16455. });
  16456. }
  16457. void start_server() {
  16458. port_ = server_->bind_to_any_port(HOST);
  16459. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16460. // Wait for server to start
  16461. while (!server_->is_running()) {
  16462. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16463. }
  16464. }
  16465. int get_port() const { return port_; }
  16466. void send_event(const std::string &event) {
  16467. std::lock_guard<std::mutex> lock(event_mutex_);
  16468. events_.push_back(event);
  16469. event_cv_.notify_all();
  16470. }
  16471. std::unique_ptr<Server> server_;
  16472. std::thread server_thread_;
  16473. std::mutex event_mutex_;
  16474. std::condition_variable event_cv_;
  16475. std::vector<std::string> events_;
  16476. std::atomic<bool> stop_server_{false};
  16477. std::string last_received_event_id_;
  16478. int port_ = 0;
  16479. };
  16480. // Test: Successful connection and on_open callback
  16481. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  16482. // Add a simple endpoint that sends one event and closes
  16483. server_->Get("/simple-event", [](const Request &, Response &res) {
  16484. res.set_chunked_content_provider(
  16485. "text/event-stream", [](size_t offset, DataSink &sink) {
  16486. if (offset == 0) {
  16487. std::string event = "data: hello\n\n";
  16488. sink.write(event.data(), event.size());
  16489. }
  16490. return false; // Close stream after sending
  16491. });
  16492. });
  16493. Client client("localhost", get_port());
  16494. sse::SSEClient sse(client, "/simple-event");
  16495. std::atomic<bool> open_called{false};
  16496. std::atomic<bool> message_received{false};
  16497. sse.on_open([&open_called]() { open_called.store(true); });
  16498. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  16499. if (msg.data == "hello") { message_received.store(true); }
  16500. });
  16501. sse.set_reconnect_interval(100);
  16502. sse.set_max_reconnect_attempts(1);
  16503. // Start async
  16504. sse.start_async();
  16505. // Wait for message to be processed
  16506. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16507. sse.stop();
  16508. EXPECT_TRUE(open_called.load());
  16509. EXPECT_TRUE(message_received.load());
  16510. }
  16511. // Test: on_message callback
  16512. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  16513. // Endpoint that sends multiple events then closes
  16514. server_->Get("/multi-event", [](const Request &, Response &res) {
  16515. res.set_chunked_content_provider(
  16516. "text/event-stream", [](size_t offset, DataSink &sink) {
  16517. if (offset == 0) {
  16518. std::string events = "data: message1\n\ndata: message2\n\n";
  16519. sink.write(events.data(), events.size());
  16520. }
  16521. return false;
  16522. });
  16523. });
  16524. Client client("localhost", get_port());
  16525. sse::SSEClient sse(client, "/multi-event");
  16526. std::vector<std::string> received_messages;
  16527. std::mutex messages_mutex;
  16528. sse.on_message([&](const sse::SSEMessage &msg) {
  16529. std::lock_guard<std::mutex> lock(messages_mutex);
  16530. received_messages.push_back(msg.data);
  16531. });
  16532. sse.set_reconnect_interval(100);
  16533. sse.set_max_reconnect_attempts(1);
  16534. sse.start_async();
  16535. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16536. sse.stop();
  16537. std::lock_guard<std::mutex> lock(messages_mutex);
  16538. EXPECT_GE(received_messages.size(), 2u);
  16539. if (received_messages.size() >= 2) {
  16540. EXPECT_EQ(received_messages[0], "message1");
  16541. EXPECT_EQ(received_messages[1], "message2");
  16542. }
  16543. }
  16544. // Test: on_event for specific types
  16545. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  16546. Client client("localhost", get_port());
  16547. sse::SSEClient sse(client, "/custom-events");
  16548. std::atomic<bool> update_received{false};
  16549. std::atomic<bool> delete_received{false};
  16550. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  16551. if (msg.data == "updated") { update_received.store(true); }
  16552. });
  16553. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  16554. if (msg.data == "deleted") { delete_received.store(true); }
  16555. });
  16556. sse.set_max_reconnect_attempts(1);
  16557. sse.start_async();
  16558. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  16559. sse.stop();
  16560. EXPECT_TRUE(update_received.load());
  16561. EXPECT_TRUE(delete_received.load());
  16562. }
  16563. // Test: on_error callback on connection failure
  16564. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  16565. // Connect to a non-existent port
  16566. Client client("localhost", 59999);
  16567. sse::SSEClient sse(client, "/events");
  16568. std::atomic<bool> error_called{false};
  16569. Error received_error = Error::Success;
  16570. sse.on_error([&](Error err) {
  16571. error_called.store(true);
  16572. received_error = err;
  16573. });
  16574. sse.set_reconnect_interval(50);
  16575. sse.set_max_reconnect_attempts(1);
  16576. sse.start_async();
  16577. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16578. sse.stop();
  16579. EXPECT_TRUE(error_called.load());
  16580. EXPECT_NE(received_error, Error::Success);
  16581. }
  16582. // Test: Last-Event-ID header sent on reconnect
  16583. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  16584. // Endpoint that sends event with ID
  16585. server_->Get("/event-with-id", [](const Request &, Response &res) {
  16586. res.set_chunked_content_provider(
  16587. "text/event-stream", [](size_t offset, DataSink &sink) {
  16588. if (offset == 0) {
  16589. std::string event = "id: evt-123\ndata: test\n\n";
  16590. sink.write(event.data(), event.size());
  16591. }
  16592. return false;
  16593. });
  16594. });
  16595. Client client("localhost", get_port());
  16596. sse::SSEClient sse(client, "/event-with-id");
  16597. std::atomic<bool> id_received{false};
  16598. sse.on_message([&](const sse::SSEMessage &msg) {
  16599. if (!msg.id.empty()) { id_received.store(true); }
  16600. });
  16601. sse.set_reconnect_interval(100);
  16602. sse.set_max_reconnect_attempts(1);
  16603. sse.start_async();
  16604. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16605. sse.stop();
  16606. EXPECT_TRUE(id_received.load());
  16607. EXPECT_EQ(sse.last_event_id(), "evt-123");
  16608. }
  16609. // Test: Manual stop
  16610. TEST_F(SSEIntegrationTest, ManualStop) {
  16611. // Endpoint that sends one event and stays open briefly
  16612. std::atomic<bool> handler_running{true};
  16613. server_->Get("/stay-open", [&handler_running](const Request &,
  16614. Response &res) {
  16615. res.set_chunked_content_provider(
  16616. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  16617. if (offset == 0) {
  16618. std::string event = "data: connected\n\n";
  16619. sink.write(event.data(), event.size());
  16620. }
  16621. // Keep connection open while handler_running is true
  16622. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  16623. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16624. }
  16625. return false;
  16626. });
  16627. });
  16628. Client client("localhost", get_port());
  16629. sse::SSEClient sse(client, "/stay-open");
  16630. std::atomic<bool> connected{false};
  16631. sse.on_open([&connected]() { connected.store(true); });
  16632. sse.set_reconnect_interval(100);
  16633. sse.set_max_reconnect_attempts(1);
  16634. sse.start_async();
  16635. // Wait for connection to establish
  16636. for (int i = 0; i < 20 && !connected.load(); ++i) {
  16637. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16638. }
  16639. EXPECT_TRUE(connected.load());
  16640. EXPECT_TRUE(sse.is_connected());
  16641. // Signal handler to stop
  16642. handler_running.store(false);
  16643. // Stop SSE client
  16644. sse.stop();
  16645. EXPECT_FALSE(sse.is_connected());
  16646. }
  16647. // Test: SSEClient with custom headers
  16648. TEST_F(SSEIntegrationTest, CustomHeaders) {
  16649. // Setup a server endpoint that checks for custom header
  16650. std::atomic<bool> header_received{false};
  16651. server_->Get("/header-check", [&](const Request &req, Response &res) {
  16652. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  16653. header_received.store(true);
  16654. }
  16655. res.set_chunked_content_provider("text/event-stream",
  16656. [](size_t, DataSink &) { return false; });
  16657. });
  16658. Client client("localhost", get_port());
  16659. Headers headers = {{"X-Custom-Header", "custom-value"}};
  16660. sse::SSEClient sse(client, "/header-check", headers);
  16661. sse.set_max_reconnect_attempts(1);
  16662. sse.start_async();
  16663. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16664. sse.stop();
  16665. EXPECT_TRUE(header_received.load());
  16666. }
  16667. // Test: Reconnect interval configuration
  16668. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  16669. Client client("localhost", get_port());
  16670. sse::SSEClient sse(client, "/events");
  16671. auto &result = sse.set_reconnect_interval(500);
  16672. // Builder pattern should return reference to self
  16673. EXPECT_EQ(&result, &sse);
  16674. }
  16675. // Test: Max reconnect attempts
  16676. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  16677. // Connect to non-existent port to force reconnects
  16678. Client client("localhost", 59998);
  16679. sse::SSEClient sse(client, "/events");
  16680. std::atomic<int> error_count{0};
  16681. sse.on_error([&](Error) { error_count.fetch_add(1); });
  16682. sse.set_reconnect_interval(50);
  16683. sse.set_max_reconnect_attempts(2);
  16684. auto start = std::chrono::steady_clock::now();
  16685. sse.start(); // Blocking call
  16686. auto end = std::chrono::steady_clock::now();
  16687. // Should have stopped after 2 failed attempts
  16688. EXPECT_GE(error_count.load(), 2);
  16689. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  16690. auto duration =
  16691. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  16692. #ifdef _WIN32
  16693. // Windows is much slower for socket connection failures
  16694. EXPECT_LT(duration.count(), 7000);
  16695. #else
  16696. EXPECT_LT(duration.count(), 1000);
  16697. #endif
  16698. }
  16699. // Test: Multi-line data in integration
  16700. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  16701. // Endpoint with multi-line data
  16702. server_->Get("/multiline-data", [](const Request &, Response &res) {
  16703. res.set_chunked_content_provider(
  16704. "text/event-stream", [](size_t offset, DataSink &sink) {
  16705. if (offset == 0) {
  16706. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  16707. sink.write(event.data(), event.size());
  16708. }
  16709. return false;
  16710. });
  16711. });
  16712. Client client("localhost", get_port());
  16713. sse::SSEClient sse(client, "/multiline-data");
  16714. std::string received_data;
  16715. std::mutex data_mutex;
  16716. sse.on_message([&](const sse::SSEMessage &msg) {
  16717. std::lock_guard<std::mutex> lock(data_mutex);
  16718. received_data = msg.data;
  16719. });
  16720. sse.set_reconnect_interval(100);
  16721. sse.set_max_reconnect_attempts(1);
  16722. sse.start_async();
  16723. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16724. sse.stop();
  16725. std::lock_guard<std::mutex> lock(data_mutex);
  16726. EXPECT_EQ(received_data, "line1\nline2\nline3");
  16727. }
  16728. // Test: Auto-reconnect after server disconnection
  16729. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  16730. std::atomic<int> connection_count{0};
  16731. std::atomic<int> message_count{0};
  16732. // Endpoint that sends one event and closes, forcing reconnect
  16733. server_->Get("/reconnect-test",
  16734. [&connection_count](const Request &, Response &res) {
  16735. connection_count.fetch_add(1);
  16736. res.set_chunked_content_provider(
  16737. "text/event-stream", [](size_t offset, DataSink &sink) {
  16738. if (offset == 0) {
  16739. std::string event = "data: hello\n\n";
  16740. sink.write(event.data(), event.size());
  16741. }
  16742. return false; // Close connection after sending
  16743. });
  16744. });
  16745. Client client("localhost", get_port());
  16746. sse::SSEClient sse(client, "/reconnect-test");
  16747. sse.on_message([&message_count](const sse::SSEMessage &) {
  16748. message_count.fetch_add(1);
  16749. });
  16750. sse.set_reconnect_interval(100);
  16751. sse.set_max_reconnect_attempts(3);
  16752. sse.start_async();
  16753. // Wait long enough for multiple reconnects
  16754. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16755. sse.stop();
  16756. // Should have connected multiple times (initial + reconnects)
  16757. EXPECT_GE(connection_count.load(), 2);
  16758. // Should have received messages from multiple connections
  16759. EXPECT_GE(message_count.load(), 2);
  16760. }
  16761. // Test: Last-Event-ID sent on reconnect
  16762. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  16763. std::atomic<int> connection_count{0};
  16764. std::vector<std::string> received_last_event_ids;
  16765. std::mutex id_mutex;
  16766. // Endpoint that checks Last-Event-ID header and sends event with ID
  16767. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  16768. int conn = connection_count.fetch_add(1);
  16769. // Capture the Last-Event-ID header from each connection
  16770. {
  16771. std::lock_guard<std::mutex> lock(id_mutex);
  16772. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  16773. }
  16774. res.set_chunked_content_provider(
  16775. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  16776. if (offset == 0) {
  16777. std::string event =
  16778. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  16779. sink.write(event.data(), event.size());
  16780. }
  16781. return false;
  16782. });
  16783. });
  16784. Client client("localhost", get_port());
  16785. sse::SSEClient sse(client, "/reconnect-with-id");
  16786. sse.set_reconnect_interval(100);
  16787. sse.set_max_reconnect_attempts(3);
  16788. sse.start_async();
  16789. // Wait for at least 2 connections
  16790. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16791. sse.stop();
  16792. // Verify behavior
  16793. std::lock_guard<std::mutex> lock(id_mutex);
  16794. EXPECT_GE(received_last_event_ids.size(), 2u);
  16795. // First connection should have no Last-Event-ID
  16796. if (!received_last_event_ids.empty()) {
  16797. EXPECT_EQ(received_last_event_ids[0], "");
  16798. }
  16799. // Second connection should have Last-Event-ID from first connection
  16800. if (received_last_event_ids.size() >= 2) {
  16801. EXPECT_EQ(received_last_event_ids[1], "event-0");
  16802. }
  16803. }
  16804. // Test: set_headers updates headers used on reconnect
  16805. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  16806. std::vector<std::string> received_tokens;
  16807. std::mutex token_mutex;
  16808. // Endpoint that captures Authorization header
  16809. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  16810. {
  16811. std::lock_guard<std::mutex> lock(token_mutex);
  16812. received_tokens.push_back(req.get_header_value("Authorization"));
  16813. }
  16814. res.set_chunked_content_provider(
  16815. "text/event-stream", [](size_t offset, DataSink &sink) {
  16816. if (offset == 0) {
  16817. std::string event = "data: hello\n\n";
  16818. sink.write(event.data(), event.size());
  16819. }
  16820. return false; // Close connection to trigger reconnect
  16821. });
  16822. });
  16823. Client client("localhost", get_port());
  16824. Headers headers = {{"Authorization", "Bearer old-token"}};
  16825. sse::SSEClient sse(client, "/auth-check", headers);
  16826. // Update headers on each successful connection
  16827. sse.on_open(
  16828. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  16829. sse.set_reconnect_interval(100);
  16830. sse.set_max_reconnect_attempts(3);
  16831. sse.start_async();
  16832. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16833. sse.stop();
  16834. std::lock_guard<std::mutex> lock(token_mutex);
  16835. ASSERT_GE(received_tokens.size(), 2u);
  16836. // First connection uses original header
  16837. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  16838. // Second connection uses updated header from set_headers
  16839. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  16840. }
  16841. // Test: 401 allows reconnection (so on_error can refresh headers)
  16842. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  16843. std::atomic<int> connection_count{0};
  16844. // Endpoint: returns 401 on first attempt, 200 on second
  16845. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  16846. int conn = connection_count.fetch_add(1);
  16847. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  16848. res.status = StatusCode::Unauthorized_401;
  16849. res.set_content("Unauthorized", "text/plain");
  16850. return;
  16851. }
  16852. res.set_chunked_content_provider(
  16853. "text/event-stream", [](size_t offset, DataSink &sink) {
  16854. if (offset == 0) {
  16855. std::string event = "data: authenticated\n\n";
  16856. sink.write(event.data(), event.size());
  16857. }
  16858. return false;
  16859. });
  16860. });
  16861. Client client("localhost", get_port());
  16862. Headers headers = {{"Authorization", "Bearer expired"}};
  16863. sse::SSEClient sse(client, "/auth-retry", headers);
  16864. std::atomic<bool> message_received{false};
  16865. // Refresh token on error
  16866. sse.on_error(
  16867. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  16868. sse.on_message([&](const sse::SSEMessage &msg) {
  16869. if (msg.data == "authenticated") { message_received.store(true); }
  16870. });
  16871. sse.set_reconnect_interval(100);
  16872. sse.set_max_reconnect_attempts(3);
  16873. sse.start_async();
  16874. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16875. sse.stop();
  16876. // Should have reconnected after 401 and succeeded with new token
  16877. EXPECT_GE(connection_count.load(), 2);
  16878. EXPECT_TRUE(message_received.load());
  16879. }
  16880. TEST(Issue2318Test, EmptyHostString) {
  16881. {
  16882. httplib::Client cli_empty("", PORT);
  16883. auto res = cli_empty.Get("/");
  16884. ASSERT_FALSE(res);
  16885. EXPECT_EQ(httplib::Error::Connection, res.error());
  16886. }
  16887. {
  16888. httplib::Client cli(" ", PORT);
  16889. auto res = cli.Get("/");
  16890. ASSERT_FALSE(res);
  16891. EXPECT_EQ(httplib::Error::Connection, res.error());
  16892. }
  16893. }
  16894. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16895. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  16896. Server svr;
  16897. // Set a small payload limit (1KB)
  16898. svr.set_payload_max_length(1024);
  16899. svr.Post("/test", [&](const Request &req, Response &res) {
  16900. res.set_content("Body size: " + std::to_string(req.body.size()),
  16901. "text/plain");
  16902. });
  16903. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16904. auto se = detail::scope_exit([&] {
  16905. svr.stop();
  16906. listen_thread.join();
  16907. });
  16908. svr.wait_until_ready();
  16909. // Create data that compresses well but exceeds limit when decompressed
  16910. // 8KB of repeated null bytes compresses to a very small size
  16911. std::string original_data(8 * 1024, '\0');
  16912. // Compress the data using gzip
  16913. std::string compressed_data;
  16914. detail::gzip_compressor compressor;
  16915. compressor.compress(original_data.data(), original_data.size(), true,
  16916. [&](const char *data, size_t size) {
  16917. compressed_data.append(data, size);
  16918. return true;
  16919. });
  16920. // Verify compression worked (compressed should be much smaller)
  16921. ASSERT_LT(compressed_data.size(), original_data.size());
  16922. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  16923. // Send compressed data with Content-Encoding: gzip
  16924. Client cli(HOST, PORT);
  16925. Headers headers = {{"Content-Encoding", "gzip"}};
  16926. auto res =
  16927. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  16928. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  16929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16930. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  16931. }
  16932. #endif
  16933. // ============================================================================
  16934. // OpenSSL-Specific Tests
  16935. // ============================================================================
  16936. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16937. X509 *readCertificate(const std::string &strFileName) {
  16938. std::ifstream inStream(strFileName);
  16939. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  16940. std::istreambuf_iterator<char>());
  16941. if (strCertPEM.empty()) return (nullptr);
  16942. BIO *pbCert = BIO_new(BIO_s_mem());
  16943. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  16944. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  16945. BIO_free(pbCert);
  16946. return (pCert);
  16947. }
  16948. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  16949. std::ifstream inStream(strFileName);
  16950. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  16951. std::istreambuf_iterator<char>());
  16952. if (strPrivateKeyPEM.empty()) return (nullptr);
  16953. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  16954. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  16955. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  16956. BIO_free(pbPrivKey);
  16957. return (pPrivateKey);
  16958. }
  16959. TEST(BindServerTest, UpdateCerts) {
  16960. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16961. int port = svr.bind_to_any_port("0.0.0.0");
  16962. ASSERT_TRUE(svr.is_valid());
  16963. ASSERT_TRUE(port > 0);
  16964. X509 *cert = readCertificate(SERVER_CERT_FILE);
  16965. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  16966. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  16967. ASSERT_TRUE(cert != nullptr);
  16968. ASSERT_TRUE(ca_cert != nullptr);
  16969. ASSERT_TRUE(key != nullptr);
  16970. X509_STORE *cert_store = X509_STORE_new();
  16971. X509_STORE_add_cert(cert_store, ca_cert);
  16972. // svr.update_certs(cert, key, cert_store); // deprecated
  16973. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  16974. CLIENT_CA_CERT_FILE);
  16975. ASSERT_TRUE(svr.is_valid());
  16976. svr.stop();
  16977. X509_STORE_free(cert_store);
  16978. X509_free(cert);
  16979. X509_free(ca_cert);
  16980. EVP_PKEY_free(key);
  16981. }
  16982. // Test that update_certs() updates client CA list correctly
  16983. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  16984. // Start with file-based constructor
  16985. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16986. ASSERT_TRUE(svr.is_valid());
  16987. // Initially no client CA list should be set
  16988. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16989. ASSERT_TRUE(ssl_ctx != nullptr);
  16990. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  16991. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  16992. EXPECT_EQ(0, count_before);
  16993. // Now update with client CA (PEM string)
  16994. std::string cert_pem, key_pem, ca_pem;
  16995. read_file(SERVER_CERT_FILE, cert_pem);
  16996. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  16997. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  16998. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  16999. ASSERT_TRUE(svr.is_valid());
  17000. // Now client CA list should be set
  17001. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  17002. ASSERT_TRUE(ca_list_after != nullptr);
  17003. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  17004. }
  17005. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  17006. // Test that the file-path SSLServer constructor properly sets the client CA
  17007. // list that is sent to clients during the TLS handshake (CertificateRequest)
  17008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17009. ASSERT_TRUE(svr.is_valid());
  17010. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17011. ASSERT_TRUE(ssl_ctx != nullptr);
  17012. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  17013. ASSERT_TRUE(ca_list != nullptr);
  17014. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  17015. }
  17016. #endif
  17017. // ============================================================================
  17018. // MbedTLS-Specific Tests
  17019. // ============================================================================
  17020. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  17021. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  17022. using namespace httplib::tls;
  17023. // Track if callback was invoked
  17024. bool callback_invoked = false;
  17025. // The callback receives void* ctx which is actually MbedTlsContext*
  17026. // We can access the mbedtls_ssl_config via the context
  17027. auto setup_callback = [&callback_invoked](void *ctx) {
  17028. callback_invoked = true;
  17029. // Cast to MbedTlsContext* to access the ssl config
  17030. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  17031. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  17032. // Use static variables to hold certificate data (simplified for test)
  17033. static mbedtls_x509_crt own_cert;
  17034. static mbedtls_pk_context own_key;
  17035. static mbedtls_x509_crt ca_chain;
  17036. static bool initialized = false;
  17037. if (!initialized) {
  17038. mbedtls_x509_crt_init(&own_cert);
  17039. mbedtls_pk_init(&own_key);
  17040. mbedtls_x509_crt_init(&ca_chain);
  17041. // Load server certificate
  17042. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  17043. return false;
  17044. }
  17045. // Load server private key.
  17046. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  17047. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  17048. #if MBEDTLS_VERSION_MAJOR == 3
  17049. ,
  17050. mbedtls_ctr_drbg_random, nullptr
  17051. #endif
  17052. ) != 0) {
  17053. return false;
  17054. }
  17055. // Load CA chain for client verification
  17056. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  17057. return false;
  17058. }
  17059. initialized = true;
  17060. }
  17061. // Configure the SSL config
  17062. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  17063. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  17064. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17065. // Set minimum TLS version using mbedTLS native API
  17066. #if MBEDTLS_VERSION_MAJOR >= 3
  17067. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17068. #else
  17069. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17070. MBEDTLS_SSL_MINOR_VERSION_3);
  17071. #endif
  17072. return true;
  17073. };
  17074. SSLServer svr(setup_callback);
  17075. ASSERT_TRUE(svr.is_valid());
  17076. ASSERT_TRUE(callback_invoked);
  17077. svr.Get("/test", [&](const Request &req, Response &res) {
  17078. res.set_content("test", "text/plain");
  17079. auto cert = req.peer_cert();
  17080. ASSERT_TRUE(static_cast<bool>(cert));
  17081. auto common_name = cert.subject_cn();
  17082. EXPECT_EQ("Common Name", common_name);
  17083. });
  17084. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17085. auto se = detail::scope_exit([&] {
  17086. svr.stop();
  17087. t.join();
  17088. ASSERT_FALSE(svr.is_running());
  17089. });
  17090. svr.wait_until_ready();
  17091. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  17092. cli.enable_server_certificate_verification(false);
  17093. cli.set_connection_timeout(30);
  17094. auto res = cli.Get("/test");
  17095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17096. ASSERT_EQ(StatusCode::OK_200, res->status);
  17097. }
  17098. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  17099. // context (owning mbedtls_ssl_config) before shutting down a still-open
  17100. // keep-alive SSL session, which reads through that config in
  17101. // mbedtls_ssl_close_notify.
  17102. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  17103. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17104. ASSERT_TRUE(svr.is_valid());
  17105. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17106. res.set_content("test", "text/plain");
  17107. });
  17108. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17109. auto se = detail::scope_exit([&] {
  17110. svr.stop();
  17111. t.join();
  17112. ASSERT_FALSE(svr.is_running());
  17113. });
  17114. svr.wait_until_ready();
  17115. {
  17116. SSLClient cli(HOST, PORT);
  17117. cli.enable_server_certificate_verification(false);
  17118. cli.set_keep_alive(true);
  17119. auto res = cli.Get("/test");
  17120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17121. ASSERT_EQ(StatusCode::OK_200, res->status);
  17122. // cli is destructed here with the keep-alive SSL session still open.
  17123. }
  17124. }
  17125. #endif
  17126. // WebSocket Tests
  17127. TEST(WebSocketTest, RSVBitsMustBeZero) {
  17128. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  17129. // defining the meaning of these bits has been negotiated.
  17130. auto make_frame = [](uint8_t first_byte) {
  17131. std::string frame;
  17132. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  17133. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  17134. frame += "Hello";
  17135. return frame;
  17136. };
  17137. // RSV1 set (0x40)
  17138. {
  17139. detail::BufferStream strm;
  17140. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  17141. ws::Opcode opcode;
  17142. std::string payload;
  17143. bool fin;
  17144. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17145. false, 1024));
  17146. }
  17147. // RSV2 set (0x20)
  17148. {
  17149. detail::BufferStream strm;
  17150. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  17151. ws::Opcode opcode;
  17152. std::string payload;
  17153. bool fin;
  17154. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17155. false, 1024));
  17156. }
  17157. // RSV3 set (0x10)
  17158. {
  17159. detail::BufferStream strm;
  17160. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  17161. ws::Opcode opcode;
  17162. std::string payload;
  17163. bool fin;
  17164. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17165. false, 1024));
  17166. }
  17167. // No RSV bits set - should succeed
  17168. {
  17169. detail::BufferStream strm;
  17170. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  17171. ws::Opcode opcode;
  17172. std::string payload;
  17173. bool fin;
  17174. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17175. false, 1024));
  17176. EXPECT_EQ(ws::Opcode::Text, opcode);
  17177. EXPECT_EQ("Hello", payload);
  17178. EXPECT_TRUE(fin);
  17179. }
  17180. }
  17181. TEST(WebSocketTest, ControlFrameValidation) {
  17182. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  17183. // payload length <= 125.
  17184. // Ping with FIN=0 - must be rejected
  17185. {
  17186. detail::BufferStream strm;
  17187. std::string frame;
  17188. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  17189. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17190. strm.write(frame.data(), frame.size());
  17191. ws::Opcode opcode;
  17192. std::string payload;
  17193. bool fin;
  17194. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17195. false, 1024));
  17196. }
  17197. // Close with FIN=0 - must be rejected
  17198. {
  17199. detail::BufferStream strm;
  17200. std::string frame;
  17201. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  17202. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17203. strm.write(frame.data(), frame.size());
  17204. ws::Opcode opcode;
  17205. std::string payload;
  17206. bool fin;
  17207. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17208. false, 1024));
  17209. }
  17210. // Ping with payload_len=126 (extended length) - must be rejected
  17211. {
  17212. detail::BufferStream strm;
  17213. std::string frame;
  17214. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17215. frame += static_cast<char>(126); // payload_len=126 (>125)
  17216. frame += static_cast<char>(0x00); // extended length high byte
  17217. frame += static_cast<char>(126); // extended length low byte
  17218. frame += std::string(126, 'x');
  17219. strm.write(frame.data(), frame.size());
  17220. ws::Opcode opcode;
  17221. std::string payload;
  17222. bool fin;
  17223. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17224. false, 1024));
  17225. }
  17226. // Ping with FIN=1 and payload_len=125 - should succeed
  17227. {
  17228. detail::BufferStream strm;
  17229. std::string frame;
  17230. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17231. frame += static_cast<char>(125); // payload_len=125
  17232. frame += std::string(125, 'x');
  17233. strm.write(frame.data(), frame.size());
  17234. ws::Opcode opcode;
  17235. std::string payload;
  17236. bool fin;
  17237. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17238. false, 1024));
  17239. EXPECT_EQ(ws::Opcode::Ping, opcode);
  17240. EXPECT_EQ(125u, payload.size());
  17241. EXPECT_TRUE(fin);
  17242. }
  17243. }
  17244. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  17245. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  17246. // length MUST be 0.
  17247. // MSB set - must be rejected
  17248. {
  17249. detail::BufferStream strm;
  17250. std::string frame;
  17251. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17252. frame += static_cast<char>(127); // 64-bit extended length
  17253. frame += static_cast<char>(0x80); // MSB set (invalid)
  17254. frame += std::string(7, '\0'); // remaining 7 bytes of length
  17255. strm.write(frame.data(), frame.size());
  17256. ws::Opcode opcode;
  17257. std::string payload;
  17258. bool fin;
  17259. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17260. false, 1024));
  17261. }
  17262. // MSB clear - should pass length parsing (will be rejected by max_len,
  17263. // but that's a different check; use a small length to verify)
  17264. {
  17265. detail::BufferStream strm;
  17266. std::string frame;
  17267. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17268. frame += static_cast<char>(127); // 64-bit extended length
  17269. frame += std::string(7, '\0'); // high bytes = 0
  17270. frame += static_cast<char>(0x03); // length = 3
  17271. frame += "abc";
  17272. strm.write(frame.data(), frame.size());
  17273. ws::Opcode opcode;
  17274. std::string payload;
  17275. bool fin;
  17276. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17277. false, 1024));
  17278. EXPECT_EQ(ws::Opcode::Text, opcode);
  17279. EXPECT_EQ("abc", payload);
  17280. }
  17281. }
  17282. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  17283. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  17284. // Valid UTF-8
  17285. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  17286. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  17287. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  17288. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  17289. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  17290. // Invalid UTF-8
  17291. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  17292. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  17293. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  17294. EXPECT_FALSE(
  17295. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  17296. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  17297. }
  17298. TEST(WebSocketTest, ConnectAndDisconnect) {
  17299. Server svr;
  17300. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17301. std::string msg;
  17302. while (ws.read(msg)) {}
  17303. });
  17304. auto port = svr.bind_to_any_port(HOST);
  17305. std::thread t([&]() { svr.listen_after_bind(); });
  17306. svr.wait_until_ready();
  17307. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17308. auto res = client.connect();
  17309. ASSERT_TRUE(res);
  17310. EXPECT_EQ(Error::Success, res.error());
  17311. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  17312. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  17313. EXPECT_TRUE(client.is_open());
  17314. client.close();
  17315. EXPECT_FALSE(client.is_open());
  17316. svr.stop();
  17317. t.join();
  17318. }
  17319. TEST(WebSocketTest, ValidURL) {
  17320. ws::WebSocketClient ws1("ws://localhost:8080/path");
  17321. EXPECT_TRUE(ws1.is_valid());
  17322. ws::WebSocketClient ws2("ws://example.com/path");
  17323. EXPECT_TRUE(ws2.is_valid());
  17324. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  17325. EXPECT_TRUE(ws3.is_valid());
  17326. #ifdef CPPHTTPLIB_SSL_ENABLED
  17327. ws::WebSocketClient wss1("wss://example.com/path");
  17328. EXPECT_TRUE(wss1.is_valid());
  17329. ws::WebSocketClient wss2("wss://example.com:443/path");
  17330. EXPECT_TRUE(wss2.is_valid());
  17331. #endif
  17332. }
  17333. TEST(WebSocketTest, InvalidURL) {
  17334. // No scheme
  17335. ws::WebSocketClient ws1("localhost:8080/path");
  17336. EXPECT_FALSE(ws1.is_valid());
  17337. // No path
  17338. ws::WebSocketClient ws2("ws://localhost:8080");
  17339. EXPECT_FALSE(ws2.is_valid());
  17340. // Empty string
  17341. ws::WebSocketClient ws3("");
  17342. EXPECT_FALSE(ws3.is_valid());
  17343. // Missing host
  17344. ws::WebSocketClient ws4("ws://:8080/path");
  17345. EXPECT_FALSE(ws4.is_valid());
  17346. // Port number overflow — should not crash
  17347. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  17348. EXPECT_FALSE(ws5.is_valid());
  17349. // Port out of range
  17350. ws::WebSocketClient ws6("ws://localhost:99999/path");
  17351. EXPECT_FALSE(ws6.is_valid());
  17352. }
  17353. TEST(WebSocketTest, UnsupportedScheme) {
  17354. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17355. ws::WebSocketClient ws1("http://localhost:8080/path");
  17356. EXPECT_FALSE(ws1.is_valid());
  17357. ws::WebSocketClient ws2("https://localhost:8080/path");
  17358. EXPECT_FALSE(ws2.is_valid());
  17359. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  17360. EXPECT_FALSE(ws3.is_valid());
  17361. #else
  17362. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  17363. std::invalid_argument);
  17364. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  17365. std::invalid_argument);
  17366. #endif
  17367. }
  17368. TEST(WebSocketTest, ConnectWhenInvalid) {
  17369. ws::WebSocketClient ws("not a valid url");
  17370. EXPECT_FALSE(ws.is_valid());
  17371. auto res = ws.connect();
  17372. EXPECT_FALSE(res);
  17373. EXPECT_EQ(Error::Connection, res.error());
  17374. EXPECT_EQ(-1, res.status());
  17375. }
  17376. TEST(WebSocketTest, ConnectRefusedReportsError) {
  17377. // Grab a port that is free, then close it again so nothing listens there
  17378. Server svr;
  17379. auto port = svr.bind_to_any_port(HOST);
  17380. svr.stop();
  17381. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17382. auto res = client.connect();
  17383. ASSERT_FALSE(res);
  17384. EXPECT_EQ(Error::Connection, res.error());
  17385. EXPECT_EQ(-1, res.status());
  17386. }
  17387. TEST(WebSocketTest, DefaultPort) {
  17388. ws::WebSocketClient ws1("ws://example.com/path");
  17389. EXPECT_TRUE(ws1.is_valid());
  17390. // ws:// defaults to port 80 (verified by successful parse)
  17391. #ifdef CPPHTTPLIB_SSL_ENABLED
  17392. ws::WebSocketClient ws2("wss://example.com/path");
  17393. EXPECT_TRUE(ws2.is_valid());
  17394. // wss:// defaults to port 443 (verified by successful parse)
  17395. #endif
  17396. }
  17397. TEST(WebSocketTest, IPv6LiteralAddress) {
  17398. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  17399. EXPECT_TRUE(ws1.is_valid());
  17400. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  17401. EXPECT_TRUE(ws2.is_valid());
  17402. }
  17403. TEST(WebSocketTest, ComplexPath) {
  17404. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  17405. EXPECT_TRUE(ws1.is_valid());
  17406. ws::WebSocketClient ws2("ws://localhost:8080/");
  17407. EXPECT_TRUE(ws2.is_valid());
  17408. }
  17409. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  17410. Server svr;
  17411. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17412. std::string msg;
  17413. while (ws.read(msg)) {}
  17414. });
  17415. auto port = svr.bind_to_any_port(HOST);
  17416. std::thread t([&]() { svr.listen_after_bind(); });
  17417. svr.wait_until_ready();
  17418. auto another_host = "example.com";
  17419. auto wrong_ip = "192.0.2.1";
  17420. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17421. client.set_hostname_addr_map({{another_host, wrong_ip}});
  17422. ASSERT_TRUE(client.connect());
  17423. EXPECT_TRUE(client.is_open());
  17424. client.close();
  17425. svr.stop();
  17426. t.join();
  17427. }
  17428. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  17429. Server svr;
  17430. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17431. std::string msg;
  17432. while (ws.read(msg)) {}
  17433. });
  17434. auto port = svr.bind_to_any_port(HOST);
  17435. std::thread t([&]() { svr.listen_after_bind(); });
  17436. svr.wait_until_ready();
  17437. auto wrong_ip = "192.0.2.1";
  17438. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17439. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  17440. client.set_connection_timeout(1);
  17441. client.set_read_timeout(1);
  17442. client.set_write_timeout(1);
  17443. EXPECT_FALSE(client.connect());
  17444. EXPECT_FALSE(client.is_open());
  17445. svr.stop();
  17446. t.join();
  17447. }
  17448. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  17449. // A mapped value that is not an IP literal must be resolved. HOST resolves
  17450. // from the hosts file, so this test needs no external DNS. "target.invalid"
  17451. // (RFC 6761) is only a map key and the Host header value.
  17452. auto host = "target.invalid";
  17453. Server svr;
  17454. std::string received_host;
  17455. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17456. received_host = req.get_header_value("Host");
  17457. std::string msg;
  17458. while (ws.read(msg)) {}
  17459. });
  17460. auto port = svr.bind_to_any_port(HOST);
  17461. std::thread t([&]() { svr.listen_after_bind(); });
  17462. // ASSERT_* below returns from the test body, which would leave t joinable
  17463. // and make ~thread call std::terminate.
  17464. auto se = detail::scope_exit([&] {
  17465. svr.stop();
  17466. if (t.joinable()) { t.join(); }
  17467. });
  17468. svr.wait_until_ready();
  17469. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  17470. std::to_string(port) + "/ws");
  17471. client.set_hostname_addr_map({{host, HOST}});
  17472. ASSERT_TRUE(client.connect());
  17473. EXPECT_TRUE(client.is_open());
  17474. client.close();
  17475. svr.stop();
  17476. t.join();
  17477. // The mapping only redirects the connection; the identity stays host_.
  17478. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  17479. }
  17480. class WebSocketIntegrationTest : public ::testing::Test {
  17481. protected:
  17482. void SetUp() override {
  17483. server_ = httplib::detail::make_unique<Server>();
  17484. setup_server();
  17485. start_server();
  17486. }
  17487. void TearDown() override {
  17488. server_->stop();
  17489. if (server_thread_.joinable()) { server_thread_.join(); }
  17490. }
  17491. void setup_server() {
  17492. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17493. std::string msg;
  17494. ws::ReadResult ret;
  17495. while ((ret = ws.read(msg))) {
  17496. if (ret == ws::Binary) {
  17497. ws.send(msg.data(), msg.size());
  17498. } else {
  17499. ws.send(msg);
  17500. }
  17501. }
  17502. });
  17503. server_->WebSocket("/ws-echo-string",
  17504. [](const Request &, ws::WebSocket &ws) {
  17505. std::string msg;
  17506. while (ws.read(msg)) {
  17507. ws.send("echo: " + msg);
  17508. }
  17509. });
  17510. server_->WebSocket(
  17511. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  17512. // Echo back request metadata
  17513. ws.send("path:" + req.path);
  17514. ws.send("header:" + req.get_header_value("X-Test-Header"));
  17515. std::string msg;
  17516. while (ws.read(msg)) {}
  17517. });
  17518. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  17519. std::string msg;
  17520. ws.read(msg); // wait for a message
  17521. ws.close();
  17522. });
  17523. server_->WebSocket("/ws-close-status",
  17524. [](const Request &, ws::WebSocket &ws) {
  17525. std::string msg;
  17526. ws.read(msg); // wait for a message
  17527. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  17528. });
  17529. server_->WebSocket(
  17530. "/ws-subprotocol",
  17531. [](const Request &, ws::WebSocket &ws) {
  17532. std::string msg;
  17533. while (ws.read(msg)) {
  17534. ws.send(msg);
  17535. }
  17536. },
  17537. [](const std::vector<std::string> &protocols) -> std::string {
  17538. for (const auto &p : protocols) {
  17539. if (p == "graphql-ws") { return p; }
  17540. }
  17541. return "";
  17542. });
  17543. }
  17544. void start_server() {
  17545. port_ = server_->bind_to_any_port(HOST);
  17546. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17547. server_->wait_until_ready();
  17548. }
  17549. std::unique_ptr<Server> server_;
  17550. std::thread server_thread_;
  17551. int port_ = 0;
  17552. };
  17553. TEST_F(WebSocketIntegrationTest, TextEcho) {
  17554. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17555. "/ws-echo");
  17556. ASSERT_TRUE(client.connect());
  17557. ASSERT_TRUE(client.is_open());
  17558. ASSERT_TRUE(client.send("Hello WebSocket"));
  17559. std::string msg;
  17560. EXPECT_EQ(ws::Text, client.read(msg));
  17561. EXPECT_EQ("Hello WebSocket", msg);
  17562. client.close();
  17563. }
  17564. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  17565. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17566. "/ws-echo");
  17567. ASSERT_TRUE(client.connect());
  17568. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  17569. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  17570. std::string msg;
  17571. EXPECT_EQ(ws::Binary, client.read(msg));
  17572. EXPECT_EQ(binary_data, msg);
  17573. client.close();
  17574. }
  17575. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  17576. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17577. "/ws-echo");
  17578. ASSERT_TRUE(client.connect());
  17579. for (int i = 0; i < 10; i++) {
  17580. auto text = "message " + std::to_string(i);
  17581. ASSERT_TRUE(client.send(text));
  17582. std::string msg;
  17583. ASSERT_TRUE(client.read(msg));
  17584. EXPECT_EQ(text, msg);
  17585. }
  17586. client.close();
  17587. }
  17588. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  17589. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17590. "/ws-close");
  17591. ASSERT_TRUE(client.connect());
  17592. // Send a message to trigger the server to close
  17593. ASSERT_TRUE(client.send("trigger close"));
  17594. // The server will close, so read should return false
  17595. std::string msg;
  17596. EXPECT_FALSE(client.read(msg));
  17597. EXPECT_FALSE(client.is_open());
  17598. }
  17599. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  17600. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17601. "/ws-echo");
  17602. ASSERT_TRUE(client.connect());
  17603. // 128KB message
  17604. std::string large_data(128 * 1024, 'X');
  17605. ASSERT_TRUE(client.send(large_data));
  17606. std::string msg;
  17607. ASSERT_TRUE(client.read(msg));
  17608. EXPECT_EQ(large_data, msg);
  17609. client.close();
  17610. }
  17611. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  17612. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17613. "/ws-echo");
  17614. ASSERT_TRUE(client.connect());
  17615. const int num_threads = 4;
  17616. std::vector<std::thread> threads;
  17617. std::atomic<int> send_count{0};
  17618. for (int t = 0; t < num_threads; t++) {
  17619. threads.emplace_back([&client, &send_count, t]() {
  17620. for (int i = 0; i < 5; i++) {
  17621. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  17622. if (client.send(text)) { send_count++; }
  17623. }
  17624. });
  17625. }
  17626. for (auto &th : threads) {
  17627. th.join();
  17628. }
  17629. int received = 0;
  17630. std::string msg;
  17631. while (received < send_count.load()) {
  17632. if (!client.read(msg)) { break; }
  17633. received++;
  17634. }
  17635. EXPECT_EQ(send_count.load(), received);
  17636. client.close();
  17637. }
  17638. TEST_F(WebSocketIntegrationTest, ReadString) {
  17639. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17640. "/ws-echo-string");
  17641. ASSERT_TRUE(client.connect());
  17642. ASSERT_TRUE(client.send("hello"));
  17643. std::string msg;
  17644. ASSERT_TRUE(client.read(msg));
  17645. EXPECT_EQ("echo: hello", msg);
  17646. ASSERT_TRUE(client.send("world"));
  17647. ASSERT_TRUE(client.read(msg));
  17648. EXPECT_EQ("echo: world", msg);
  17649. client.close();
  17650. }
  17651. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  17652. Headers headers = {{"X-Test-Header", "test-value"}};
  17653. ws::WebSocketClient client(
  17654. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  17655. ASSERT_TRUE(client.connect());
  17656. std::string msg;
  17657. ASSERT_TRUE(client.read(msg));
  17658. EXPECT_EQ("path:/ws-request-info", msg);
  17659. ASSERT_TRUE(client.read(msg));
  17660. EXPECT_EQ("header:test-value", msg);
  17661. client.close();
  17662. }
  17663. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  17664. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17665. "/ws-echo");
  17666. client.set_read_timeout(1, 0); // 1 second
  17667. ASSERT_TRUE(client.connect());
  17668. // Don't send anything — server echo handler waits for a message,
  17669. // so read() should time out and return false.
  17670. std::string msg;
  17671. EXPECT_FALSE(client.read(msg));
  17672. }
  17673. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  17674. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17675. "/ws-echo");
  17676. client.set_read_timeout(5, 0);
  17677. ASSERT_TRUE(client.connect());
  17678. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17679. // The server should reject it and close the connection.
  17680. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  17681. client.send(oversized);
  17682. // The server's read() should have failed due to payload limit,
  17683. // so our read() should return false (connection closed).
  17684. std::string msg;
  17685. EXPECT_FALSE(client.read(msg));
  17686. }
  17687. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  17688. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17689. "/ws-echo");
  17690. client.set_read_timeout(10, 0);
  17691. ASSERT_TRUE(client.connect());
  17692. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17693. // This should succeed.
  17694. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  17695. ASSERT_TRUE(client.send(at_limit));
  17696. std::string msg;
  17697. ASSERT_TRUE(client.read(msg));
  17698. EXPECT_EQ(at_limit.size(), msg.size());
  17699. client.close();
  17700. }
  17701. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  17702. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17703. "/nonexistent");
  17704. auto res = client.connect();
  17705. EXPECT_FALSE(res);
  17706. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  17707. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  17708. EXPECT_FALSE(client.is_open());
  17709. }
  17710. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  17711. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17712. "/ws-echo");
  17713. ASSERT_TRUE(client.connect());
  17714. ASSERT_TRUE(client.send(""));
  17715. std::string msg;
  17716. EXPECT_EQ(ws::Text, client.read(msg));
  17717. EXPECT_EQ("", msg);
  17718. client.close();
  17719. }
  17720. TEST_F(WebSocketIntegrationTest, Reconnect) {
  17721. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17722. "/ws-echo");
  17723. // First connection
  17724. ASSERT_TRUE(client.connect());
  17725. ASSERT_TRUE(client.send("first"));
  17726. std::string msg;
  17727. ASSERT_TRUE(client.read(msg));
  17728. EXPECT_EQ("first", msg);
  17729. client.close();
  17730. EXPECT_FALSE(client.is_open());
  17731. // Reconnect using the same client object
  17732. ASSERT_TRUE(client.connect());
  17733. ASSERT_TRUE(client.is_open());
  17734. ASSERT_TRUE(client.send("second"));
  17735. ASSERT_TRUE(client.read(msg));
  17736. EXPECT_EQ("second", msg);
  17737. client.close();
  17738. }
  17739. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  17740. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17741. "/ws-close-status");
  17742. ASSERT_TRUE(client.connect());
  17743. // Trigger the server to close with GoingAway status
  17744. ASSERT_TRUE(client.send("trigger"));
  17745. // read() should return false after receiving the close frame
  17746. std::string msg;
  17747. EXPECT_FALSE(client.read(msg));
  17748. EXPECT_FALSE(client.is_open());
  17749. }
  17750. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  17751. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17752. "/ws-echo");
  17753. ASSERT_TRUE(client.connect());
  17754. client.close(ws::CloseStatus::GoingAway, "client leaving");
  17755. EXPECT_FALSE(client.is_open());
  17756. }
  17757. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  17758. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  17759. ws::WebSocketClient client(
  17760. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17761. ASSERT_TRUE(client.connect());
  17762. // Server should have selected graphql-ws
  17763. EXPECT_EQ("graphql-ws", client.subprotocol());
  17764. client.close();
  17765. }
  17766. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  17767. Headers headers;
  17768. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  17769. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  17770. ws::WebSocketClient client(
  17771. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17772. ASSERT_TRUE(client.connect());
  17773. // The offer on the second field line counts too, so graphql-ws is selected
  17774. EXPECT_EQ("graphql-ws", client.subprotocol());
  17775. client.close();
  17776. }
  17777. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  17778. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  17779. ws::WebSocketClient client(
  17780. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17781. ASSERT_TRUE(client.connect());
  17782. // Server should not have selected any subprotocol
  17783. EXPECT_TRUE(client.subprotocol().empty());
  17784. client.close();
  17785. }
  17786. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  17787. // Connect without requesting any subprotocol
  17788. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17789. "/ws-subprotocol");
  17790. ASSERT_TRUE(client.connect());
  17791. EXPECT_TRUE(client.subprotocol().empty());
  17792. client.close();
  17793. }
  17794. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  17795. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17796. "/ws-echo");
  17797. client.set_tcp_nodelay(true);
  17798. client.set_connection_timeout(3, 0);
  17799. bool socket_options_called = false;
  17800. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  17801. ASSERT_TRUE(client.connect());
  17802. ASSERT_TRUE(client.is_open());
  17803. EXPECT_TRUE(socket_options_called);
  17804. ASSERT_TRUE(client.send("hello"));
  17805. std::string msg;
  17806. auto result = client.read(msg);
  17807. EXPECT_EQ(result, ws::ReadResult::Text);
  17808. EXPECT_EQ(msg, "hello");
  17809. client.close();
  17810. }
  17811. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  17812. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17813. "/ws-echo");
  17814. client.set_connection_timeout(std::chrono::seconds(3));
  17815. client.set_write_timeout(std::chrono::seconds(3));
  17816. // A sub-second remainder exercises the seconds/microseconds split.
  17817. client.set_read_timeout(std::chrono::milliseconds(1500));
  17818. ASSERT_TRUE(client.connect());
  17819. auto start = std::chrono::steady_clock::now();
  17820. std::string msg;
  17821. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  17822. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17823. std::chrono::steady_clock::now() - start)
  17824. .count();
  17825. // Above 1s so that dropping the microseconds half of the split fails here,
  17826. // and well under the 300s default so that ignoring the setter fails too.
  17827. EXPECT_GE(elapsed, 1400);
  17828. EXPECT_LT(elapsed, 30000);
  17829. }
  17830. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  17831. Server svr;
  17832. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  17833. if (!req.has_header("Authorization")) {
  17834. res.status = StatusCode::Unauthorized_401;
  17835. res.set_content("Unauthorized", "text/plain");
  17836. return Server::HandlerResponse::Handled;
  17837. }
  17838. return Server::HandlerResponse::Unhandled;
  17839. });
  17840. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17841. std::string msg;
  17842. while (ws.read(msg)) {
  17843. ws.send(msg);
  17844. }
  17845. });
  17846. auto port = svr.bind_to_any_port("localhost");
  17847. std::thread t([&]() { svr.listen_after_bind(); });
  17848. svr.wait_until_ready();
  17849. // Without Authorization header - should be rejected before upgrade
  17850. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  17851. EXPECT_FALSE(client1.connect());
  17852. // With Authorization header - should succeed
  17853. Headers headers = {{"Authorization", "Bearer token123"}};
  17854. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  17855. headers);
  17856. ASSERT_TRUE(client2.connect());
  17857. ASSERT_TRUE(client2.send("hello"));
  17858. std::string msg;
  17859. ASSERT_TRUE(client2.read(msg));
  17860. EXPECT_EQ("hello", msg);
  17861. client2.close();
  17862. svr.stop();
  17863. t.join();
  17864. }
  17865. TEST(WebSocketTest, QueryStringInHandshake) {
  17866. Server svr;
  17867. std::mutex mtx;
  17868. std::string received_target;
  17869. std::string received_token;
  17870. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17871. {
  17872. std::lock_guard<std::mutex> lock(mtx);
  17873. received_target = req.target;
  17874. if (req.has_param("token")) {
  17875. received_token = req.get_param_value("token");
  17876. }
  17877. }
  17878. std::string msg;
  17879. while (ws.read(msg)) {
  17880. ws.send(msg);
  17881. }
  17882. });
  17883. auto port = svr.bind_to_any_port("localhost");
  17884. std::thread t([&]() { svr.listen_after_bind(); });
  17885. svr.wait_until_ready();
  17886. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  17887. "/ws?token=ABC&session=123");
  17888. ASSERT_TRUE(client.connect());
  17889. // Round-trip ensures the handler has run and captured the request.
  17890. ASSERT_TRUE(client.send("hello"));
  17891. std::string msg;
  17892. ASSERT_TRUE(client.read(msg));
  17893. EXPECT_EQ("hello", msg);
  17894. client.close();
  17895. {
  17896. std::lock_guard<std::mutex> lock(mtx);
  17897. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  17898. EXPECT_EQ("ABC", received_token);
  17899. }
  17900. svr.stop();
  17901. t.join();
  17902. }
  17903. // Run a handshake against a throwaway server and hand the request the server
  17904. // received back to the caller, so tests can assert on the headers the client
  17905. // actually put on the wire.
  17906. static void capture_websocket_handshake_request(
  17907. const Headers &client_headers,
  17908. std::function<void(const Request &, int port)> verify) {
  17909. Server svr;
  17910. std::mutex mtx;
  17911. Request received;
  17912. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17913. {
  17914. std::lock_guard<std::mutex> lock(mtx);
  17915. received = req;
  17916. }
  17917. std::string msg;
  17918. while (ws.read(msg)) {
  17919. ws.send(msg);
  17920. }
  17921. });
  17922. auto port = svr.bind_to_any_port("localhost");
  17923. std::thread t([&]() { svr.listen_after_bind(); });
  17924. auto se = detail::scope_exit([&] {
  17925. svr.stop();
  17926. t.join();
  17927. });
  17928. svr.wait_until_ready();
  17929. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  17930. client_headers);
  17931. ASSERT_TRUE(client.connect());
  17932. ASSERT_TRUE(client.send("hello"));
  17933. std::string msg;
  17934. ASSERT_TRUE(client.read(msg));
  17935. client.close();
  17936. {
  17937. std::lock_guard<std::mutex> lock(mtx);
  17938. verify(received, port);
  17939. }
  17940. }
  17941. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  17942. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  17943. // Non-default port must be present in the Host header. Default ports
  17944. // (80/443) are omitted; that logic is covered by
  17945. // MakeHostAndPortStringTest.
  17946. EXPECT_EQ("localhost:" + std::to_string(port),
  17947. req.get_header_value("Host"));
  17948. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  17949. req.get_header_value("User-Agent"));
  17950. EXPECT_FALSE(req.has_header("Accept"));
  17951. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  17952. EXPECT_FALSE(req.has_header("Content-Length"));
  17953. });
  17954. }
  17955. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  17956. capture_websocket_handshake_request(
  17957. {{"Host", "example.com"},
  17958. {"User-Agent", "custom-agent"},
  17959. {"X-Custom", "value"}},
  17960. [](const Request &req, int) {
  17961. EXPECT_EQ("example.com", req.get_header_value("Host"));
  17962. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  17963. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  17964. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  17965. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  17966. });
  17967. }
  17968. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  17969. capture_websocket_handshake_request(
  17970. {{"Upgrade", "bogus"},
  17971. {"Connection", "close"},
  17972. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  17973. {"Sec-WebSocket-Version", "8"}},
  17974. [](const Request &req, int) {
  17975. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  17976. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  17977. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  17978. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  17979. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  17980. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  17981. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  17982. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  17983. req.get_header_value("Sec-WebSocket-Key"));
  17984. });
  17985. }
  17986. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  17987. // A header the client refuses to send must abort the handshake before any
  17988. // part of it reaches the wire; a lone request line would otherwise sit in
  17989. // the peer's buffer as a truncated request.
  17990. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17991. ASSERT_NE(INVALID_SOCKET, srv);
  17992. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  17993. sockaddr_in addr{};
  17994. addr.sin_family = AF_INET;
  17995. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  17996. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17997. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17998. ASSERT_EQ(0, ::listen(srv, 1));
  17999. sockaddr_in bound{};
  18000. socklen_t bound_len = sizeof(bound);
  18001. ASSERT_EQ(
  18002. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  18003. auto port = ntohs(bound.sin_port);
  18004. ssize_t received = -1;
  18005. std::thread t([&] {
  18006. // Bound every blocking call so a regression fails the test with a bad
  18007. // value instead of hanging the suite.
  18008. fd_set rfds;
  18009. FD_ZERO(&rfds);
  18010. FD_SET(srv, &rfds);
  18011. timeval tv{5, 0};
  18012. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  18013. 0) {
  18014. return;
  18015. }
  18016. sockaddr_in cli_addr{};
  18017. socklen_t cli_len = sizeof(cli_addr);
  18018. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18019. if (cli == INVALID_SOCKET) { return; }
  18020. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  18021. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18022. char buf[4096];
  18023. received = ::recv(cli, buf, sizeof(buf), 0);
  18024. });
  18025. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  18026. // connect() has already shut the socket down by the time it returns false,
  18027. // so the peer sees EOF without waiting for the client to be destroyed.
  18028. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  18029. {{"X-Bad", "a\r\nInjected: 1"}});
  18030. EXPECT_FALSE(client.connect());
  18031. t.join();
  18032. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  18033. EXPECT_EQ(0, received);
  18034. }
  18035. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  18036. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  18037. // contains "upgrade" as a substring is a different token and must not
  18038. // start a WebSocket handshake.
  18039. auto make_request = [](const std::vector<std::string> &connection_values) {
  18040. Request req;
  18041. req.method = "GET";
  18042. req.headers.emplace("Upgrade", "websocket");
  18043. for (const auto &value : connection_values) {
  18044. req.headers.emplace("Connection", value);
  18045. }
  18046. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18047. req.headers.emplace("Sec-WebSocket-Version", "13");
  18048. return req;
  18049. };
  18050. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  18051. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  18052. EXPECT_TRUE(
  18053. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  18054. EXPECT_TRUE(
  18055. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  18056. EXPECT_TRUE(
  18057. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  18058. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  18059. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  18060. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  18061. EXPECT_FALSE(
  18062. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  18063. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  18064. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18065. }
  18066. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  18067. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  18068. // asks recipients to match each protocol-name case-insensitively, and RFC
  18069. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  18070. // client naming websocket alongside another protocol, or on a second field
  18071. // line, is offering websocket; a value that merely contains "websocket" as a
  18072. // substring is a different protocol name and is not.
  18073. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  18074. Request req;
  18075. req.method = "GET";
  18076. for (const auto &value : upgrade_values) {
  18077. req.headers.emplace("Upgrade", value);
  18078. }
  18079. req.headers.emplace("Connection", "Upgrade");
  18080. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18081. req.headers.emplace("Sec-WebSocket-Version", "13");
  18082. return req;
  18083. };
  18084. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  18085. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  18086. EXPECT_TRUE(
  18087. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  18088. EXPECT_TRUE(
  18089. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  18090. EXPECT_TRUE(
  18091. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  18092. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  18093. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  18094. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  18095. EXPECT_FALSE(
  18096. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  18097. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  18098. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18099. }
  18100. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  18101. Server svr;
  18102. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  18103. auto port = svr.bind_to_any_port("localhost");
  18104. std::thread t([&]() { svr.listen_after_bind(); });
  18105. auto se = detail::scope_exit([&] {
  18106. svr.stop();
  18107. t.join();
  18108. });
  18109. svr.wait_until_ready();
  18110. Headers headers = {{"Upgrade", "websocket"},
  18111. {"Connection", "notupgrade"},
  18112. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  18113. {"Sec-WebSocket-Version", "13"}};
  18114. Client cli("localhost", port);
  18115. auto res = cli.Get("/ws", headers);
  18116. // The route exists only as a WebSocket route, so a request that fails the
  18117. // handshake check falls through to ordinary routing.
  18118. ASSERT_TRUE(res);
  18119. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  18120. }
  18121. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  18122. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  18123. // Connection value is the only thing left for the client to reject.
  18124. Server svr;
  18125. svr.Get("/ws", [](const Request &req, Response &res) {
  18126. res.status = StatusCode::SwitchingProtocol_101;
  18127. res.set_header("Upgrade", "websocket");
  18128. res.set_header("Connection", "notupgrade");
  18129. res.set_header("Sec-WebSocket-Accept",
  18130. detail::websocket_accept_key(
  18131. req.get_header_value("Sec-WebSocket-Key")));
  18132. });
  18133. auto port = svr.bind_to_any_port("localhost");
  18134. std::thread t([&]() { svr.listen_after_bind(); });
  18135. auto se = detail::scope_exit([&] {
  18136. svr.stop();
  18137. t.join();
  18138. });
  18139. svr.wait_until_ready();
  18140. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18141. auto res = client.connect();
  18142. EXPECT_FALSE(res);
  18143. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18144. EXPECT_FALSE(client.is_open());
  18145. }
  18146. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  18147. // The socket path doubles as the URL host, so it must not contain '/'.
  18148. const char *shard = getenv("GTEST_SHARD_INDEX");
  18149. const std::string sock_path =
  18150. shard ? std::string("httplib-ws-") + shard + ".sock"
  18151. : std::string("httplib-ws.sock");
  18152. std::remove(sock_path.c_str());
  18153. Server svr;
  18154. std::mutex mtx;
  18155. std::string received_host;
  18156. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18157. {
  18158. std::lock_guard<std::mutex> lock(mtx);
  18159. received_host = req.get_header_value("Host");
  18160. }
  18161. std::string msg;
  18162. while (ws.read(msg)) {
  18163. ws.send(msg);
  18164. }
  18165. });
  18166. svr.set_address_family(AF_UNIX);
  18167. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  18168. auto se = detail::scope_exit([&] {
  18169. svr.stop();
  18170. t.join();
  18171. std::remove(sock_path.c_str());
  18172. });
  18173. svr.wait_until_ready();
  18174. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  18175. client.set_address_family(AF_UNIX);
  18176. ASSERT_TRUE(client.connect());
  18177. ASSERT_TRUE(client.send("hello"));
  18178. std::string msg;
  18179. ASSERT_TRUE(client.read(msg));
  18180. client.close();
  18181. {
  18182. std::lock_guard<std::mutex> lock(mtx);
  18183. // There is no host:port for a Unix socket, so the same "localhost"
  18184. // placeholder the HTTP client uses is expected.
  18185. EXPECT_EQ("localhost", received_host);
  18186. }
  18187. }
  18188. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18189. class WebSocketSSLIntegrationTest : public ::testing::Test {
  18190. protected:
  18191. void SetUp() override {
  18192. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  18193. SERVER_PRIVATE_KEY_FILE);
  18194. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18195. std::string msg;
  18196. ws::ReadResult ret;
  18197. while ((ret = ws.read(msg))) {
  18198. if (ret == ws::Binary) {
  18199. ws.send(msg.data(), msg.size());
  18200. } else {
  18201. ws.send(msg);
  18202. }
  18203. }
  18204. });
  18205. port_ = server_->bind_to_any_port(HOST);
  18206. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18207. server_->wait_until_ready();
  18208. }
  18209. void TearDown() override {
  18210. server_->stop();
  18211. if (server_thread_.joinable()) { server_thread_.join(); }
  18212. }
  18213. std::unique_ptr<SSLServer> server_;
  18214. std::thread server_thread_;
  18215. int port_ = 0;
  18216. };
  18217. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  18218. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18219. "/ws-echo");
  18220. client.enable_server_certificate_verification(false);
  18221. ASSERT_TRUE(client.connect());
  18222. ASSERT_TRUE(client.is_open());
  18223. ASSERT_TRUE(client.send("Hello WSS"));
  18224. std::string msg;
  18225. EXPECT_EQ(ws::Text, client.read(msg));
  18226. EXPECT_EQ("Hello WSS", msg);
  18227. client.close();
  18228. }
  18229. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  18230. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  18231. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  18232. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  18233. // client (without calling close() first) is the only path that runs
  18234. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  18235. // bug exactly.
  18236. //
  18237. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  18238. // when linked against an instrumented libssl; run under Valgrind to catch it
  18239. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  18240. // suite (the freed session otherwise stalls on the close handshake) — this test
  18241. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  18242. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  18243. {
  18244. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18245. "/ws-echo");
  18246. client.enable_server_certificate_verification(false);
  18247. client.set_read_timeout(2, 0);
  18248. client.set_write_timeout(2, 0);
  18249. ASSERT_TRUE(client.connect());
  18250. ASSERT_TRUE(client.is_open());
  18251. ASSERT_TRUE(client.send("still open"));
  18252. // Intentionally do NOT call client.close(): leaving scope runs
  18253. // shutdown_and_close() with the WebSocket still open, which must send the
  18254. // close frame while the TLS session is still alive.
  18255. }
  18256. }
  18257. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  18258. // shutdown_and_close() at the start of connect(), reproducing the same
  18259. // use-after-free within the test body rather than at scope exit. The second
  18260. // connect must succeed and echo, proving the close handshake ran over a live
  18261. // session. See the note above about memory-tool requirements.
  18262. TEST_F(WebSocketSSLIntegrationTest,
  18263. ReconnectWhileOpenSendsCloseOverLiveSession) {
  18264. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18265. "/ws-echo");
  18266. client.enable_server_certificate_verification(false);
  18267. client.set_read_timeout(2, 0);
  18268. client.set_write_timeout(2, 0);
  18269. ASSERT_TRUE(client.connect());
  18270. ASSERT_TRUE(client.is_open());
  18271. ASSERT_TRUE(client.send("still open"));
  18272. // Reconnect without closing first: connect() calls shutdown_and_close() on
  18273. // the still-open connection, which must not touch a freed TLS session.
  18274. ASSERT_TRUE(client.connect());
  18275. ASSERT_TRUE(client.is_open());
  18276. ASSERT_TRUE(client.send("after reconnect"));
  18277. std::string msg;
  18278. EXPECT_EQ(ws::Text, client.read(msg));
  18279. EXPECT_EQ("after reconnect", msg);
  18280. client.close();
  18281. }
  18282. #endif
  18283. #ifdef CPPHTTPLIB_SSL_ENABLED
  18284. class WebSocketSSLCATest : public ::testing::Test {
  18285. protected:
  18286. void SetUp() override {
  18287. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  18288. SERVER_PRIVATE_KEY_FILE);
  18289. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18290. std::string msg;
  18291. while (ws.read(msg)) {
  18292. ws.send(msg);
  18293. }
  18294. });
  18295. port_ = server_->bind_to_any_port("127.0.0.1");
  18296. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18297. server_->wait_until_ready();
  18298. }
  18299. void TearDown() override {
  18300. server_->stop();
  18301. if (server_thread_.joinable()) { server_thread_.join(); }
  18302. }
  18303. std::string url() const {
  18304. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  18305. }
  18306. std::unique_ptr<SSLServer> server_;
  18307. std::thread server_thread_;
  18308. int port_ = 0;
  18309. };
  18310. // A custom CA loaded as PEM verifies the server with full certificate
  18311. // verification enabled
  18312. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  18313. ws::WebSocketClient client(url());
  18314. std::string cert;
  18315. read_file(SERVER_CERT2_FILE, cert);
  18316. client.load_ca_cert_store(cert.c_str(), cert.size());
  18317. ASSERT_TRUE(client.connect());
  18318. ASSERT_TRUE(client.send("hello"));
  18319. std::string msg;
  18320. EXPECT_EQ(ws::Text, client.read(msg));
  18321. EXPECT_EQ("hello", msg);
  18322. client.close();
  18323. }
  18324. // A custom CA that does not cover the server must fail verification (the
  18325. // custom CA is exclusive; system certs are not loaded alongside it)
  18326. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  18327. ws::WebSocketClient client(url());
  18328. std::string cert;
  18329. read_file(CLIENT_CA_CERT_FILE, cert);
  18330. client.load_ca_cert_store(cert.c_str(), cert.size());
  18331. auto res = client.connect();
  18332. ASSERT_FALSE(res);
  18333. EXPECT_EQ(Error::SSLServerVerification, res.error());
  18334. EXPECT_EQ(-1, res.status());
  18335. EXPECT_NE(0u, res.ssl_backend_error());
  18336. }
  18337. // The same CA as a file path rather than PEM in memory
  18338. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  18339. ws::WebSocketClient client(url());
  18340. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18341. ASSERT_TRUE(client.connect());
  18342. ASSERT_TRUE(client.send("hello"));
  18343. std::string msg;
  18344. EXPECT_EQ(ws::Text, client.read(msg));
  18345. EXPECT_EQ("hello", msg);
  18346. client.close();
  18347. }
  18348. // ...and a CA file that does not cover the server still fails, so it is the
  18349. // path above that decides the outcome
  18350. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  18351. ws::WebSocketClient client(url());
  18352. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  18353. ASSERT_FALSE(client.connect());
  18354. }
  18355. // Regression test: reconnecting with a native custom CA store used to reuse
  18356. // a store handle the previous TLS context had already freed (use-after-free
  18357. // under the OpenSSL backend). The context now lives as long as the client.
  18358. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  18359. ws::WebSocketClient client(url());
  18360. std::string cert;
  18361. read_file(SERVER_CERT2_FILE, cert);
  18362. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  18363. ASSERT_TRUE(client.connect());
  18364. client.close();
  18365. ASSERT_TRUE(client.connect());
  18366. ASSERT_TRUE(client.send("again"));
  18367. std::string msg;
  18368. EXPECT_EQ(ws::Text, client.read(msg));
  18369. EXPECT_EQ("again", msg);
  18370. client.close();
  18371. }
  18372. // Regression test: a certificate with a trusted chain but no identity match
  18373. // for the server IP must be rejected. The Mbed TLS backend used to skip
  18374. // verification entirely for IP hosts, so this connection succeeded there.
  18375. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  18376. // chain verification while the identity check must still fail.
  18377. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  18378. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18379. ASSERT_TRUE(svr.is_valid());
  18380. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18381. std::string msg;
  18382. while (ws.read(msg)) {
  18383. ws.send(msg);
  18384. }
  18385. });
  18386. auto port = svr.bind_to_any_port("127.0.0.1");
  18387. auto t = std::thread([&]() { svr.listen_after_bind(); });
  18388. auto se = detail::scope_exit([&] {
  18389. svr.stop();
  18390. t.join();
  18391. });
  18392. svr.wait_until_ready();
  18393. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  18394. "/echo");
  18395. std::string cert;
  18396. read_file(SERVER_CERT_FILE, cert);
  18397. client.load_ca_cert_store(cert.c_str(), cert.size());
  18398. ASSERT_FALSE(client.connect());
  18399. }
  18400. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  18401. // SNI, so nothing binds the host name to the TLS session. These bind the
  18402. // server to "localhost" instead, the only shape that exercises the SNI and
  18403. // hostname-verification path with certificate verification left enabled.
  18404. class WebSocketSSLDnsHostTest : public ::testing::Test {
  18405. protected:
  18406. void Start(const char *cert_file) {
  18407. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  18408. SERVER_PRIVATE_KEY_FILE);
  18409. ASSERT_TRUE(server_->is_valid());
  18410. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18411. std::string msg;
  18412. while (ws.read(msg)) {
  18413. ws.send(msg);
  18414. }
  18415. });
  18416. port_ = server_->bind_to_any_port("localhost");
  18417. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18418. server_->wait_until_ready();
  18419. }
  18420. void TearDown() override {
  18421. if (server_) { server_->stop(); }
  18422. if (server_thread_.joinable()) { server_thread_.join(); }
  18423. }
  18424. std::string url() const {
  18425. return "wss://localhost:" + std::to_string(port_) + "/echo";
  18426. }
  18427. std::unique_ptr<SSLServer> server_;
  18428. std::thread server_thread_;
  18429. int port_ = 0;
  18430. };
  18431. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  18432. // out and the connection is usable
  18433. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  18434. Start(SERVER_CERT2_FILE);
  18435. ws::WebSocketClient client(url());
  18436. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18437. ASSERT_TRUE(client.connect());
  18438. ASSERT_TRUE(client.send("hello"));
  18439. std::string msg;
  18440. EXPECT_EQ(ws::Text, client.read(msg));
  18441. EXPECT_EQ("hello", msg);
  18442. client.close();
  18443. }
  18444. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  18445. // while the identity check must still reject "localhost"
  18446. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  18447. Start(SERVER_CERT_FILE);
  18448. ws::WebSocketClient client(url());
  18449. client.set_ca_cert_path(SERVER_CERT_FILE);
  18450. auto res = client.connect();
  18451. ASSERT_FALSE(res);
  18452. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  18453. EXPECT_EQ(-1, res.status());
  18454. }
  18455. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  18456. // disabled: the chain is still checked, only the identity check is skipped
  18457. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  18458. Start(SERVER_CERT_FILE);
  18459. ws::WebSocketClient client(url());
  18460. client.set_ca_cert_path(SERVER_CERT_FILE);
  18461. client.enable_server_hostname_verification(false);
  18462. ASSERT_TRUE(client.connect());
  18463. ASSERT_TRUE(client.send("hello"));
  18464. std::string msg;
  18465. EXPECT_EQ(ws::Text, client.read(msg));
  18466. EXPECT_EQ("hello", msg);
  18467. client.close();
  18468. }
  18469. // A CA that did not sign the server certificate fails the chain, even though
  18470. // the name would match
  18471. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  18472. Start(SERVER_CERT2_FILE);
  18473. ws::WebSocketClient client(url());
  18474. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  18475. ASSERT_FALSE(client.connect());
  18476. }
  18477. // With verification disabled, neither the chain nor the name is checked
  18478. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  18479. Start(SERVER_CERT_FILE);
  18480. ws::WebSocketClient client(url());
  18481. client.enable_server_certificate_verification(false);
  18482. ASSERT_TRUE(client.connect());
  18483. ASSERT_TRUE(client.send("hello"));
  18484. std::string msg;
  18485. EXPECT_EQ(ws::Text, client.read(msg));
  18486. EXPECT_EQ("hello", msg);
  18487. client.close();
  18488. }
  18489. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  18490. protected:
  18491. void SetUp() override {
  18492. server_ = httplib::detail::make_unique<SSLServer>(
  18493. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18494. ASSERT_TRUE(server_->is_valid());
  18495. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18496. std::string msg;
  18497. while (ws.read(msg)) {
  18498. ws.send(msg);
  18499. }
  18500. });
  18501. port_ = server_->bind_to_any_port("localhost");
  18502. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18503. server_->wait_until_ready();
  18504. }
  18505. void TearDown() override {
  18506. server_->stop();
  18507. if (server_thread_.joinable()) { server_thread_.join(); }
  18508. }
  18509. std::string url() const {
  18510. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  18511. }
  18512. void ConnectWithClientCert(const std::string &client_cert_file,
  18513. const std::string &client_private_key_file,
  18514. const char *private_key_password) {
  18515. std::string cert_pem, key_pem;
  18516. read_file(client_cert_file, cert_pem);
  18517. read_file(client_private_key_file, key_pem);
  18518. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  18519. key_pem.c_str(), key_pem.size(),
  18520. private_key_password};
  18521. ws::WebSocketClient client(url(), pem);
  18522. ASSERT_TRUE(client.is_valid());
  18523. client.enable_server_certificate_verification(false);
  18524. ASSERT_TRUE(client.connect());
  18525. ASSERT_TRUE(client.send("hello"));
  18526. std::string msg;
  18527. EXPECT_EQ(ws::Text, client.read(msg));
  18528. EXPECT_EQ("hello", msg);
  18529. client.close();
  18530. }
  18531. std::unique_ptr<SSLServer> server_;
  18532. std::thread server_thread_;
  18533. int port_ = 0;
  18534. };
  18535. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  18536. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  18537. }
  18538. // Control for the tests above: the fixture's server really does require a
  18539. // client certificate, so it is the PEM the constructor installed that decides
  18540. // the outcome.
  18541. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  18542. ws::WebSocketClient client(url());
  18543. ASSERT_TRUE(client.is_valid());
  18544. client.enable_server_certificate_verification(false);
  18545. EXPECT_FALSE(client.connect());
  18546. }
  18547. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  18548. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  18549. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  18550. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  18551. }
  18552. #endif
  18553. #if !defined(_WIN32)
  18554. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  18555. auto secret_dir = std::string("./symlink_test_secret");
  18556. auto served_dir = std::string("./symlink_test_served");
  18557. auto secret_file = secret_dir + "/secret.txt";
  18558. auto symlink_path = served_dir + "/escape";
  18559. // Setup: create directories and files
  18560. mkdir(secret_dir.c_str(), 0755);
  18561. mkdir(served_dir.c_str(), 0755);
  18562. {
  18563. std::ofstream ofs(secret_file);
  18564. ofs << "SECRET_DATA";
  18565. }
  18566. // Create symlink using absolute path so it resolves correctly
  18567. #ifdef PATH_MAX
  18568. char abs_secret[PATH_MAX];
  18569. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  18570. #else
  18571. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  18572. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  18573. ASSERT_NE(nullptr, abs_secret);
  18574. #endif
  18575. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  18576. auto se = detail::scope_exit([&] {
  18577. unlink(symlink_path.c_str());
  18578. unlink(secret_file.c_str());
  18579. rmdir(served_dir.c_str());
  18580. rmdir(secret_dir.c_str());
  18581. });
  18582. Server svr;
  18583. svr.set_mount_point("/", served_dir);
  18584. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18585. auto se2 = detail::scope_exit([&] {
  18586. svr.stop();
  18587. listen_thread.join();
  18588. });
  18589. svr.wait_until_ready();
  18590. Client cli("localhost", PORT);
  18591. // Symlink pointing outside base dir should be blocked
  18592. auto res = cli.Get("/escape/secret.txt");
  18593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18594. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18595. }
  18596. #endif
  18597. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  18598. // A GET request with Content-Length to a static file handler must have its
  18599. // body drained before the keep-alive connection is reused. Otherwise the
  18600. // unread body bytes are interpreted as the next HTTP request.
  18601. //
  18602. // The body is sent AFTER receiving the first response (as in the original
  18603. // PoC) so that the stream_line_reader cannot buffer it together with the
  18604. // headers of the first request.
  18605. Server svr;
  18606. svr.set_mount_point("/", "./www");
  18607. std::atomic<int> smuggled_count(0);
  18608. svr.Get("/smuggled", [&](const Request &, Response &res) {
  18609. smuggled_count++;
  18610. res.set_content("oops", "text/plain");
  18611. });
  18612. auto port = svr.bind_to_any_port("localhost");
  18613. thread t = thread([&] { svr.listen_after_bind(); });
  18614. auto se = detail::scope_exit([&] {
  18615. svr.stop();
  18616. t.join();
  18617. });
  18618. svr.wait_until_ready();
  18619. auto error = Error::Success;
  18620. auto sock = detail::create_client_socket(
  18621. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  18622. /*connection_timeout_sec=*/2, 0,
  18623. /*read_timeout_sec=*/2, 0,
  18624. /*write_timeout_sec=*/2, 0, std::string(), error);
  18625. ASSERT_NE(INVALID_SOCKET, sock);
  18626. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18627. // The "smuggled" request will be sent as the body of the outer GET
  18628. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  18629. "Host: localhost\r\n"
  18630. "Connection: close\r\n"
  18631. "\r\n";
  18632. // Step 1: Send only the outer request headers (no body yet)
  18633. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  18634. "Host: localhost\r\n"
  18635. "Content-Length: " +
  18636. std::to_string(smuggled.size()) +
  18637. "\r\n"
  18638. "\r\n";
  18639. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  18640. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  18641. // Step 2: Read the first response (server serves file without reading body)
  18642. std::string first_response;
  18643. char buf[4096];
  18644. for (;;) {
  18645. auto n = recv(sock, buf, sizeof(buf), 0);
  18646. if (n <= 0) break;
  18647. first_response.append(buf, static_cast<size_t>(n));
  18648. // Stop once we have a complete response (headers + body)
  18649. auto hdr_end = first_response.find("\r\n\r\n");
  18650. if (hdr_end != std::string::npos) {
  18651. // Check for Content-Length to know when the body is complete
  18652. auto cl_pos = first_response.find("Content-Length:");
  18653. if (cl_pos != std::string::npos) {
  18654. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  18655. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  18656. auto cl = std::stoul(
  18657. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  18658. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  18659. } else {
  18660. break; // No Content-Length, assume headers-only response
  18661. }
  18662. }
  18663. }
  18664. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  18665. // Step 3: Now send the body, which looks like a new HTTP request.
  18666. // On a vulnerable server the keep-alive loop reads this as a second request.
  18667. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  18668. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  18669. // Step 4: Try to read a second response (should NOT exist after fix)
  18670. std::string second_response;
  18671. for (;;) {
  18672. auto n = recv(sock, buf, sizeof(buf), 0);
  18673. if (n <= 0) break;
  18674. second_response.append(buf, static_cast<size_t>(n));
  18675. }
  18676. // The smuggled request must NOT have been processed
  18677. EXPECT_EQ(0, smuggled_count.load());
  18678. }
  18679. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18680. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  18681. // must be rejected with 400 Bad Request.
  18682. Server svr;
  18683. svr.Post("/test", [&](const Request &, Response &res) {
  18684. res.set_content("ok", "text/plain");
  18685. });
  18686. thread t = thread([&] { svr.listen(HOST, PORT); });
  18687. auto se = detail::scope_exit([&] {
  18688. svr.stop();
  18689. t.join();
  18690. ASSERT_FALSE(svr.is_running());
  18691. });
  18692. svr.wait_until_ready();
  18693. // Exact "chunked"
  18694. {
  18695. auto req = "POST /test HTTP/1.1\r\n"
  18696. "Host: localhost\r\n"
  18697. "Content-Length: 5\r\n"
  18698. "Transfer-Encoding: chunked\r\n"
  18699. "Connection: close\r\n"
  18700. "\r\n"
  18701. "hello";
  18702. std::string response;
  18703. ASSERT_TRUE(send_request(1, req, &response));
  18704. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18705. response.substr(0, response.find("\r\n")));
  18706. }
  18707. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  18708. {
  18709. auto req = "POST /test HTTP/1.1\r\n"
  18710. "Host: localhost\r\n"
  18711. "Content-Length: 5\r\n"
  18712. "Transfer-Encoding: gzip, chunked\r\n"
  18713. "Connection: close\r\n"
  18714. "\r\n"
  18715. "hello";
  18716. std::string response;
  18717. ASSERT_TRUE(send_request(1, req, &response));
  18718. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18719. response.substr(0, response.find("\r\n")));
  18720. }
  18721. }
  18722. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  18723. Server svr;
  18724. svr.Post("/test", [&](const Request &, Response &res) {
  18725. res.set_content("ok", "text/plain");
  18726. });
  18727. thread t = thread([&] { svr.listen(HOST, PORT); });
  18728. auto se = detail::scope_exit([&] {
  18729. svr.stop();
  18730. t.join();
  18731. ASSERT_FALSE(svr.is_running());
  18732. });
  18733. svr.wait_until_ready();
  18734. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  18735. // length cannot be determined, so the server must answer 400 and close
  18736. // rather than treat the request as bodyless and leave the body in the
  18737. // socket for the next request to pick up.
  18738. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  18739. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  18740. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  18741. std::string response;
  18742. ASSERT_TRUE(send_request(1, req, &response));
  18743. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18744. response.substr(0, response.find("\r\n")))
  18745. << transfer_encoding;
  18746. }
  18747. // RFC 9110 5.3: the codings may also be split across several
  18748. // Transfer-Encoding lines, which combine in the order they were received.
  18749. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  18750. // just like the single-line "chunked, gzip" above.
  18751. {
  18752. auto req = "POST /test HTTP/1.1\r\n"
  18753. "Host: localhost\r\n"
  18754. "Transfer-Encoding: chunked\r\n"
  18755. "Transfer-Encoding: gzip\r\n"
  18756. "\r\n"
  18757. "0\r\n\r\n";
  18758. std::string response;
  18759. ASSERT_TRUE(send_request(1, req, &response));
  18760. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18761. response.substr(0, response.find("\r\n")));
  18762. }
  18763. // A sequence ending in chunked stays valid.
  18764. auto req = "POST /test HTTP/1.1\r\n"
  18765. "Host: localhost\r\n"
  18766. "Transfer-Encoding: gzip, chunked\r\n"
  18767. "Connection: close\r\n"
  18768. "\r\n"
  18769. "0\r\n\r\n";
  18770. std::string response;
  18771. ASSERT_TRUE(send_request(1, req, &response));
  18772. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18773. // ...including when it is spread over several lines.
  18774. auto split_req = "POST /test HTTP/1.1\r\n"
  18775. "Host: localhost\r\n"
  18776. "Transfer-Encoding: gzip\r\n"
  18777. "Transfer-Encoding: chunked\r\n"
  18778. "Connection: close\r\n"
  18779. "\r\n"
  18780. "0\r\n\r\n";
  18781. std::string split_response;
  18782. ASSERT_TRUE(send_request(1, split_req, &split_response));
  18783. EXPECT_EQ("HTTP/1.1 200 OK",
  18784. split_response.substr(0, split_response.find("\r\n")));
  18785. }
  18786. // Regression for issue #2450: a DELETE without Content-Length on a
  18787. // keep-alive connection must not let the post-response drain consume the
  18788. // next request's bytes.
  18789. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  18790. Server svr;
  18791. std::atomic<int> delete_count(0);
  18792. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  18793. delete_count++;
  18794. res.status = StatusCode::NoContent_204;
  18795. });
  18796. auto port = svr.bind_to_any_port(HOST);
  18797. thread t = thread([&] { svr.listen_after_bind(); });
  18798. auto se = detail::scope_exit([&] {
  18799. svr.stop();
  18800. t.join();
  18801. });
  18802. svr.wait_until_ready();
  18803. auto error = Error::Success;
  18804. auto sock = detail::create_client_socket(
  18805. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18806. /*connection_timeout_sec=*/2, 0,
  18807. /*read_timeout_sec=*/2, 0,
  18808. /*write_timeout_sec=*/2, 0, std::string(), error);
  18809. ASSERT_NE(INVALID_SOCKET, sock);
  18810. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18811. auto send_request_and_read_response = [&](const std::string &req,
  18812. std::string &out) -> bool {
  18813. auto sent = send(sock, req.data(), req.size(), 0);
  18814. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  18815. char buf[4096];
  18816. for (;;) {
  18817. auto n = recv(sock, buf, sizeof(buf), 0);
  18818. if (n <= 0) { return !out.empty(); }
  18819. out.append(buf, static_cast<size_t>(n));
  18820. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  18821. }
  18822. };
  18823. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  18824. "Host: localhost\r\n"
  18825. "\r\n";
  18826. std::string resp1;
  18827. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  18828. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  18829. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  18830. "Host: localhost\r\n"
  18831. "Connection: close\r\n"
  18832. "\r\n";
  18833. std::string resp2;
  18834. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  18835. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  18836. EXPECT_EQ(2, delete_count.load());
  18837. }
  18838. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  18839. Server svr;
  18840. svr.Post("/ingest", [&](const Request &, Response &res,
  18841. const ContentReader &content_reader) {
  18842. auto consumed = content_reader([](const char *, size_t) { return false; });
  18843. EXPECT_FALSE(consumed);
  18844. res.status = StatusCode::Conflict_409;
  18845. res.set_header("Connection", "close");
  18846. });
  18847. auto port = svr.bind_to_any_port(HOST);
  18848. thread t = thread([&] { svr.listen_after_bind(); });
  18849. auto se = detail::scope_exit([&] {
  18850. svr.stop();
  18851. t.join();
  18852. });
  18853. svr.wait_until_ready();
  18854. auto error = Error::Success;
  18855. auto sock = detail::create_client_socket(
  18856. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18857. /*connection_timeout_sec=*/2, 0,
  18858. /*read_timeout_sec=*/1, 0,
  18859. /*write_timeout_sec=*/2, 0, std::string(), error);
  18860. ASSERT_NE(INVALID_SOCKET, sock);
  18861. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18862. std::string request = "POST /ingest HTTP/1.1\r\n"
  18863. "Host: localhost\r\n"
  18864. "Transfer-Encoding: chunked\r\n"
  18865. "\r\n"
  18866. "4\r\n"
  18867. "data\r\n";
  18868. auto sent = send(sock, request.data(), request.size(), 0);
  18869. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  18870. std::string response;
  18871. ssize_t received = 0;
  18872. do {
  18873. char buf[4096];
  18874. received = recv(sock, buf, sizeof(buf), 0);
  18875. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  18876. } while (received > 0);
  18877. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  18878. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  18879. EXPECT_EQ(0, received);
  18880. }
  18881. namespace no_proxy_test {
  18882. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  18883. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  18884. // calling listen().
  18885. class ScopedServer {
  18886. public:
  18887. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  18888. ~ScopedServer() {
  18889. svr_.stop();
  18890. if (th_.joinable()) { th_.join(); }
  18891. }
  18892. Server &svr() { return svr_; }
  18893. int port() const { return port_; }
  18894. void listen() {
  18895. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18896. svr_.wait_until_ready();
  18897. }
  18898. private:
  18899. Server svr_;
  18900. std::thread th_;
  18901. int port_ = 0;
  18902. };
  18903. class ProxyAndTargetServers {
  18904. public:
  18905. ProxyAndTargetServers() {
  18906. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  18907. proxy_hits_++;
  18908. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18909. res.set_content("via-proxy", "text/plain");
  18910. });
  18911. target_.Get(".*", [this](const Request &req, Response &res) {
  18912. target_hits_++;
  18913. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18914. res.set_content("direct", "text/plain");
  18915. });
  18916. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  18917. target_port_ = target_.bind_to_any_port("127.0.0.1");
  18918. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  18919. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  18920. proxy_mock_.wait_until_ready();
  18921. target_.wait_until_ready();
  18922. }
  18923. ~ProxyAndTargetServers() {
  18924. proxy_mock_.stop();
  18925. target_.stop();
  18926. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  18927. if (target_thread_.joinable()) { target_thread_.join(); }
  18928. }
  18929. Server &proxy_mock() { return proxy_mock_; }
  18930. Server &target() { return target_; }
  18931. int proxy_port() const { return proxy_port_; }
  18932. int target_port() const { return target_port_; }
  18933. int proxy_hits() const { return proxy_hits_.load(); }
  18934. int target_hits() const { return target_hits_.load(); }
  18935. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  18936. void reset_counters() {
  18937. proxy_hits_ = 0;
  18938. target_hits_ = 0;
  18939. last_had_proxy_authz_ = false;
  18940. }
  18941. private:
  18942. Server proxy_mock_;
  18943. Server target_;
  18944. std::thread proxy_thread_;
  18945. std::thread target_thread_;
  18946. int proxy_port_ = 0;
  18947. int target_port_ = 0;
  18948. std::atomic<int> proxy_hits_{0};
  18949. std::atomic<int> target_hits_{0};
  18950. std::atomic<bool> last_had_proxy_authz_{false};
  18951. };
  18952. inline std::unique_ptr<Client> make_client(const std::string &host,
  18953. ProxyAndTargetServers &s) {
  18954. auto cli = detail::make_unique<Client>(host, s.target_port());
  18955. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  18956. cli->set_proxy("127.0.0.1", s.proxy_port());
  18957. return cli;
  18958. }
  18959. } // namespace no_proxy_test
  18960. using no_proxy_test::make_client;
  18961. using no_proxy_test::ProxyAndTargetServers;
  18962. TEST(NoProxyTest, ExactHostnameBypasses) {
  18963. ProxyAndTargetServers s;
  18964. auto cli = make_client("example.com", s);
  18965. cli->set_no_proxy({"example.com"});
  18966. auto res = cli->Get("/");
  18967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18968. EXPECT_EQ(0, s.proxy_hits());
  18969. EXPECT_EQ(1, s.target_hits());
  18970. }
  18971. TEST(NoProxyTest, SubdomainBypasses) {
  18972. ProxyAndTargetServers s;
  18973. auto cli = make_client("foo.example.com", s);
  18974. cli->set_no_proxy({"example.com"});
  18975. auto res = cli->Get("/");
  18976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18977. EXPECT_EQ(0, s.proxy_hits());
  18978. EXPECT_EQ(1, s.target_hits());
  18979. }
  18980. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  18981. // Regression guard: "evilexample.com" must not be considered a subdomain
  18982. // of "example.com". Without the dot-boundary rule, a naive endsWith
  18983. // check would let traffic bypass the proxy and leak credentials direct
  18984. // to the attacker host.
  18985. ProxyAndTargetServers s;
  18986. auto cli = make_client("evilexample.com", s);
  18987. cli->set_no_proxy({"example.com"});
  18988. auto res = cli->Get("/");
  18989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18990. EXPECT_GE(s.proxy_hits(), 1);
  18991. EXPECT_EQ(0, s.target_hits());
  18992. }
  18993. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  18994. ProxyAndTargetServers s;
  18995. auto cli = make_client("example.com.evil.com", s);
  18996. cli->set_no_proxy({"example.com"});
  18997. auto res = cli->Get("/");
  18998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18999. EXPECT_GE(s.proxy_hits(), 1);
  19000. EXPECT_EQ(0, s.target_hits());
  19001. }
  19002. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  19003. ProxyAndTargetServers s;
  19004. auto cli = make_client("example.com", s);
  19005. cli->set_no_proxy({".example.com"});
  19006. auto res = cli->Get("/");
  19007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19008. EXPECT_EQ(0, s.proxy_hits());
  19009. EXPECT_EQ(1, s.target_hits());
  19010. }
  19011. TEST(NoProxyTest, CaseInsensitiveHostname) {
  19012. ProxyAndTargetServers s;
  19013. auto cli = make_client("Example.COM", s);
  19014. cli->set_no_proxy({"EXAMPLE.com"});
  19015. auto res = cli->Get("/");
  19016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19017. EXPECT_EQ(0, s.proxy_hits());
  19018. EXPECT_EQ(1, s.target_hits());
  19019. }
  19020. TEST(NoProxyTest, TrailingDotIsNormalized) {
  19021. ProxyAndTargetServers s;
  19022. auto cli = make_client("example.com.", s);
  19023. cli->set_no_proxy({"example.com"});
  19024. auto res = cli->Get("/");
  19025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19026. EXPECT_EQ(0, s.proxy_hits());
  19027. EXPECT_EQ(1, s.target_hits());
  19028. }
  19029. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  19030. // Trailing dots must be normalized on BOTH sides — host and entry.
  19031. // An implementation that only strips the host-side trailing dot would
  19032. // fail to match host "example.com" against entry "example.com." because
  19033. // a literal substring search would compare 11 chars against 12.
  19034. ProxyAndTargetServers s;
  19035. auto cli = make_client("example.com", s);
  19036. cli->set_no_proxy({"example.com."});
  19037. auto res = cli->Get("/");
  19038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19039. EXPECT_EQ(0, s.proxy_hits());
  19040. EXPECT_EQ(1, s.target_hits());
  19041. }
  19042. TEST(NoProxyTest, WildcardBypassesEverything) {
  19043. ProxyAndTargetServers s;
  19044. auto cli = make_client("anything.invalid.test", s);
  19045. cli->set_no_proxy({"*"});
  19046. auto res = cli->Get("/");
  19047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19048. EXPECT_EQ(0, s.proxy_hits());
  19049. EXPECT_EQ(1, s.target_hits());
  19050. }
  19051. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  19052. ProxyAndTargetServers s;
  19053. Client cli("127.0.0.1", s.target_port());
  19054. cli.set_proxy("127.0.0.1", s.proxy_port());
  19055. cli.set_no_proxy({"127.0.0.1"});
  19056. auto res = cli.Get("/");
  19057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19058. EXPECT_EQ(0, s.proxy_hits());
  19059. EXPECT_EQ(1, s.target_hits());
  19060. }
  19061. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  19062. ProxyAndTargetServers s;
  19063. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  19064. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  19065. cli.set_proxy("127.0.0.1", s.proxy_port());
  19066. cli.set_no_proxy({"::1"});
  19067. auto res = cli.Get("/");
  19068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19069. EXPECT_EQ(0, s.proxy_hits());
  19070. EXPECT_EQ(1, s.target_hits());
  19071. }
  19072. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  19073. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  19074. // must still be recognized as IPv6 for CIDR matching. Implementations
  19075. // that detect IPv6 only when the host begins with '[' would parse the
  19076. // host as a hostname and miss the match.
  19077. ProxyAndTargetServers s;
  19078. Client cli("fe80::1", s.target_port());
  19079. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19080. cli.set_proxy("127.0.0.1", s.proxy_port());
  19081. cli.set_no_proxy({"fe80::/10"});
  19082. auto res = cli.Get("/");
  19083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19084. EXPECT_EQ(0, s.proxy_hits());
  19085. EXPECT_EQ(1, s.target_hits());
  19086. }
  19087. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  19088. ProxyAndTargetServers s;
  19089. Client cli("::1", s.target_port());
  19090. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  19091. cli.set_proxy("127.0.0.1", s.proxy_port());
  19092. cli.set_no_proxy({"[::1]"});
  19093. auto res = cli.Get("/");
  19094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19095. EXPECT_EQ(0, s.proxy_hits());
  19096. EXPECT_EQ(1, s.target_hits());
  19097. }
  19098. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  19099. ProxyAndTargetServers s;
  19100. Client cli("fe80::1", s.target_port());
  19101. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19102. cli.set_proxy("127.0.0.1", s.proxy_port());
  19103. cli.set_no_proxy({"[fe80::]/10"});
  19104. auto res = cli.Get("/");
  19105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19106. EXPECT_EQ(0, s.proxy_hits());
  19107. EXPECT_EQ(1, s.target_hits());
  19108. }
  19109. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  19110. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  19111. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  19112. // tricks via address-family conversion.
  19113. ProxyAndTargetServers s;
  19114. Client cli("::ffff:127.0.0.1", s.target_port());
  19115. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  19116. cli.set_proxy("127.0.0.1", s.proxy_port());
  19117. cli.set_no_proxy({"127.0.0.1"});
  19118. auto res = cli.Get("/");
  19119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19120. EXPECT_GE(s.proxy_hits(), 1);
  19121. EXPECT_EQ(0, s.target_hits());
  19122. }
  19123. TEST(NoProxyTest, IPv4CidrMatch) {
  19124. ProxyAndTargetServers s;
  19125. Client cli("127.0.0.1", s.target_port());
  19126. cli.set_proxy("127.0.0.1", s.proxy_port());
  19127. cli.set_no_proxy({"127.0.0.0/8"});
  19128. auto res = cli.Get("/");
  19129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19130. EXPECT_EQ(0, s.proxy_hits());
  19131. EXPECT_EQ(1, s.target_hits());
  19132. }
  19133. TEST(NoProxyTest, IPv4CidrNonMatch) {
  19134. ProxyAndTargetServers s;
  19135. Client cli("127.0.0.1", s.target_port());
  19136. cli.set_proxy("127.0.0.1", s.proxy_port());
  19137. cli.set_no_proxy({"10.0.0.0/8"});
  19138. auto res = cli.Get("/");
  19139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19140. EXPECT_GE(s.proxy_hits(), 1);
  19141. EXPECT_EQ(0, s.target_hits());
  19142. }
  19143. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  19144. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  19145. // IPv4 target matches.
  19146. ProxyAndTargetServers s;
  19147. Client cli("127.0.0.1", s.target_port());
  19148. cli.set_proxy("127.0.0.1", s.proxy_port());
  19149. cli.set_no_proxy({"0.0.0.0/0"});
  19150. auto res = cli.Get("/");
  19151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19152. EXPECT_EQ(0, s.proxy_hits());
  19153. EXPECT_EQ(1, s.target_hits());
  19154. }
  19155. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  19156. ProxyAndTargetServers s;
  19157. Client cli("127.0.0.1", s.target_port());
  19158. cli.set_proxy("127.0.0.1", s.proxy_port());
  19159. cli.set_no_proxy({"127.0.0.1"});
  19160. auto res = cli.Get("/");
  19161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19162. EXPECT_EQ(0, s.proxy_hits());
  19163. EXPECT_EQ(1, s.target_hits());
  19164. }
  19165. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  19166. ProxyAndTargetServers s;
  19167. Client cli("127.0.0.1", s.target_port());
  19168. cli.set_proxy("127.0.0.1", s.proxy_port());
  19169. cli.set_no_proxy({"127.0.0.0/33"});
  19170. auto res = cli.Get("/");
  19171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19172. EXPECT_GE(s.proxy_hits(), 1);
  19173. EXPECT_EQ(0, s.target_hits());
  19174. }
  19175. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  19176. // Empty prefix after the slash must be rejected, not silently treated as /32.
  19177. ProxyAndTargetServers s;
  19178. Client cli("127.0.0.1", s.target_port());
  19179. cli.set_proxy("127.0.0.1", s.proxy_port());
  19180. cli.set_no_proxy({"127.0.0.1/"});
  19181. auto res = cli.Get("/");
  19182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19183. EXPECT_GE(s.proxy_hits(), 1);
  19184. EXPECT_EQ(0, s.target_hits());
  19185. }
  19186. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  19187. ProxyAndTargetServers s;
  19188. auto cli = make_client("internal.corp", s);
  19189. cli->set_proxy_basic_auth("u", "p");
  19190. cli->set_no_proxy({"internal.corp"});
  19191. auto res = cli->Get("/");
  19192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19193. EXPECT_EQ(1, s.target_hits());
  19194. EXPECT_EQ(0, s.proxy_hits());
  19195. EXPECT_FALSE(s.last_had_proxy_authz())
  19196. << "Proxy-Authorization must not be sent direct to the target";
  19197. }
  19198. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  19199. ProxyAndTargetServers s;
  19200. auto cli = make_client("public.example", s);
  19201. cli->set_proxy_basic_auth("u", "p");
  19202. cli->set_no_proxy({"internal.corp"}); // does not match
  19203. auto res = cli->Get("/");
  19204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19205. EXPECT_GE(s.proxy_hits(), 1);
  19206. EXPECT_TRUE(s.last_had_proxy_authz());
  19207. }
  19208. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  19209. ProxyAndTargetServers s;
  19210. auto cli = make_client("anything.test", s);
  19211. auto res = cli->Get("/");
  19212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19213. EXPECT_GE(s.proxy_hits(), 1);
  19214. EXPECT_EQ(0, s.target_hits());
  19215. }
  19216. TEST(NoProxyTest, PortSpecificEntryRejected) {
  19217. ProxyAndTargetServers s;
  19218. auto cli = make_client("example.com", s);
  19219. cli->set_no_proxy({"example.com:8080"});
  19220. auto res = cli->Get("/");
  19221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19222. EXPECT_GE(s.proxy_hits(), 1);
  19223. EXPECT_EQ(0, s.target_hits());
  19224. }
  19225. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  19226. ProxyAndTargetServers s;
  19227. auto cli = make_client("anything.test", s);
  19228. cli->set_no_proxy({"", " ", "\t"});
  19229. auto res = cli->Get("/");
  19230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19231. EXPECT_GE(s.proxy_hits(), 1);
  19232. EXPECT_EQ(0, s.target_hits());
  19233. }
  19234. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  19235. // An entry with leading/trailing whitespace must still match — env-style
  19236. // values are commonly pasted with stray spaces and an implementation
  19237. // that feeds the raw token directly to inet_pton would fail to match
  19238. // valid CIDRs because of the spaces.
  19239. ProxyAndTargetServers s;
  19240. Client cli("127.0.0.1", s.target_port());
  19241. cli.set_proxy("127.0.0.1", s.proxy_port());
  19242. cli.set_no_proxy({" 127.0.0.0/8 "});
  19243. auto res = cli.Get("/");
  19244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19245. EXPECT_EQ(0, s.proxy_hits());
  19246. EXPECT_EQ(1, s.target_hits());
  19247. }
  19248. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  19249. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  19250. // go direct and must NOT carry Proxy-Authorization.
  19251. std::atomic<int> proxy_hits{0};
  19252. std::atomic<int> target_hits{0};
  19253. std::atomic<bool> target_saw_authz{false};
  19254. no_proxy_test::ScopedServer proxy_mock, target;
  19255. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19256. proxy_hits++;
  19257. res.status = 302;
  19258. res.set_header("Location", "http://127.0.0.1:" +
  19259. std::to_string(target.port()) + "/landed");
  19260. });
  19261. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19262. target_hits++;
  19263. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  19264. res.set_content("direct", "text/plain");
  19265. });
  19266. proxy_mock.listen();
  19267. target.listen();
  19268. Client cli("public.example", target.port());
  19269. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19270. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19271. cli.set_proxy_basic_auth("u", "p");
  19272. cli.set_no_proxy({"127.0.0.1"});
  19273. cli.set_follow_location(true);
  19274. auto res = cli.Get("/redir");
  19275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19276. EXPECT_GE(proxy_hits.load(), 1);
  19277. EXPECT_GE(target_hits.load(), 1);
  19278. EXPECT_FALSE(target_saw_authz.load());
  19279. }
  19280. #ifdef CPPHTTPLIB_SSL_ENABLED
  19281. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  19282. // Direct origin replying 407 must not trigger the digest retry; otherwise
  19283. // proxy creds would be sent to the (possibly hostile) origin.
  19284. std::atomic<int> target_hits{0};
  19285. std::atomic<bool> target_saw_proxy_authz{false};
  19286. no_proxy_test::ScopedServer target;
  19287. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19288. target_hits++;
  19289. if (req.has_header("Proxy-Authorization")) {
  19290. target_saw_proxy_authz = true;
  19291. }
  19292. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19293. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  19294. "nonce=\"abc\", algorithm=MD5");
  19295. });
  19296. target.listen();
  19297. // The proxy address is set to the target's port: the bypass MUST kick in;
  19298. // if it doesn't, the test still routes "via proxy" to the same server and
  19299. // the Proxy-Authorization assertion below catches the leak.
  19300. Client cli("evil.example", target.port());
  19301. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  19302. cli.set_proxy("127.0.0.1", target.port());
  19303. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19304. cli.set_no_proxy({"evil.example"});
  19305. auto res = cli.Get("/x");
  19306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19307. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19308. EXPECT_EQ(1, target_hits.load());
  19309. EXPECT_FALSE(target_saw_proxy_authz.load());
  19310. }
  19311. #endif
  19312. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  19313. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  19314. std::atomic<int> proxy_hits{0};
  19315. std::atomic<int> bypass_hits{0};
  19316. std::atomic<bool> proxy_saw_c_url{false};
  19317. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  19318. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  19319. proxy_hits++;
  19320. if (req.path.find("/start") != std::string::npos) {
  19321. res.status = 302;
  19322. res.set_header("Location", "http://127.0.0.1:" +
  19323. std::to_string(bypass_server.port()) +
  19324. "/middle");
  19325. return;
  19326. }
  19327. if (req.path.find("/end") != std::string::npos) {
  19328. proxy_saw_c_url = true;
  19329. res.set_content("c-via-proxy", "text/plain");
  19330. return;
  19331. }
  19332. res.set_content("unexpected", "text/plain");
  19333. });
  19334. // public.example's "advertised" port is arbitrary (the request never lands
  19335. // there — it goes through the proxy), but use a dynamic value to stay
  19336. // friendly with sharded parallel runs.
  19337. int public_port = bypass_server.port();
  19338. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  19339. bypass_hits++;
  19340. res.status = 302;
  19341. res.set_header("Location", "http://public.example:" +
  19342. std::to_string(public_port) + "/end");
  19343. });
  19344. proxy_mock.listen();
  19345. bypass_server.listen();
  19346. Client cli("public.example", public_port);
  19347. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19348. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19349. cli.set_no_proxy({"127.0.0.1"});
  19350. cli.set_follow_location(true);
  19351. auto res = cli.Get("/start");
  19352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19353. EXPECT_EQ(StatusCode::OK_200, res->status);
  19354. EXPECT_EQ("c-via-proxy", res->body);
  19355. EXPECT_GE(proxy_hits.load(), 2);
  19356. EXPECT_GE(bypass_hits.load(), 1);
  19357. EXPECT_TRUE(proxy_saw_c_url.load());
  19358. }
  19359. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  19360. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  19361. // request reconnects to the correct endpoint.
  19362. std::atomic<int> proxy_hits{0};
  19363. std::atomic<int> target_hits{0};
  19364. no_proxy_test::ScopedServer proxy_mock, target;
  19365. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19366. proxy_hits++;
  19367. res.set_content("via-proxy", "text/plain");
  19368. });
  19369. target.svr().Get(".*", [&](const Request &, Response &res) {
  19370. target_hits++;
  19371. res.set_content("direct", "text/plain");
  19372. });
  19373. proxy_mock.listen();
  19374. target.listen();
  19375. Client cli("public.example", target.port());
  19376. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19377. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19378. cli.set_keep_alive(true);
  19379. auto res1 = cli.Get("/a");
  19380. ASSERT_TRUE(res1);
  19381. EXPECT_EQ("via-proxy", res1->body);
  19382. EXPECT_EQ(1, proxy_hits.load());
  19383. EXPECT_EQ(0, target_hits.load());
  19384. cli.set_no_proxy({"public.example"});
  19385. auto res2 = cli.Get("/b");
  19386. ASSERT_TRUE(res2);
  19387. EXPECT_EQ("direct", res2->body);
  19388. EXPECT_EQ(1, proxy_hits.load());
  19389. EXPECT_EQ(1, target_hits.load());
  19390. }
  19391. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  19392. namespace proxy_tunnel_test {
  19393. // SSLServer counterpart to no_proxy_test::ScopedServer.
  19394. class ScopedSSLServer {
  19395. public:
  19396. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  19397. port_ = svr_.bind_to_any_port("127.0.0.1");
  19398. }
  19399. ~ScopedSSLServer() {
  19400. svr_.stop();
  19401. if (th_.joinable()) { th_.join(); }
  19402. }
  19403. SSLServer &svr() { return svr_; }
  19404. int port() const { return port_; }
  19405. void listen() {
  19406. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19407. svr_.wait_until_ready();
  19408. }
  19409. private:
  19410. SSLServer svr_;
  19411. std::thread th_;
  19412. int port_ = 0;
  19413. };
  19414. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  19415. class ScopedConnectProxy {
  19416. public:
  19417. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  19418. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  19419. if (listen_fd_ < 0) { return; }
  19420. int yes = 1;
  19421. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  19422. sockaddr_in a{};
  19423. a.sin_family = AF_INET;
  19424. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  19425. a.sin_port = 0;
  19426. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  19427. return;
  19428. }
  19429. socklen_t alen = sizeof(a);
  19430. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  19431. 0) {
  19432. return;
  19433. }
  19434. port_ = ntohs(a.sin_port);
  19435. if (::listen(listen_fd_, 1) != 0) { return; }
  19436. th_ = std::thread([this] { run(); });
  19437. }
  19438. ~ScopedConnectProxy() {
  19439. stop_ = true;
  19440. if (listen_fd_ >= 0) {
  19441. ::shutdown(listen_fd_, SHUT_RDWR);
  19442. ::close(listen_fd_);
  19443. }
  19444. if (th_.joinable()) { th_.join(); }
  19445. }
  19446. int port() const { return port_; }
  19447. int connect_hits() const { return connect_hits_.load(); }
  19448. private:
  19449. void run() {
  19450. while (!stop_.load()) {
  19451. fd_set rfds;
  19452. FD_ZERO(&rfds);
  19453. FD_SET(listen_fd_, &rfds);
  19454. timeval tv{0, 100 * 1000};
  19455. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  19456. if (sel <= 0) { continue; }
  19457. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  19458. if (client_fd < 0) { continue; }
  19459. std::string req;
  19460. char buf[2048];
  19461. while (req.find("\r\n\r\n") == std::string::npos) {
  19462. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  19463. if (n <= 0) { break; }
  19464. req.append(buf, static_cast<size_t>(n));
  19465. }
  19466. if (req.compare(0, 7, "CONNECT") != 0) {
  19467. ::close(client_fd);
  19468. continue;
  19469. }
  19470. connect_hits_++;
  19471. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  19472. ::send(client_fd, ok, std::strlen(ok), 0);
  19473. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  19474. sockaddr_in o{};
  19475. o.sin_family = AF_INET;
  19476. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  19477. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  19478. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  19479. 0) {
  19480. ::close(client_fd);
  19481. ::close(origin_fd);
  19482. continue;
  19483. }
  19484. auto forward = [](int from, int to) {
  19485. char b[8192];
  19486. for (;;) {
  19487. ssize_t n = ::recv(from, b, sizeof(b), 0);
  19488. if (n <= 0) { break; }
  19489. ssize_t off = 0;
  19490. while (off < n) {
  19491. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  19492. if (s <= 0) {
  19493. off = n;
  19494. break;
  19495. }
  19496. off += s;
  19497. }
  19498. }
  19499. ::shutdown(to, SHUT_WR);
  19500. };
  19501. std::thread t1([&] { forward(client_fd, origin_fd); });
  19502. std::thread t2([&] { forward(origin_fd, client_fd); });
  19503. t1.join();
  19504. t2.join();
  19505. ::close(client_fd);
  19506. ::close(origin_fd);
  19507. }
  19508. }
  19509. int forward_port_ = -1;
  19510. int listen_fd_ = -1;
  19511. int port_ = 0;
  19512. std::thread th_;
  19513. std::atomic<bool> stop_{false};
  19514. std::atomic<int> connect_hits_{0};
  19515. };
  19516. } // namespace proxy_tunnel_test
  19517. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  19518. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  19519. // retry; otherwise proxy creds would be sent to the origin.
  19520. std::atomic<int> origin_hits{0};
  19521. std::atomic<bool> origin_saw_proxy_authz{false};
  19522. proxy_tunnel_test::ScopedSSLServer origin;
  19523. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  19524. origin_hits++;
  19525. if (req.has_header("Proxy-Authorization")) {
  19526. origin_saw_proxy_authz = true;
  19527. }
  19528. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19529. res.set_header("Proxy-Authenticate",
  19530. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  19531. "algorithm=MD5");
  19532. });
  19533. origin.listen();
  19534. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  19535. ASSERT_NE(0, proxy.port());
  19536. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  19537. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  19538. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  19539. // and answer with its own status, making this test flaky.
  19540. SSLClient cli("127.0.0.1", origin.port());
  19541. cli.enable_server_certificate_verification(false);
  19542. cli.set_proxy("127.0.0.1", proxy.port());
  19543. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19544. auto res = cli.Get("/x");
  19545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19546. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19547. EXPECT_EQ(1, origin_hits.load());
  19548. EXPECT_FALSE(origin_saw_proxy_authz.load());
  19549. EXPECT_EQ(1, proxy.connect_hits());
  19550. }
  19551. #endif