test.cc 748 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374
  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(BearerTokenAuthTest, SchemeValidation) {
  1358. // A value shorter than "Bearer " must not throw from the fixed-length
  1359. // substr, and a non-Bearer scheme must not be reported as a token.
  1360. struct {
  1361. const char *value;
  1362. const char *expected;
  1363. } cases[] = {
  1364. {"x", ""},
  1365. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1366. {"Bearer abc123", "abc123"},
  1367. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1368. };
  1369. for (const auto &c : cases) {
  1370. Request req;
  1371. req.set_header("Authorization", c.value);
  1372. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1373. }
  1374. }
  1375. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1376. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1377. // to depend on the standard library (libstdc++ handed back duplicates in
  1378. // reverse insertion order, libc++ in insertion order).
  1379. Request req;
  1380. req.set_header("Accept-Encoding", "gzip");
  1381. req.set_header("Accept-Encoding", "deflate");
  1382. req.set_header("Accept-Encoding", "br");
  1383. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1384. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1385. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1386. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1387. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1388. }
  1389. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1390. Request req;
  1391. req.set_header("X-Test", "only");
  1392. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1393. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1394. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1395. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1396. }
  1397. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1398. Headers headers;
  1399. headers.emplace("Host", "example.com");
  1400. headers.emplace("Accept-Encoding", "gzip");
  1401. headers.emplace("User-Agent", "test");
  1402. headers.emplace("Accept-Encoding", "deflate");
  1403. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1404. "Accept-Encoding=deflate ",
  1405. entries_to_string(headers));
  1406. }
  1407. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1408. Headers headers = {{"Content-Type", "text/html"},
  1409. {"CONTENT-TYPE", "text/xml"}};
  1410. EXPECT_EQ(2U, headers.count("content-type"));
  1411. auto it = headers.find("content-type");
  1412. ASSERT_TRUE(it != headers.end());
  1413. EXPECT_EQ("text/html", it->second);
  1414. }
  1415. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1416. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1417. // drop only those fields and leave everything positioned between them.
  1418. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1419. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1420. auto rng = headers.equal_range("a");
  1421. headers.erase(rng.first, rng.second);
  1422. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1423. }
  1424. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1425. Headers headers = {
  1426. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1427. EXPECT_EQ(3U, headers.erase("A"));
  1428. EXPECT_EQ(0U, headers.count("A"));
  1429. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1430. }
  1431. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1432. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1433. headers.emplace_front("Host", "example.com");
  1434. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1435. entries_to_string(headers));
  1436. }
  1437. TEST(ParseHeaderValueTest, Range) {
  1438. {
  1439. Ranges ranges;
  1440. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1441. EXPECT_TRUE(ret);
  1442. EXPECT_EQ(1u, ranges.size());
  1443. EXPECT_EQ(1u, ranges[0].first);
  1444. EXPECT_EQ(-1, ranges[0].second);
  1445. }
  1446. {
  1447. Ranges ranges;
  1448. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1449. EXPECT_TRUE(ret);
  1450. EXPECT_EQ(1u, ranges.size());
  1451. EXPECT_EQ(-1, ranges[0].first);
  1452. EXPECT_EQ(1u, ranges[0].second);
  1453. }
  1454. {
  1455. Ranges ranges;
  1456. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1457. EXPECT_TRUE(ret);
  1458. EXPECT_EQ(1u, ranges.size());
  1459. EXPECT_EQ(1u, ranges[0].first);
  1460. EXPECT_EQ(10u, ranges[0].second);
  1461. }
  1462. {
  1463. Ranges ranges;
  1464. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1465. EXPECT_FALSE(ret);
  1466. }
  1467. {
  1468. Ranges ranges;
  1469. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1470. EXPECT_TRUE(ret);
  1471. EXPECT_EQ(2u, ranges.size());
  1472. EXPECT_EQ(1u, ranges[0].first);
  1473. EXPECT_EQ(10u, ranges[0].second);
  1474. EXPECT_EQ(100u, ranges[1].first);
  1475. EXPECT_EQ(-1, ranges[1].second);
  1476. }
  1477. {
  1478. Ranges ranges;
  1479. auto ret =
  1480. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1481. EXPECT_TRUE(ret);
  1482. EXPECT_EQ(3u, ranges.size());
  1483. EXPECT_EQ(1u, ranges[0].first);
  1484. EXPECT_EQ(10u, ranges[0].second);
  1485. EXPECT_EQ(100u, ranges[1].first);
  1486. EXPECT_EQ(200u, ranges[1].second);
  1487. EXPECT_EQ(300u, ranges[2].first);
  1488. EXPECT_EQ(400u, ranges[2].second);
  1489. }
  1490. {
  1491. Ranges ranges;
  1492. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1493. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1494. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1495. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1496. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1497. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1498. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1499. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1500. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1501. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1502. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1503. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1504. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1505. EXPECT_TRUE(ranges.empty());
  1506. }
  1507. }
  1508. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1509. Request req;
  1510. req.set_header("Accept-Encoding", "gzip");
  1511. Response res;
  1512. res.set_header("Content-Type", "text/plain");
  1513. auto ret = detail::encoding_type(req, res);
  1514. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1515. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1516. #else
  1517. EXPECT_TRUE(ret == detail::EncodingType::None);
  1518. #endif
  1519. }
  1520. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1521. Request req;
  1522. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1523. Response res;
  1524. res.set_header("Content-Type", "text/plain");
  1525. auto ret = detail::encoding_type(req, res);
  1526. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1527. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1528. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1529. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1530. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1531. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1532. #else
  1533. EXPECT_TRUE(ret == detail::EncodingType::None);
  1534. #endif
  1535. }
  1536. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1537. Request req;
  1538. req.set_header("Accept-Encoding",
  1539. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1540. Response res;
  1541. res.set_header("Content-Type", "text/plain");
  1542. auto ret = detail::encoding_type(req, res);
  1543. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1544. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1545. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1546. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1547. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1548. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1549. #else
  1550. EXPECT_TRUE(ret == detail::EncodingType::None);
  1551. #endif
  1552. }
  1553. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1554. // All supported encodings rejected with q=0 should return None
  1555. Request req;
  1556. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  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(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1563. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1564. Request req;
  1565. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1566. Response res;
  1567. res.set_header("Content-Type", "text/plain");
  1568. auto ret = detail::encoding_type(req, res);
  1569. EXPECT_TRUE(ret == detail::EncodingType::None);
  1570. }
  1571. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1572. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1573. Request req;
  1574. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1575. Response res;
  1576. res.set_header("Content-Type", "text/plain");
  1577. auto ret = detail::encoding_type(req, res);
  1578. EXPECT_TRUE(ret == detail::EncodingType::None);
  1579. }
  1580. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1581. // RFC 7231: Accept-Encoding values are case-insensitive
  1582. Request req;
  1583. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1584. Response res;
  1585. res.set_header("Content-Type", "text/plain");
  1586. auto ret = detail::encoding_type(req, res);
  1587. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1588. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1589. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1590. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1591. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1592. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1593. #else
  1594. EXPECT_TRUE(ret == detail::EncodingType::None);
  1595. #endif
  1596. }
  1597. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1598. // q value should determine priority, not hardcoded order
  1599. Request req;
  1600. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1601. Response res;
  1602. res.set_header("Content-Type", "text/plain");
  1603. auto ret = detail::encoding_type(req, res);
  1604. // gzip has highest q=1.0, so it should be selected even though
  1605. // br and zstd are also supported
  1606. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1607. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1608. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1609. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1610. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1611. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1612. #else
  1613. EXPECT_TRUE(ret == detail::EncodingType::None);
  1614. #endif
  1615. }
  1616. TEST(BufferStreamTest, read) {
  1617. detail::BufferStream strm1;
  1618. Stream &strm = strm1;
  1619. EXPECT_EQ(5, strm.write("hello"));
  1620. char buf[512];
  1621. EXPECT_EQ(2, strm.read(buf, 2));
  1622. EXPECT_EQ('h', buf[0]);
  1623. EXPECT_EQ('e', buf[1]);
  1624. EXPECT_EQ(2, strm.read(buf, 2));
  1625. EXPECT_EQ('l', buf[0]);
  1626. EXPECT_EQ('l', buf[1]);
  1627. EXPECT_EQ(1, strm.read(buf, 1));
  1628. EXPECT_EQ('o', buf[0]);
  1629. EXPECT_EQ(0, strm.read(buf, 1));
  1630. }
  1631. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1632. auto host = "www.httpwatch.com";
  1633. auto ip = hosted_at(host);
  1634. EXPECT_EQ("23.96.13.243", ip);
  1635. std::vector<std::string> addrs;
  1636. hosted_at(host, addrs);
  1637. EXPECT_EQ(1u, addrs.size());
  1638. }
  1639. #if 0 // It depends on each test environment...
  1640. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1641. auto host = "www.youtube.com";
  1642. std::vector<std::string> addrs;
  1643. hosted_at(host, addrs);
  1644. EXPECT_EQ(20u, addrs.size());
  1645. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1646. EXPECT_TRUE(it != addrs.end());
  1647. }
  1648. #endif
  1649. class ChunkedEncodingTest : public ::testing::Test {
  1650. protected:
  1651. ChunkedEncodingTest()
  1652. : cli_(HOST, PORT)
  1653. #ifdef CPPHTTPLIB_SSL_ENABLED
  1654. ,
  1655. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1656. #endif
  1657. {
  1658. cli_.set_connection_timeout(2);
  1659. #ifdef CPPHTTPLIB_SSL_ENABLED
  1660. cli_.enable_server_certificate_verification(false);
  1661. #endif
  1662. }
  1663. virtual void SetUp() {
  1664. read_file("./image.jpg", image_data_);
  1665. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1666. res.set_content("Hello World!", "text/plain");
  1667. });
  1668. svr_.Get(
  1669. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1670. res.set_chunked_content_provider(
  1671. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1672. size_t remaining = image_data_.size() - offset;
  1673. if (remaining == 0) {
  1674. sink.done();
  1675. } else {
  1676. constexpr size_t CHUNK_SIZE = 1024;
  1677. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1678. sink.write(&image_data_[offset], send_size);
  1679. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1680. }
  1681. return true;
  1682. });
  1683. });
  1684. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1685. svr_.wait_until_ready();
  1686. }
  1687. virtual void TearDown() {
  1688. svr_.stop();
  1689. if (!request_threads_.empty()) {
  1690. std::this_thread::sleep_for(std::chrono::seconds(1));
  1691. for (auto &t : request_threads_) {
  1692. t.join();
  1693. }
  1694. }
  1695. t_.join();
  1696. }
  1697. #ifdef CPPHTTPLIB_SSL_ENABLED
  1698. SSLClient cli_;
  1699. SSLServer svr_;
  1700. #else
  1701. Client cli_;
  1702. Server svr_;
  1703. #endif
  1704. thread t_;
  1705. std::vector<thread> request_threads_;
  1706. std::string image_data_;
  1707. };
  1708. TEST_F(ChunkedEncodingTest, NormalGet) {
  1709. auto res = cli_.Get("/chunked");
  1710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1711. std::string out;
  1712. read_file("./image.jpg", out);
  1713. EXPECT_EQ(StatusCode::OK_200, res->status);
  1714. EXPECT_EQ(out, res->body);
  1715. }
  1716. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1717. std::string body;
  1718. auto res = cli_.Get("/chunked", [&](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_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1729. std::string body;
  1730. auto res = cli_.Get(
  1731. "/chunked",
  1732. [&](const Response &response) {
  1733. EXPECT_EQ(StatusCode::OK_200, response.status);
  1734. return true;
  1735. },
  1736. [&](const char *data, size_t data_length) {
  1737. body.append(data, data_length);
  1738. return true;
  1739. });
  1740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1741. std::string out;
  1742. read_file("./image.jpg", out);
  1743. EXPECT_EQ(StatusCode::OK_200, res->status);
  1744. EXPECT_EQ(out, body);
  1745. }
  1746. TEST(RangeTest, FromHTTPBin_Online) {
  1747. auto host = "httpbingo.org";
  1748. auto path = std::string{"/range/32"};
  1749. #ifdef CPPHTTPLIB_SSL_ENABLED
  1750. auto port = 443;
  1751. SSLClient cli(host, port);
  1752. #else
  1753. auto port = 80;
  1754. Client cli(host, port);
  1755. #endif
  1756. cli.set_connection_timeout(5);
  1757. {
  1758. auto res = cli.Get(path);
  1759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1760. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1761. EXPECT_EQ(StatusCode::OK_200, res->status);
  1762. }
  1763. {
  1764. Headers headers = {make_range_header({{1, -1}})};
  1765. auto res = cli.Get(path, headers);
  1766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1767. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1768. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1769. }
  1770. {
  1771. Headers headers = {make_range_header({{1, 10}})};
  1772. auto res = cli.Get(path, headers);
  1773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1774. EXPECT_EQ("bcdefghijk", res->body);
  1775. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1776. }
  1777. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1778. // entire resource, while the original httpbin returned 200. Both are
  1779. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1780. {
  1781. Headers headers = {make_range_header({{0, 31}})};
  1782. auto res = cli.Get(path, headers);
  1783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1784. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1785. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1786. res->status == StatusCode::PartialContent_206);
  1787. }
  1788. {
  1789. Headers headers = {make_range_header({{0, -1}})};
  1790. auto res = cli.Get(path, headers);
  1791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1792. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1793. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1794. res->status == StatusCode::PartialContent_206);
  1795. }
  1796. // go-httpbin returns 206 with clamped range for over-range requests,
  1797. // while the original httpbin returned 416. Both behaviors are observed
  1798. // in real servers, so we only verify the request succeeds.
  1799. {
  1800. Headers headers = {make_range_header({{0, 32}})};
  1801. auto res = cli.Get(path, headers);
  1802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1803. }
  1804. }
  1805. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1806. auto host = "unresolvableaddress.local";
  1807. auto path = std::string{"/"};
  1808. #ifdef CPPHTTPLIB_SSL_ENABLED
  1809. auto port = 443;
  1810. SSLClient cli(host, port);
  1811. #else
  1812. auto port = 80;
  1813. Client cli(host, port);
  1814. #endif
  1815. cli.set_connection_timeout(1);
  1816. {
  1817. auto res = cli.Get(path);
  1818. ASSERT_FALSE(res);
  1819. }
  1820. std::this_thread::sleep_for(std::chrono::seconds(8));
  1821. }
  1822. #if defined(__linux__) && defined(__GLIBC__) && \
  1823. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1824. // Forward declaration: in split builds split.py strips `inline` and moves the
  1825. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1826. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1827. // against the symbol in both header-only and split builds.
  1828. namespace httplib {
  1829. namespace detail {
  1830. int getaddrinfo_with_timeout(const char *node, const char *service,
  1831. const struct addrinfo *hints,
  1832. struct addrinfo **res, time_t timeout_sec);
  1833. } // namespace detail
  1834. } // namespace httplib
  1835. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1836. //
  1837. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1838. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1839. // gai_suspend() call hits the connection timeout the function calls
  1840. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1841. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1842. // still alive and still references the now-destroyed stack frame.
  1843. //
  1844. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1845. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1846. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1847. // and runs them in a container.
  1848. namespace {
  1849. bool should_run_issue_2431_tests() {
  1850. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1851. return v && *v && std::string(v) != "0";
  1852. }
  1853. std::string unique_unresolvable_host(int n) {
  1854. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1855. // glibc still asks the configured nameserver — which is exactly the path
  1856. // we want to exercise. A unique label per call avoids the resolver cache.
  1857. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1858. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1859. std::to_string(n) + ".invalid";
  1860. }
  1861. } // namespace
  1862. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1863. if (!should_run_issue_2431_tests()) {
  1864. GTEST_SKIP()
  1865. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1866. }
  1867. for (int i = 0; i < 8; ++i) {
  1868. struct addrinfo hints;
  1869. memset(&hints, 0, sizeof(hints));
  1870. hints.ai_family = AF_UNSPEC;
  1871. hints.ai_socktype = SOCK_STREAM;
  1872. auto host = unique_unresolvable_host(i);
  1873. struct addrinfo *result = nullptr;
  1874. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1875. &result, /*timeout_sec=*/1);
  1876. if (rc == 0 && result) { freeaddrinfo(result); }
  1877. }
  1878. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1879. // stack region they still believe holds their gaicb.
  1880. std::this_thread::sleep_for(std::chrono::seconds(3));
  1881. }
  1882. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1883. if (!should_run_issue_2431_tests()) {
  1884. GTEST_SKIP()
  1885. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1886. }
  1887. std::atomic<bool> stop{false};
  1888. std::vector<std::thread> threads;
  1889. for (int t = 0; t < 8; ++t) {
  1890. threads.emplace_back([t, &stop] {
  1891. int i = 0;
  1892. while (!stop.load(std::memory_order_relaxed)) {
  1893. struct addrinfo hints;
  1894. memset(&hints, 0, sizeof(hints));
  1895. hints.ai_family = AF_UNSPEC;
  1896. hints.ai_socktype = SOCK_STREAM;
  1897. auto host = unique_unresolvable_host(t * 100000 + i++);
  1898. struct addrinfo *result = nullptr;
  1899. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1900. &result, /*timeout_sec=*/1);
  1901. if (rc == 0 && result) { freeaddrinfo(result); }
  1902. }
  1903. });
  1904. }
  1905. std::this_thread::sleep_for(std::chrono::seconds(8));
  1906. stop.store(true, std::memory_order_relaxed);
  1907. for (auto &th : threads) {
  1908. th.join();
  1909. }
  1910. std::this_thread::sleep_for(std::chrono::seconds(3));
  1911. }
  1912. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1913. if (!should_run_issue_2431_tests()) {
  1914. GTEST_SKIP()
  1915. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1916. }
  1917. std::atomic<bool> stop{false};
  1918. std::vector<std::thread> threads;
  1919. for (int t = 0; t < 8; ++t) {
  1920. threads.emplace_back([t, &stop] {
  1921. int i = 0;
  1922. while (!stop.load(std::memory_order_relaxed)) {
  1923. auto host = unique_unresolvable_host(t * 100000 + i++);
  1924. Client cli(host, 80);
  1925. cli.set_connection_timeout(1, 0);
  1926. cli.set_read_timeout(1, 0);
  1927. cli.set_write_timeout(1, 0);
  1928. (void)cli.Get("/");
  1929. }
  1930. });
  1931. }
  1932. std::this_thread::sleep_for(std::chrono::seconds(8));
  1933. stop.store(true, std::memory_order_relaxed);
  1934. for (auto &th : threads) {
  1935. th.join();
  1936. }
  1937. std::this_thread::sleep_for(std::chrono::seconds(3));
  1938. }
  1939. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1940. TEST(ConnectionErrorTest, InvalidHost) {
  1941. auto host = "-abcde.com";
  1942. #ifdef CPPHTTPLIB_SSL_ENABLED
  1943. auto port = 443;
  1944. SSLClient cli(host, port);
  1945. #else
  1946. auto port = 80;
  1947. Client cli(host, port);
  1948. #endif
  1949. cli.set_connection_timeout(std::chrono::seconds(2));
  1950. auto res = cli.Get("/");
  1951. ASSERT_TRUE(!res);
  1952. EXPECT_EQ(Error::Connection, res.error());
  1953. }
  1954. TEST(ConnectionErrorTest, InvalidHost2) {
  1955. auto host = "httpcan.org/";
  1956. #ifdef CPPHTTPLIB_SSL_ENABLED
  1957. SSLClient cli(host);
  1958. #else
  1959. Client cli(host);
  1960. #endif
  1961. cli.set_connection_timeout(std::chrono::seconds(2));
  1962. auto res = cli.Get("/");
  1963. ASSERT_TRUE(!res);
  1964. EXPECT_EQ(Error::Connection, res.error());
  1965. }
  1966. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1967. auto host = "httpcan.org/";
  1968. #ifdef CPPHTTPLIB_SSL_ENABLED
  1969. SSLClient cli(host);
  1970. #else
  1971. Client cli(host);
  1972. #endif
  1973. cli.set_connection_timeout(std::chrono::seconds(2));
  1974. auto res = cli.Get("/");
  1975. ASSERT_TRUE(!res);
  1976. stringstream s;
  1977. s << "error code: " << res.error();
  1978. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1979. }
  1980. TEST(ConnectionErrorTest, InvalidPort) {
  1981. auto host = "localhost";
  1982. auto port = 44380;
  1983. #ifdef CPPHTTPLIB_SSL_ENABLED
  1984. SSLClient cli(host, port);
  1985. #else
  1986. Client cli(host, port);
  1987. #endif
  1988. cli.set_connection_timeout(std::chrono::seconds(2));
  1989. auto res = cli.Get("/");
  1990. ASSERT_TRUE(!res);
  1991. EXPECT_TRUE(Error::Connection == res.error() ||
  1992. Error::ConnectionTimeout == res.error());
  1993. }
  1994. TEST(ConnectionErrorTest, Timeout_Online) {
  1995. auto host = "google.com";
  1996. #ifdef CPPHTTPLIB_SSL_ENABLED
  1997. auto port = 44380;
  1998. SSLClient cli(host, port);
  1999. #else
  2000. auto port = 8080;
  2001. Client cli(host, port);
  2002. #endif
  2003. cli.set_connection_timeout(std::chrono::seconds(2));
  2004. // only probe one address type so that the error reason
  2005. // correlates to the timed-out IPv4, not the unsupported
  2006. // IPv6 connection attempt
  2007. cli.set_address_family(AF_INET);
  2008. auto res = cli.Get("/");
  2009. ASSERT_TRUE(!res);
  2010. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2011. }
  2012. TEST(CancelTest, NoCancel_Online) {
  2013. auto host = "httpbingo.org";
  2014. auto path = std::string{"/range/32"};
  2015. #ifdef CPPHTTPLIB_SSL_ENABLED
  2016. auto port = 443;
  2017. SSLClient cli(host, port);
  2018. #else
  2019. auto port = 80;
  2020. Client cli(host, port);
  2021. #endif
  2022. cli.set_connection_timeout(std::chrono::seconds(5));
  2023. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2025. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2026. EXPECT_EQ(StatusCode::OK_200, res->status);
  2027. }
  2028. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2029. // Use /bytes with a large payload so that the DownloadProgress callback
  2030. // (which only fires for Content-Length responses) is invoked before the
  2031. // entire body is received, giving cancellation a chance to fire.
  2032. auto host = "httpbingo.org";
  2033. auto path = std::string{"/bytes/524288"};
  2034. #ifdef CPPHTTPLIB_SSL_ENABLED
  2035. auto port = 443;
  2036. SSLClient cli(host, port);
  2037. #else
  2038. auto port = 80;
  2039. Client cli(host, port);
  2040. #endif
  2041. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2042. cli.set_connection_timeout(std::chrono::seconds(5));
  2043. ASSERT_TRUE(!res);
  2044. EXPECT_EQ(Error::Canceled, res.error());
  2045. }
  2046. TEST(CancelTest, WithCancelLargePayload_Online) {
  2047. auto host = "httpbingo.org";
  2048. auto path = std::string{"/bytes/524288"};
  2049. #ifdef CPPHTTPLIB_SSL_ENABLED
  2050. auto port = 443;
  2051. SSLClient cli(host, port);
  2052. #else
  2053. auto port = 80;
  2054. Client cli(host, port);
  2055. #endif
  2056. cli.set_connection_timeout(std::chrono::seconds(5));
  2057. uint32_t count = 0;
  2058. auto res =
  2059. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2060. ASSERT_TRUE(!res);
  2061. EXPECT_EQ(Error::Canceled, res.error());
  2062. }
  2063. TEST(CancelTest, NoCancelPost) {
  2064. Server svr;
  2065. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2066. res.set_content("Hello World!", "text/plain");
  2067. });
  2068. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2069. auto se = detail::scope_exit([&] {
  2070. svr.stop();
  2071. thread.join();
  2072. ASSERT_FALSE(svr.is_running());
  2073. });
  2074. svr.wait_until_ready();
  2075. Client cli(HOST, PORT);
  2076. cli.set_connection_timeout(std::chrono::seconds(5));
  2077. auto res =
  2078. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2079. "application/json", [](uint64_t, uint64_t) { return true; });
  2080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2081. EXPECT_EQ("Hello World!", res->body);
  2082. EXPECT_EQ(StatusCode::OK_200, res->status);
  2083. }
  2084. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2085. Server svr;
  2086. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2087. res.set_content("Hello World!", "text/plain");
  2088. });
  2089. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2090. auto se = detail::scope_exit([&] {
  2091. svr.stop();
  2092. thread.join();
  2093. ASSERT_FALSE(svr.is_running());
  2094. });
  2095. svr.wait_until_ready();
  2096. Client cli(HOST, PORT);
  2097. cli.set_connection_timeout(std::chrono::seconds(5));
  2098. auto res =
  2099. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2100. "application/json", [](uint64_t, uint64_t) { return false; });
  2101. ASSERT_TRUE(!res);
  2102. EXPECT_EQ(Error::Canceled, res.error());
  2103. }
  2104. TEST(CancelTest, WithCancelLargePayloadPost) {
  2105. Server svr;
  2106. svr.set_payload_max_length(200 * 1024 * 1024);
  2107. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2108. res.set_content(LARGE_DATA, "text/plain");
  2109. });
  2110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2111. auto se = detail::scope_exit([&] {
  2112. svr.stop();
  2113. thread.join();
  2114. ASSERT_FALSE(svr.is_running());
  2115. });
  2116. svr.wait_until_ready();
  2117. Client cli(HOST, PORT);
  2118. cli.set_payload_max_length(200 * 1024 * 1024);
  2119. cli.set_connection_timeout(std::chrono::seconds(5));
  2120. auto res =
  2121. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2122. "application/json", [](uint64_t, uint64_t) { return false; });
  2123. ASSERT_TRUE(!res);
  2124. EXPECT_EQ(Error::Canceled, res.error());
  2125. }
  2126. TEST(CancelTest, NoCancelPut) {
  2127. Server svr;
  2128. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2129. res.set_content("Hello World!", "text/plain");
  2130. });
  2131. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2132. auto se = detail::scope_exit([&] {
  2133. svr.stop();
  2134. thread.join();
  2135. ASSERT_FALSE(svr.is_running());
  2136. });
  2137. svr.wait_until_ready();
  2138. Client cli(HOST, PORT);
  2139. cli.set_connection_timeout(std::chrono::seconds(5));
  2140. auto res =
  2141. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2142. "application/json", [](uint64_t, uint64_t) { return true; });
  2143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2144. EXPECT_EQ("Hello World!", res->body);
  2145. EXPECT_EQ(StatusCode::OK_200, res->status);
  2146. }
  2147. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2148. Server svr;
  2149. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2150. res.set_content("Hello World!", "text/plain");
  2151. });
  2152. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2153. auto se = detail::scope_exit([&] {
  2154. svr.stop();
  2155. thread.join();
  2156. ASSERT_FALSE(svr.is_running());
  2157. });
  2158. svr.wait_until_ready();
  2159. Client cli(HOST, PORT);
  2160. cli.set_connection_timeout(std::chrono::seconds(5));
  2161. auto res =
  2162. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2163. "application/json", [](uint64_t, uint64_t) { return false; });
  2164. ASSERT_TRUE(!res);
  2165. EXPECT_EQ(Error::Canceled, res.error());
  2166. }
  2167. TEST(CancelTest, WithCancelLargePayloadPut) {
  2168. Server svr;
  2169. svr.set_payload_max_length(200 * 1024 * 1024);
  2170. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2171. res.set_content(LARGE_DATA, "text/plain");
  2172. });
  2173. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2174. auto se = detail::scope_exit([&] {
  2175. svr.stop();
  2176. thread.join();
  2177. ASSERT_FALSE(svr.is_running());
  2178. });
  2179. svr.wait_until_ready();
  2180. Client cli(HOST, PORT);
  2181. cli.set_payload_max_length(200 * 1024 * 1024);
  2182. cli.set_connection_timeout(std::chrono::seconds(5));
  2183. auto res =
  2184. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2185. "application/json", [](uint64_t, uint64_t) { return false; });
  2186. ASSERT_TRUE(!res);
  2187. EXPECT_EQ(Error::Canceled, res.error());
  2188. }
  2189. TEST(CancelTest, NoCancelPatch) {
  2190. Server svr;
  2191. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2192. res.set_content("Hello World!", "text/plain");
  2193. });
  2194. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2195. auto se = detail::scope_exit([&] {
  2196. svr.stop();
  2197. thread.join();
  2198. ASSERT_FALSE(svr.is_running());
  2199. });
  2200. svr.wait_until_ready();
  2201. Client cli(HOST, PORT);
  2202. cli.set_connection_timeout(std::chrono::seconds(5));
  2203. auto res =
  2204. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2205. "application/json", [](uint64_t, uint64_t) { return true; });
  2206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2207. EXPECT_EQ("Hello World!", res->body);
  2208. EXPECT_EQ(StatusCode::OK_200, res->status);
  2209. }
  2210. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2211. Server svr;
  2212. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2213. res.set_content("Hello World!", "text/plain");
  2214. });
  2215. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2216. auto se = detail::scope_exit([&] {
  2217. svr.stop();
  2218. thread.join();
  2219. ASSERT_FALSE(svr.is_running());
  2220. });
  2221. svr.wait_until_ready();
  2222. Client cli(HOST, PORT);
  2223. cli.set_connection_timeout(std::chrono::seconds(5));
  2224. auto res =
  2225. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2226. "application/json", [](uint64_t, uint64_t) { return false; });
  2227. ASSERT_TRUE(!res);
  2228. EXPECT_EQ(Error::Canceled, res.error());
  2229. }
  2230. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2231. Server svr;
  2232. svr.set_payload_max_length(200 * 1024 * 1024);
  2233. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2234. res.set_content(LARGE_DATA, "text/plain");
  2235. });
  2236. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2237. auto se = detail::scope_exit([&] {
  2238. svr.stop();
  2239. thread.join();
  2240. ASSERT_FALSE(svr.is_running());
  2241. });
  2242. svr.wait_until_ready();
  2243. Client cli(HOST, PORT);
  2244. cli.set_payload_max_length(200 * 1024 * 1024);
  2245. cli.set_connection_timeout(std::chrono::seconds(5));
  2246. auto res =
  2247. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2248. "application/json", [](uint64_t, uint64_t) { return false; });
  2249. ASSERT_TRUE(!res);
  2250. EXPECT_EQ(Error::Canceled, res.error());
  2251. }
  2252. TEST(CancelTest, NoCancelDelete) {
  2253. Server svr;
  2254. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2255. res.set_content("Hello World!", "text/plain");
  2256. });
  2257. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2258. auto se = detail::scope_exit([&] {
  2259. svr.stop();
  2260. thread.join();
  2261. ASSERT_FALSE(svr.is_running());
  2262. });
  2263. svr.wait_until_ready();
  2264. Client cli(HOST, PORT);
  2265. cli.set_connection_timeout(std::chrono::seconds(5));
  2266. auto res =
  2267. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2268. "application/json", [](uint64_t, uint64_t) { return true; });
  2269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2270. EXPECT_EQ("Hello World!", res->body);
  2271. EXPECT_EQ(StatusCode::OK_200, res->status);
  2272. }
  2273. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2274. Server svr;
  2275. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2276. res.set_content("Hello World!", "text/plain");
  2277. });
  2278. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2279. auto se = detail::scope_exit([&] {
  2280. svr.stop();
  2281. thread.join();
  2282. ASSERT_FALSE(svr.is_running());
  2283. });
  2284. svr.wait_until_ready();
  2285. Client cli(HOST, PORT);
  2286. cli.set_connection_timeout(std::chrono::seconds(5));
  2287. auto res =
  2288. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2289. "application/json", [](uint64_t, uint64_t) { return false; });
  2290. ASSERT_TRUE(!res);
  2291. EXPECT_EQ(Error::Canceled, res.error());
  2292. }
  2293. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2294. Server svr;
  2295. svr.set_payload_max_length(200 * 1024 * 1024);
  2296. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2297. res.set_content(LARGE_DATA, "text/plain");
  2298. });
  2299. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2300. auto se = detail::scope_exit([&] {
  2301. svr.stop();
  2302. thread.join();
  2303. ASSERT_FALSE(svr.is_running());
  2304. });
  2305. svr.wait_until_ready();
  2306. Client cli(HOST, PORT);
  2307. cli.set_payload_max_length(200 * 1024 * 1024);
  2308. cli.set_connection_timeout(std::chrono::seconds(5));
  2309. auto res =
  2310. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2311. "application/json", [](uint64_t, uint64_t) { return false; });
  2312. ASSERT_TRUE(!res);
  2313. EXPECT_EQ(Error::Canceled, res.error());
  2314. }
  2315. static std::string remove_whitespace(const std::string &input) {
  2316. std::string output;
  2317. output.reserve(input.size());
  2318. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2319. [](unsigned char c) { return !std::isspace(c); });
  2320. return output;
  2321. }
  2322. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2323. auto host = "httpbingo.org";
  2324. auto path = std::string{"/basic-auth/hello/world"};
  2325. #ifdef CPPHTTPLIB_SSL_ENABLED
  2326. auto port = 443;
  2327. SSLClient cli(host, port);
  2328. #else
  2329. auto port = 80;
  2330. Client cli(host, port);
  2331. #endif
  2332. {
  2333. auto res = cli.Get(path);
  2334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2335. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2336. }
  2337. {
  2338. auto res = cli.Get(
  2339. path, Headers{make_basic_authentication_header("hello", "world")});
  2340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2341. auto body = remove_whitespace(res->body);
  2342. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2343. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2344. EXPECT_EQ(StatusCode::OK_200, res->status);
  2345. }
  2346. {
  2347. cli.set_basic_auth("hello", "world");
  2348. auto res = cli.Get(path);
  2349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2350. auto body = remove_whitespace(res->body);
  2351. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2352. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2353. EXPECT_EQ(StatusCode::OK_200, res->status);
  2354. }
  2355. {
  2356. cli.set_basic_auth("hello", "bad");
  2357. auto res = cli.Get(path);
  2358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2359. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2360. }
  2361. {
  2362. cli.set_basic_auth("bad", "world");
  2363. auto res = cli.Get(path);
  2364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2365. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2366. }
  2367. }
  2368. #ifdef CPPHTTPLIB_SSL_ENABLED
  2369. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2370. auto host = "httpbingo.org";
  2371. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2372. auto paths = std::vector<std::string>{
  2373. "/digest-auth/auth/hello/world/MD5",
  2374. "/digest-auth/auth/hello/world/SHA-256",
  2375. };
  2376. auto port = 443;
  2377. SSLClient cli(host, port);
  2378. {
  2379. auto res = cli.Get(unauth_path);
  2380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2381. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2382. }
  2383. {
  2384. cli.set_digest_auth("hello", "world");
  2385. for (const auto &path : paths) {
  2386. auto res = cli.Get(path.c_str());
  2387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2388. auto body = remove_whitespace(res->body);
  2389. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2390. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2391. EXPECT_EQ(StatusCode::OK_200, res->status);
  2392. }
  2393. cli.set_digest_auth("hello", "bad");
  2394. for (const auto &path : paths) {
  2395. auto res = cli.Get(path.c_str());
  2396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2397. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2398. }
  2399. }
  2400. }
  2401. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2402. // comma-separated list of challenges, and each challenge may itself carry a
  2403. // comma-separated auth-param list, so a server can legally offer Basic
  2404. // before Digest, either as two field lines or packed into one. Runs one 401
  2405. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2406. // value() joins them in receipt order) and checks that the retry carries a
  2407. // well-formed Digest Authorization header naming expected_realm.
  2408. static void
  2409. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2410. const std::string &expected_realm) {
  2411. std::atomic<int> hits{0};
  2412. Server svr;
  2413. svr.Get("/x", [&](const Request &req, Response &res) {
  2414. if (++hits == 1) {
  2415. res.status = StatusCode::Unauthorized_401;
  2416. for (const auto &challenge : challenges) {
  2417. res.set_header("WWW-Authenticate", challenge);
  2418. }
  2419. } else {
  2420. auto authorization = req.get_header_value("Authorization");
  2421. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2422. EXPECT_NE(std::string::npos,
  2423. authorization.find("realm=\"" + expected_realm + "\""));
  2424. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2425. res.set_content("ok", "text/plain");
  2426. }
  2427. });
  2428. auto port = svr.bind_to_any_port(HOST);
  2429. std::thread t([&]() { svr.listen_after_bind(); });
  2430. auto se = detail::scope_exit([&] {
  2431. svr.stop();
  2432. t.join();
  2433. });
  2434. svr.wait_until_ready();
  2435. Client cli(HOST, port);
  2436. cli.set_digest_auth("hello", "world");
  2437. auto res = cli.Get("/x");
  2438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2439. EXPECT_EQ(2, hits.load());
  2440. }
  2441. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2442. static const char *kDigestChallenge =
  2443. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2444. "algorithm=MD5";
  2445. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2446. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2447. "testrealm");
  2448. }
  2449. // Same challenge list with the schemes in the opposite order, to make sure
  2450. // the fix above didn't just special-case "Basic first".
  2451. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2452. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2453. "testrealm");
  2454. }
  2455. // A comma inside a quoted auth-param value must not be mistaken for the
  2456. // separator between two challenges (or two auth-params).
  2457. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2458. run_digest_challenge_list_test(
  2459. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2460. "algorithm=MD5"},
  2461. "test,realm");
  2462. }
  2463. #endif
  2464. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2465. auto host = "google.com";
  2466. auto another_host = "example.com";
  2467. auto wrong_ip = "0.0.0.0";
  2468. #ifdef CPPHTTPLIB_SSL_ENABLED
  2469. SSLClient cli(host);
  2470. #else
  2471. Client cli(host);
  2472. #endif
  2473. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2474. auto res = cli.Get("/");
  2475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2476. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2477. }
  2478. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2479. auto host = "google.com";
  2480. auto wrong_ip = "0.0.0.0";
  2481. #ifdef CPPHTTPLIB_SSL_ENABLED
  2482. SSLClient cli(host);
  2483. #else
  2484. Client cli(host);
  2485. #endif
  2486. cli.set_hostname_addr_map({{host, wrong_ip}});
  2487. auto res = cli.Get("/");
  2488. ASSERT_TRUE(!res);
  2489. EXPECT_EQ(Error::Connection, res.error());
  2490. }
  2491. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2492. // A mapped value that is not an IP literal must be resolved. "localhost"
  2493. // resolves from the hosts file, so this test needs no external DNS.
  2494. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2495. auto host = "target.invalid";
  2496. Server svr;
  2497. std::string received_host;
  2498. svr.Get("/hi", [&](const Request &req, Response &res) {
  2499. received_host = req.get_header_value("Host");
  2500. res.set_content("Hello World!", "text/plain");
  2501. });
  2502. auto port = svr.bind_to_any_port(HOST);
  2503. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2504. auto se = detail::scope_exit([&] {
  2505. svr.stop();
  2506. thread.join();
  2507. ASSERT_FALSE(svr.is_running());
  2508. });
  2509. svr.wait_until_ready();
  2510. Client cli(host, port);
  2511. cli.set_hostname_addr_map({{host, HOST}});
  2512. auto res = cli.Get("/hi");
  2513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2514. EXPECT_EQ(StatusCode::OK_200, res->status);
  2515. // The mapping only redirects the connection; the identity stays host_.
  2516. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2517. }
  2518. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2519. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2520. auto host = "target.invalid";
  2521. Server svr;
  2522. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2523. res.set_content("Hello World!", "text/plain");
  2524. });
  2525. auto port = svr.bind_to_any_port("127.0.0.1");
  2526. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2527. auto se = detail::scope_exit([&] {
  2528. svr.stop();
  2529. thread.join();
  2530. ASSERT_FALSE(svr.is_running());
  2531. });
  2532. svr.wait_until_ready();
  2533. Client cli(host, port);
  2534. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2535. auto res = cli.Get("/hi");
  2536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2537. EXPECT_EQ(StatusCode::OK_200, res->status);
  2538. }
  2539. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2540. // An empty mapped value must leave host_ as the connection target. Without
  2541. // that guard the empty value would become the host argument, getaddrinfo
  2542. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2543. // loopback - silently connecting somewhere the caller never asked for.
  2544. // The server listens on loopback, so such a fallback would succeed and is
  2545. // therefore observable as a failure of this test.
  2546. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2547. Server svr;
  2548. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2549. res.set_content("Hello World!", "text/plain");
  2550. });
  2551. auto port = svr.bind_to_any_port(HOST);
  2552. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2553. auto se = detail::scope_exit([&] {
  2554. svr.stop();
  2555. thread.join();
  2556. ASSERT_FALSE(svr.is_running());
  2557. });
  2558. svr.wait_until_ready();
  2559. Client cli(blackhole, port);
  2560. cli.set_hostname_addr_map({{blackhole, ""}});
  2561. cli.set_connection_timeout(1);
  2562. auto res = cli.Get("/hi");
  2563. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2564. }
  2565. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2566. auto host = "httpbingo.org";
  2567. auto path = std::string{"/absolute-redirect/3"};
  2568. #ifdef CPPHTTPLIB_SSL_ENABLED
  2569. SSLClient cli(host);
  2570. #else
  2571. Client cli(host);
  2572. #endif
  2573. cli.set_follow_location(true);
  2574. auto res = cli.Get(path);
  2575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2576. EXPECT_EQ(StatusCode::OK_200, res->status);
  2577. }
  2578. TEST(RedirectTest, Redirect_Online) {
  2579. auto host = "httpbingo.org";
  2580. auto path = std::string{"/redirect/3"};
  2581. #ifdef CPPHTTPLIB_SSL_ENABLED
  2582. SSLClient cli(host);
  2583. #else
  2584. Client cli(host);
  2585. #endif
  2586. cli.set_follow_location(true);
  2587. auto res = cli.Get(path);
  2588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2589. EXPECT_EQ(StatusCode::OK_200, res->status);
  2590. }
  2591. TEST(RelativeRedirectTest, Redirect_Online) {
  2592. auto host = "httpbingo.org";
  2593. auto path = std::string{"/relative-redirect/3"};
  2594. #ifdef CPPHTTPLIB_SSL_ENABLED
  2595. SSLClient cli(host);
  2596. #else
  2597. Client cli(host);
  2598. #endif
  2599. cli.set_follow_location(true);
  2600. auto res = cli.Get(path);
  2601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2602. EXPECT_EQ(StatusCode::OK_200, res->status);
  2603. }
  2604. TEST(TooManyRedirectTest, Redirect_Online) {
  2605. auto host = "httpbingo.org";
  2606. auto path = std::string{"/redirect/21"};
  2607. #ifdef CPPHTTPLIB_SSL_ENABLED
  2608. SSLClient cli(host);
  2609. #else
  2610. Client cli(host);
  2611. #endif
  2612. cli.set_follow_location(true);
  2613. auto res = cli.Get(path);
  2614. ASSERT_TRUE(!res);
  2615. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2616. }
  2617. #ifdef CPPHTTPLIB_SSL_ENABLED
  2618. TEST(YahooRedirectTest, Redirect_Online) {
  2619. Client cli("yahoo.com");
  2620. auto res = cli.Get("/");
  2621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2622. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2623. cli.set_follow_location(true);
  2624. res = cli.Get("/");
  2625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2626. EXPECT_EQ(StatusCode::OK_200, res->status);
  2627. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2628. }
  2629. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2630. #define REDIR_HOST "httpbingo.org"
  2631. #define REDIR_PATH "/redirect-to"
  2632. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2633. SSLClient cli(REDIR_HOST);
  2634. cli.set_follow_location(true);
  2635. auto res =
  2636. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2638. EXPECT_EQ(StatusCode::OK_200, res->status);
  2639. }
  2640. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2641. SSLClient cli(REDIR_HOST);
  2642. cli.set_follow_location(true);
  2643. Params params;
  2644. params.emplace("url", "http://example.com");
  2645. params.emplace("status_code", "302");
  2646. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2648. EXPECT_EQ(StatusCode::OK_200, res->status);
  2649. }
  2650. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2651. SSLClient cli(REDIR_HOST);
  2652. cli.set_follow_location(true);
  2653. Params params;
  2654. params.emplace("url", "http://example.com");
  2655. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2657. EXPECT_EQ(StatusCode::OK_200, res->status);
  2658. }
  2659. TEST(UrlWithSpace, Redirect_Online) {
  2660. SSLClient cli("edge.forgecdn.net");
  2661. cli.set_follow_location(true);
  2662. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2664. EXPECT_EQ(StatusCode::OK_200, res->status);
  2665. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2666. }
  2667. #endif
  2668. #if !defined(_WIN32) && !defined(_WIN64)
  2669. TEST(ReceiveSignals, Signal) {
  2670. auto setupSignalHandlers = []() {
  2671. struct sigaction act;
  2672. sigemptyset(&act.sa_mask);
  2673. act.sa_flags = SA_SIGINFO;
  2674. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2675. switch (sig) {
  2676. case SIGINT:
  2677. default: break;
  2678. }
  2679. };
  2680. ::sigaction(SIGINT, &act, nullptr);
  2681. };
  2682. Server svr;
  2683. int port = 0;
  2684. auto thread = std::thread([&]() {
  2685. setupSignalHandlers();
  2686. port = svr.bind_to_any_port(HOST);
  2687. svr.listen_after_bind();
  2688. });
  2689. auto se = detail::scope_exit([&] {
  2690. svr.stop();
  2691. thread.join();
  2692. ASSERT_FALSE(svr.is_running());
  2693. });
  2694. svr.wait_until_ready();
  2695. ASSERT_TRUE(svr.is_running());
  2696. pthread_kill(thread.native_handle(), SIGINT);
  2697. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2698. ASSERT_TRUE(svr.is_running());
  2699. }
  2700. #endif
  2701. TEST(RedirectToDifferentPort, Redirect) {
  2702. Server svr1;
  2703. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2704. res.set_content("Hello World!", "text/plain");
  2705. });
  2706. int svr1_port = 0;
  2707. auto thread1 = std::thread([&]() {
  2708. svr1_port = svr1.bind_to_any_port(HOST);
  2709. svr1.listen_after_bind();
  2710. });
  2711. Server svr2;
  2712. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2713. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2714. });
  2715. int svr2_port = 0;
  2716. auto thread2 = std::thread([&]() {
  2717. svr2_port = svr2.bind_to_any_port(HOST);
  2718. svr2.listen_after_bind();
  2719. });
  2720. auto se = detail::scope_exit([&] {
  2721. svr2.stop();
  2722. thread2.join();
  2723. svr1.stop();
  2724. thread1.join();
  2725. ASSERT_FALSE(svr2.is_running());
  2726. ASSERT_FALSE(svr1.is_running());
  2727. });
  2728. svr1.wait_until_ready();
  2729. svr2.wait_until_ready();
  2730. Client cli("localhost", svr2_port);
  2731. cli.set_follow_location(true);
  2732. auto res = cli.Get("/2");
  2733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2734. EXPECT_EQ(StatusCode::OK_200, res->status);
  2735. EXPECT_EQ("Hello World!", res->body);
  2736. }
  2737. static void
  2738. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2739. Server svr1;
  2740. std::string captured_authorization;
  2741. svr1.Get("/target", [&](const Request &req, Response &res) {
  2742. captured_authorization = req.get_header_value("Authorization");
  2743. res.set_content("OK", "text/plain");
  2744. });
  2745. int svr1_port = 0;
  2746. auto thread1 = std::thread([&]() {
  2747. svr1_port = svr1.bind_to_any_port(HOST);
  2748. svr1.listen_after_bind();
  2749. });
  2750. Server svr2;
  2751. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2752. res.set_redirect(
  2753. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2754. });
  2755. int svr2_port = 0;
  2756. auto thread2 = std::thread([&]() {
  2757. svr2_port = svr2.bind_to_any_port(HOST);
  2758. svr2.listen_after_bind();
  2759. });
  2760. auto se = detail::scope_exit([&] {
  2761. svr2.stop();
  2762. thread2.join();
  2763. svr1.stop();
  2764. thread1.join();
  2765. ASSERT_FALSE(svr2.is_running());
  2766. ASSERT_FALSE(svr1.is_running());
  2767. });
  2768. svr1.wait_until_ready();
  2769. svr2.wait_until_ready();
  2770. Client cli("localhost", svr2_port);
  2771. cli.set_follow_location(true);
  2772. set_auth(cli);
  2773. auto res = cli.Get("/redir");
  2774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2775. EXPECT_EQ(StatusCode::OK_200, res->status);
  2776. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2777. EXPECT_TRUE(captured_authorization.empty());
  2778. }
  2779. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2780. TestDoNotForwardCredentialsOnRedirect(
  2781. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2782. }
  2783. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2784. TestDoNotForwardCredentialsOnRedirect(
  2785. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2786. }
  2787. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2788. Server svr1;
  2789. std::string captured_cookie;
  2790. bool target_hit = false;
  2791. svr1.Get("/target", [&](const Request &req, Response &res) {
  2792. captured_cookie = req.get_header_value("Cookie");
  2793. target_hit = true;
  2794. res.set_content("OK", "text/plain");
  2795. });
  2796. int svr1_port = 0;
  2797. auto thread1 = std::thread([&]() {
  2798. svr1_port = svr1.bind_to_any_port(HOST);
  2799. svr1.listen_after_bind();
  2800. });
  2801. Server svr2;
  2802. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2803. res.set_redirect(
  2804. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2805. });
  2806. int svr2_port = 0;
  2807. auto thread2 = std::thread([&]() {
  2808. svr2_port = svr2.bind_to_any_port(HOST);
  2809. svr2.listen_after_bind();
  2810. });
  2811. auto se = detail::scope_exit([&] {
  2812. svr2.stop();
  2813. thread2.join();
  2814. svr1.stop();
  2815. thread1.join();
  2816. ASSERT_FALSE(svr2.is_running());
  2817. ASSERT_FALSE(svr1.is_running());
  2818. });
  2819. svr1.wait_until_ready();
  2820. svr2.wait_until_ready();
  2821. Client cli("localhost", svr2_port);
  2822. cli.set_follow_location(true);
  2823. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2824. auto res = cli.Get("/redir", headers);
  2825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2826. EXPECT_EQ(StatusCode::OK_200, res->status);
  2827. EXPECT_TRUE(target_hit);
  2828. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2829. EXPECT_TRUE(captured_cookie.empty());
  2830. }
  2831. TEST(RedirectToSamePort, ForwardCookie) {
  2832. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2833. // header so that ordinary session flows keep working.
  2834. Server svr;
  2835. std::string captured_cookie;
  2836. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2837. res.set_redirect("/target", 302);
  2838. });
  2839. svr.Get("/target", [&](const Request &req, Response &res) {
  2840. captured_cookie = req.get_header_value("Cookie");
  2841. res.set_content("OK", "text/plain");
  2842. });
  2843. auto port = svr.bind_to_any_port(HOST);
  2844. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2845. auto se = detail::scope_exit([&] {
  2846. svr.stop();
  2847. thread.join();
  2848. ASSERT_FALSE(svr.is_running());
  2849. });
  2850. svr.wait_until_ready();
  2851. Client cli(HOST, port);
  2852. cli.set_follow_location(true);
  2853. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2854. auto res = cli.Get("/redir", headers);
  2855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2856. EXPECT_EQ(StatusCode::OK_200, res->status);
  2857. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2858. }
  2859. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2860. Server svr;
  2861. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2862. // Port number that overflows int — should not crash
  2863. res.set_redirect("http://localhost:99999999999999999999/target");
  2864. });
  2865. auto port = svr.bind_to_any_port(HOST);
  2866. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2867. auto se = detail::scope_exit([&] {
  2868. svr.stop();
  2869. thread.join();
  2870. ASSERT_FALSE(svr.is_running());
  2871. });
  2872. svr.wait_until_ready();
  2873. Client cli(HOST, port);
  2874. cli.set_follow_location(true);
  2875. auto res = cli.Get("/redir");
  2876. // Should fail gracefully, not crash (no valid response due to bad port)
  2877. EXPECT_FALSE(res);
  2878. }
  2879. TEST(RedirectFromPageWithContent, Redirect) {
  2880. Server svr;
  2881. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2882. res.set_content("___", "text/plain");
  2883. res.set_redirect("/2");
  2884. });
  2885. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2886. res.set_content("Hello World!", "text/plain");
  2887. });
  2888. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2889. auto se = detail::scope_exit([&] {
  2890. svr.stop();
  2891. th.join();
  2892. ASSERT_FALSE(svr.is_running());
  2893. });
  2894. svr.wait_until_ready();
  2895. {
  2896. Client cli("localhost", PORT);
  2897. cli.set_follow_location(true);
  2898. std::string body;
  2899. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2900. body.append(data, data_length);
  2901. return true;
  2902. });
  2903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2904. EXPECT_EQ(StatusCode::OK_200, res->status);
  2905. EXPECT_EQ("Hello World!", body);
  2906. }
  2907. {
  2908. Client cli("localhost", PORT);
  2909. std::string body;
  2910. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2911. body.append(data, data_length);
  2912. return true;
  2913. });
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::Found_302, res->status);
  2916. EXPECT_EQ("___", body);
  2917. }
  2918. }
  2919. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2920. Server svr;
  2921. auto port_str = std::to_string(PORT);
  2922. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2923. auto expected_host = "[::1]:" + port_str;
  2924. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2925. res.set_content("___", "text/plain");
  2926. // res.set_redirect("/2");
  2927. res.set_redirect(redirect_url);
  2928. });
  2929. svr.Get("/2", [&](const Request &req, Response &res) {
  2930. auto host_header = req.headers.find("Host");
  2931. ASSERT_TRUE(host_header != req.headers.end());
  2932. EXPECT_EQ(expected_host, host_header->second);
  2933. res.set_content("Hello World!", "text/plain");
  2934. });
  2935. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2936. auto se = detail::scope_exit([&] {
  2937. svr.stop();
  2938. th.join();
  2939. ASSERT_FALSE(svr.is_running());
  2940. });
  2941. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2942. // actually starts anything, so the condition !svr.is_running() will
  2943. // always remain true, and the loop never stops.
  2944. // This basically counts how many milliseconds have passed since the
  2945. // call to svr.listen(), and if after 5 seconds nothing started yet
  2946. // aborts the test.
  2947. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2948. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2949. ASSERT_LT(milliseconds, 5000U);
  2950. }
  2951. {
  2952. Client cli("::1", PORT);
  2953. cli.set_follow_location(true);
  2954. std::string body;
  2955. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2956. body.append(data, data_length);
  2957. return true;
  2958. });
  2959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2960. EXPECT_EQ(StatusCode::OK_200, res->status);
  2961. EXPECT_EQ("Hello World!", body);
  2962. }
  2963. {
  2964. Client cli("::1", PORT);
  2965. std::string body;
  2966. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2967. body.append(data, data_length);
  2968. return true;
  2969. });
  2970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2971. EXPECT_EQ(StatusCode::Found_302, res->status);
  2972. EXPECT_EQ("___", body);
  2973. }
  2974. }
  2975. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2976. Server svr;
  2977. svr.Get("/foo", [](const Request &req, Response &res) {
  2978. auto a = req.params.find("a");
  2979. if (a != req.params.end()) {
  2980. res.set_content((*a).second, "text/plain");
  2981. res.status = StatusCode::OK_200;
  2982. } else {
  2983. res.status = StatusCode::BadRequest_400;
  2984. }
  2985. });
  2986. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2987. auto se = detail::scope_exit([&] {
  2988. svr.stop();
  2989. thread.join();
  2990. ASSERT_FALSE(svr.is_running());
  2991. });
  2992. svr.wait_until_ready();
  2993. {
  2994. Client cli(HOST, PORT);
  2995. cli.set_path_encode(false);
  2996. auto res = cli.Get("/foo?a=explicitly+encoded");
  2997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2998. EXPECT_EQ(StatusCode::OK_200, res->status);
  2999. // This expects it back with a space, as the `+` won't have been
  3000. // url-encoded, and server-side the params get decoded turning `+`
  3001. // into spaces.
  3002. EXPECT_EQ("explicitly encoded", res->body);
  3003. }
  3004. }
  3005. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3006. // When path encoding is disabled the client must transmit the supplied
  3007. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3008. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3009. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3010. // than a space (0x20). Assert on the raw wire target to catch this.
  3011. Server svr;
  3012. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3013. svr.Get("/foo", [&](const Request &req, Response &res) {
  3014. EXPECT_EQ(expected_target, req.target);
  3015. res.status = StatusCode::OK_200;
  3016. });
  3017. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3018. auto se = detail::scope_exit([&] {
  3019. svr.stop();
  3020. thread.join();
  3021. ASSERT_FALSE(svr.is_running());
  3022. });
  3023. svr.wait_until_ready();
  3024. {
  3025. Client cli(HOST, PORT);
  3026. cli.set_path_encode(false);
  3027. auto res = cli.Get(expected_target.c_str());
  3028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3029. EXPECT_EQ(StatusCode::OK_200, res->status);
  3030. }
  3031. }
  3032. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3033. // `open_stream()` used to skip the path encoding that the buffered send
  3034. // path applies, so the same `path` produced different bytes in the request
  3035. // line depending on which API was used. Assert the two agree.
  3036. Server svr;
  3037. std::string target;
  3038. svr.Get(".*", [&](const Request &req, Response &res) {
  3039. target = req.target;
  3040. res.status = StatusCode::OK_200;
  3041. });
  3042. auto port = svr.bind_to_any_port(HOST);
  3043. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3044. auto se = detail::scope_exit([&] {
  3045. svr.stop();
  3046. thread.join();
  3047. ASSERT_FALSE(svr.is_running());
  3048. });
  3049. svr.wait_until_ready();
  3050. struct {
  3051. const char *path;
  3052. const char *expected;
  3053. } cases[] = {
  3054. {"/a b?x=1", "/a%20b?x=1"},
  3055. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3056. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3057. };
  3058. for (const auto &c : cases) {
  3059. Client cli(HOST, port);
  3060. target.clear();
  3061. auto res = cli.Get(c.path);
  3062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3063. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3064. auto buffered_target = target;
  3065. target.clear();
  3066. auto handle = cli.open_stream("GET", c.path);
  3067. EXPECT_TRUE(handle.is_valid())
  3068. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3069. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3070. }
  3071. }
  3072. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3073. // The `set_path_encode(false)` contract — transmit the supplied target
  3074. // verbatim — must hold for the streaming API too.
  3075. Server svr;
  3076. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3077. std::string target;
  3078. svr.Get("/foo", [&](const Request &req, Response &res) {
  3079. target = req.target;
  3080. res.status = StatusCode::OK_200;
  3081. });
  3082. auto port = svr.bind_to_any_port(HOST);
  3083. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3084. auto se = detail::scope_exit([&] {
  3085. svr.stop();
  3086. thread.join();
  3087. ASSERT_FALSE(svr.is_running());
  3088. });
  3089. svr.wait_until_ready();
  3090. {
  3091. Client cli(HOST, port);
  3092. cli.set_path_encode(false);
  3093. auto handle = cli.open_stream("GET", expected_target);
  3094. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3095. EXPECT_EQ(expected_target, target);
  3096. }
  3097. }
  3098. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3099. // With path encoding enabled a CR/LF in the target is percent-encoded
  3100. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3101. // write_request_line still backstops `set_path_encode(false)`, which is
  3102. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3103. Server svr;
  3104. // Captured before routing: the decoded path contains a newline, which a
  3105. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3106. std::string target;
  3107. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3108. target = req.target;
  3109. res.status = StatusCode::OK_200;
  3110. return Server::HandlerResponse::Handled;
  3111. });
  3112. auto port = svr.bind_to_any_port(HOST);
  3113. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3114. auto se = detail::scope_exit([&] {
  3115. svr.stop();
  3116. thread.join();
  3117. ASSERT_FALSE(svr.is_running());
  3118. });
  3119. svr.wait_until_ready();
  3120. {
  3121. Client cli(HOST, port);
  3122. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3123. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3124. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3125. }
  3126. }
  3127. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3128. // Nothing may reach the wire: a raw CR/LF target would split the request
  3129. // line and inject headers.
  3130. Server svr;
  3131. // Pre-routing so that "not called" means nothing reached the server at all,
  3132. // rather than merely failing to match a handler pattern.
  3133. auto handler_called = false;
  3134. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3135. handler_called = true;
  3136. res.status = StatusCode::OK_200;
  3137. return Server::HandlerResponse::Handled;
  3138. });
  3139. auto port = svr.bind_to_any_port(HOST);
  3140. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3141. auto se = detail::scope_exit([&] {
  3142. svr.stop();
  3143. thread.join();
  3144. ASSERT_FALSE(svr.is_running());
  3145. });
  3146. svr.wait_until_ready();
  3147. {
  3148. Client cli(HOST, port);
  3149. cli.set_path_encode(false);
  3150. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3151. EXPECT_FALSE(handle.is_valid());
  3152. EXPECT_EQ(Error::Write, handle.error);
  3153. EXPECT_FALSE(handler_called);
  3154. }
  3155. }
  3156. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3157. // Which of the two branches runs is decided by whether the query component
  3158. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3159. // an empty query and must still fall back to building one from
  3160. // `req.params`, while a non-empty query must win over `req.params`.
  3161. Server svr;
  3162. std::string target;
  3163. svr.Get("/foo", [&](const Request &req, Response &res) {
  3164. target = req.target;
  3165. res.status = StatusCode::OK_200;
  3166. });
  3167. auto port = svr.bind_to_any_port(HOST);
  3168. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3169. auto se = detail::scope_exit([&] {
  3170. svr.stop();
  3171. thread.join();
  3172. ASSERT_FALSE(svr.is_running());
  3173. });
  3174. svr.wait_until_ready();
  3175. {
  3176. // Trailing `?` -> empty query component -> `req.params` is used.
  3177. Client cli(HOST, port);
  3178. Request req;
  3179. req.method = "GET";
  3180. req.path = "/foo?";
  3181. req.params.emplace("a", "1");
  3182. target.clear();
  3183. auto res = cli.send(req);
  3184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3185. EXPECT_EQ("/foo?a=1", target);
  3186. }
  3187. {
  3188. // Non-empty query in `req.path` -> `req.params` is not appended.
  3189. Client cli(HOST, port);
  3190. Request req;
  3191. req.method = "GET";
  3192. req.path = "/foo?b=2";
  3193. req.params.emplace("a", "1");
  3194. target.clear();
  3195. auto res = cli.send(req);
  3196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3197. EXPECT_EQ("/foo?b=2", target);
  3198. }
  3199. }
  3200. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3201. Server svr;
  3202. svr.Get("/", [](const Request &req, Response &) {
  3203. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3204. });
  3205. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3206. auto se = detail::scope_exit([&] {
  3207. svr.stop();
  3208. thread.join();
  3209. ASSERT_FALSE(svr.is_running());
  3210. });
  3211. svr.wait_until_ready();
  3212. {
  3213. Client cli(HOST, PORT);
  3214. cli.set_path_encode(false);
  3215. auto res = cli.Get("/?something=%0A");
  3216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3217. EXPECT_EQ(StatusCode::OK_200, res->status);
  3218. }
  3219. }
  3220. TEST(BindServerTest, BindDualStack) {
  3221. Server svr;
  3222. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3223. res.set_content("Hello World!", "text/plain");
  3224. });
  3225. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3226. auto se = detail::scope_exit([&] {
  3227. svr.stop();
  3228. thread.join();
  3229. ASSERT_FALSE(svr.is_running());
  3230. });
  3231. svr.wait_until_ready();
  3232. {
  3233. Client cli("127.0.0.1", PORT);
  3234. auto res = cli.Get("/1");
  3235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3236. EXPECT_EQ(StatusCode::OK_200, res->status);
  3237. EXPECT_EQ("Hello World!", res->body);
  3238. }
  3239. {
  3240. Client cli("::1", PORT);
  3241. auto res = cli.Get("/1");
  3242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3243. EXPECT_EQ(StatusCode::OK_200, res->status);
  3244. EXPECT_EQ("Hello World!", res->body);
  3245. }
  3246. }
  3247. TEST(BindServerTest, BindAndListenSeparately) {
  3248. Server svr;
  3249. int port = svr.bind_to_any_port("0.0.0.0");
  3250. ASSERT_TRUE(svr.is_valid());
  3251. ASSERT_TRUE(port > 0);
  3252. svr.stop();
  3253. }
  3254. // Reports whether anything is still listening on a loopback port. A plain
  3255. // connect() is used instead of a Client request because a socket left bound by
  3256. // mistake accepts the connection into its backlog and never answers, which
  3257. // would hang the test instead of failing it.
  3258. static bool is_loopback_port_accepting(int port) {
  3259. sockaddr_in addr{};
  3260. addr.sin_family = AF_INET;
  3261. addr.sin_port = htons(static_cast<uint16_t>(port));
  3262. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3263. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3264. EXPECT_NE(sock, INVALID_SOCKET);
  3265. if (sock == INVALID_SOCKET) { return false; }
  3266. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3267. static_cast<socklen_t>(sizeof(addr)));
  3268. detail::close_socket(sock);
  3269. return ret == 0;
  3270. }
  3271. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3272. Server svr;
  3273. auto port = svr.bind_to_any_port("127.0.0.1");
  3274. ASSERT_TRUE(port > 0);
  3275. svr.stop();
  3276. // bind_to_any_port() already called listen(2), so until stop() closed the
  3277. // descriptor the port kept accepting connections into the backlog. ASSERT
  3278. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3279. // below blocks forever in the accept loop.
  3280. ASSERT_FALSE(is_loopback_port_accepting(port));
  3281. // Nothing is left to accept on, so listen_after_bind() must report failure
  3282. // instead of returning success without ever serving.
  3283. EXPECT_FALSE(svr.listen_after_bind());
  3284. // The failed listen marks the server decommissioned, so a waiter returns
  3285. // instead of spinning forever.
  3286. svr.wait_until_ready();
  3287. }
  3288. #ifdef CPPHTTPLIB_SSL_ENABLED
  3289. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3290. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3291. CLIENT_CA_CERT_DIR);
  3292. int port = svr.bind_to_any_port("0.0.0.0");
  3293. ASSERT_TRUE(svr.is_valid());
  3294. ASSERT_TRUE(port > 0);
  3295. svr.stop();
  3296. }
  3297. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3298. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3299. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3300. int port = svr.bind_to_any_port("0.0.0.0");
  3301. ASSERT_TRUE(svr.is_valid());
  3302. ASSERT_TRUE(port > 0);
  3303. svr.stop();
  3304. }
  3305. TEST(BindServerTest, UpdateCertsPem) {
  3306. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3307. int port = svr.bind_to_any_port("0.0.0.0");
  3308. ASSERT_TRUE(svr.is_valid());
  3309. ASSERT_TRUE(port > 0);
  3310. // Read PEM files
  3311. std::string cert_pem, key_pem, ca_pem;
  3312. read_file(SERVER_CERT_FILE, cert_pem);
  3313. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3314. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3315. // Update server certificates using PEM API
  3316. ASSERT_TRUE(
  3317. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3318. ASSERT_TRUE(svr.is_valid());
  3319. svr.stop();
  3320. }
  3321. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3322. // Start server with client CA (enables client auth)
  3323. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3324. ASSERT_TRUE(svr.is_valid());
  3325. bool handler_called = false;
  3326. svr.Get("/test", [&](const Request &req, Response &res) {
  3327. handler_called = true;
  3328. // Verify client certificate is present
  3329. auto cert = req.peer_cert();
  3330. EXPECT_TRUE(static_cast<bool>(cert));
  3331. res.set_content("ok", "text/plain");
  3332. });
  3333. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3334. auto se = detail::scope_exit([&] {
  3335. svr.stop();
  3336. t.join();
  3337. ASSERT_FALSE(svr.is_running());
  3338. });
  3339. svr.wait_until_ready();
  3340. // Read PEM files
  3341. std::string cert_pem, key_pem, ca_pem;
  3342. read_file(SERVER_CERT_FILE, cert_pem);
  3343. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3344. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3345. // Update server certificates and client CA using PEM API while server running
  3346. ASSERT_TRUE(
  3347. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3348. // Connect with client certificate
  3349. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3350. cli.enable_server_certificate_verification(false);
  3351. cli.set_connection_timeout(30);
  3352. auto res = cli.Get("/test");
  3353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3354. ASSERT_EQ(StatusCode::OK_200, res->status);
  3355. ASSERT_TRUE(handler_called);
  3356. EXPECT_EQ("ok", res->body);
  3357. }
  3358. #endif
  3359. TEST(ErrorHandlerTest, ContentLength) {
  3360. Server svr;
  3361. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3362. res.status = StatusCode::OK_200;
  3363. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3364. "text/html"); // <= Content-Length still 13
  3365. });
  3366. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3367. res.set_content("Hello World!\n", "text/plain");
  3368. res.status = 524;
  3369. });
  3370. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3371. auto se = detail::scope_exit([&] {
  3372. svr.stop();
  3373. thread.join();
  3374. ASSERT_FALSE(svr.is_running());
  3375. });
  3376. svr.wait_until_ready();
  3377. {
  3378. Client cli(HOST, PORT);
  3379. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3381. EXPECT_EQ(StatusCode::OK_200, res->status);
  3382. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3383. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3384. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3385. }
  3386. }
  3387. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3388. TEST(ExceptionTest, WithoutExceptionHandler) {
  3389. Server svr;
  3390. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3391. throw std::runtime_error("exception...");
  3392. });
  3393. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3394. throw std::runtime_error("exception\r\n...");
  3395. });
  3396. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3397. auto se = detail::scope_exit([&] {
  3398. svr.stop();
  3399. listen_thread.join();
  3400. ASSERT_FALSE(svr.is_running());
  3401. });
  3402. svr.wait_until_ready();
  3403. Client cli("localhost", PORT);
  3404. {
  3405. auto res = cli.Get("/exception");
  3406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3407. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3408. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3409. }
  3410. {
  3411. auto res = cli.Get("/unknown");
  3412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3413. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3414. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3415. }
  3416. }
  3417. TEST(ExceptionTest, WithExceptionHandler) {
  3418. Server svr;
  3419. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3420. std::exception_ptr ep) {
  3421. EXPECT_FALSE(ep == nullptr);
  3422. try {
  3423. std::rethrow_exception(ep);
  3424. } catch (std::exception &e) {
  3425. EXPECT_EQ("abc", std::string(e.what()));
  3426. } catch (...) {}
  3427. res.status = StatusCode::InternalServerError_500;
  3428. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3429. "text/html"); // <= Content-Length still 13 at this point
  3430. });
  3431. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3432. res.set_content("Hello World!\n", "text/plain");
  3433. throw std::runtime_error("abc");
  3434. });
  3435. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3436. auto se = detail::scope_exit([&] {
  3437. svr.stop();
  3438. thread.join();
  3439. ASSERT_FALSE(svr.is_running());
  3440. });
  3441. svr.wait_until_ready();
  3442. for (size_t i = 0; i < 10; i++) {
  3443. Client cli(HOST, PORT);
  3444. for (size_t j = 0; j < 100; j++) {
  3445. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3447. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3448. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3449. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3450. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3451. }
  3452. cli.set_keep_alive(true);
  3453. for (size_t j = 0; j < 100; j++) {
  3454. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3456. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3457. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3458. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3459. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3460. }
  3461. }
  3462. }
  3463. TEST(ExceptionTest, AndErrorHandler) {
  3464. Server svr;
  3465. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3466. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3467. });
  3468. svr.set_exception_handler(
  3469. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3470. EXPECT_FALSE(ep == nullptr);
  3471. try {
  3472. std::rethrow_exception(ep);
  3473. } catch (std::exception &e) {
  3474. res.set_content(e.what(), "text/html");
  3475. } catch (...) {}
  3476. res.status = StatusCode::InternalServerError_500;
  3477. });
  3478. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3479. throw std::runtime_error("EXCEPTION");
  3480. });
  3481. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3482. res.set_content("ERROR", "text/html");
  3483. res.status = StatusCode::InternalServerError_500;
  3484. });
  3485. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3486. auto se = detail::scope_exit([&] {
  3487. svr.stop();
  3488. thread.join();
  3489. ASSERT_FALSE(svr.is_running());
  3490. });
  3491. svr.wait_until_ready();
  3492. Client cli(HOST, PORT);
  3493. {
  3494. auto res = cli.Get("/exception");
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3497. EXPECT_EQ("EXCEPTION", res->body);
  3498. }
  3499. {
  3500. auto res = cli.Get("/error");
  3501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3502. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3503. EXPECT_EQ("ERROR", res->body);
  3504. }
  3505. {
  3506. auto res = cli.Get("/invalid");
  3507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3508. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3509. EXPECT_EQ("NOT_FOUND", res->body);
  3510. }
  3511. }
  3512. #endif
  3513. TEST(NoContentTest, ContentLength) {
  3514. Server svr;
  3515. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3516. res.status = StatusCode::NoContent_204;
  3517. });
  3518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3519. auto se = detail::scope_exit([&] {
  3520. svr.stop();
  3521. thread.join();
  3522. ASSERT_FALSE(svr.is_running());
  3523. });
  3524. svr.wait_until_ready();
  3525. {
  3526. Client cli(HOST, PORT);
  3527. auto res = cli.Get("/hi");
  3528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3529. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3530. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3531. }
  3532. }
  3533. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3534. #ifdef CPPHTTPLIB_SSL_ENABLED
  3535. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3536. ASSERT_TRUE(svr.is_valid());
  3537. #else
  3538. Server svr;
  3539. #endif
  3540. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3541. if (req.path == "/routing_handler") {
  3542. res.set_header("PRE_ROUTING", "on");
  3543. res.set_content("Routing Handler", "text/plain");
  3544. return httplib::Server::HandlerResponse::Handled;
  3545. }
  3546. return httplib::Server::HandlerResponse::Unhandled;
  3547. });
  3548. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3549. res.set_content("Error", "text/html");
  3550. });
  3551. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3552. if (req.path == "/routing_handler") {
  3553. res.set_header("POST_ROUTING", "on");
  3554. }
  3555. });
  3556. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3557. res.set_content("Hello World!\n", "text/plain");
  3558. });
  3559. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3560. auto se = detail::scope_exit([&] {
  3561. svr.stop();
  3562. thread.join();
  3563. ASSERT_FALSE(svr.is_running());
  3564. });
  3565. svr.wait_until_ready();
  3566. {
  3567. #ifdef CPPHTTPLIB_SSL_ENABLED
  3568. SSLClient cli(HOST, PORT);
  3569. cli.enable_server_certificate_verification(false);
  3570. #else
  3571. Client cli(HOST, PORT);
  3572. #endif
  3573. auto res = cli.Get("/routing_handler");
  3574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3575. EXPECT_EQ(StatusCode::OK_200, res->status);
  3576. EXPECT_EQ("Routing Handler", res->body);
  3577. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3578. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3579. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3580. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3581. }
  3582. {
  3583. #ifdef CPPHTTPLIB_SSL_ENABLED
  3584. SSLClient cli(HOST, PORT);
  3585. cli.enable_server_certificate_verification(false);
  3586. #else
  3587. Client cli(HOST, PORT);
  3588. #endif
  3589. auto res = cli.Get("/hi");
  3590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3591. EXPECT_EQ(StatusCode::OK_200, res->status);
  3592. EXPECT_EQ("Hello World!\n", res->body);
  3593. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3594. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3595. }
  3596. {
  3597. #ifdef CPPHTTPLIB_SSL_ENABLED
  3598. SSLClient cli(HOST, PORT);
  3599. cli.enable_server_certificate_verification(false);
  3600. #else
  3601. Client cli(HOST, PORT);
  3602. #endif
  3603. auto res = cli.Get("/aaa");
  3604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3605. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3606. EXPECT_EQ("Error", res->body);
  3607. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3608. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3609. }
  3610. }
  3611. TEST(RequestHandlerTest, PreRequestHandler) {
  3612. auto route_path = "/user/:user";
  3613. Server svr;
  3614. svr.Get("/hi", [](const Request &, Response &res) {
  3615. res.set_content("hi", "text/plain");
  3616. });
  3617. svr.Get(route_path, [](const Request &req, Response &res) {
  3618. res.set_content(req.path_params.at("user"), "text/plain");
  3619. });
  3620. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3621. if (req.matched_route == route_path) {
  3622. auto user = req.path_params.at("user");
  3623. if (user != "john") {
  3624. res.status = StatusCode::Forbidden_403;
  3625. res.set_content("error", "text/html");
  3626. return Server::HandlerResponse::Handled;
  3627. }
  3628. }
  3629. return Server::HandlerResponse::Unhandled;
  3630. });
  3631. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3632. auto se = detail::scope_exit([&] {
  3633. svr.stop();
  3634. thread.join();
  3635. ASSERT_FALSE(svr.is_running());
  3636. });
  3637. svr.wait_until_ready();
  3638. Client cli(HOST, PORT);
  3639. {
  3640. auto res = cli.Get("/hi");
  3641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3642. EXPECT_EQ(StatusCode::OK_200, res->status);
  3643. EXPECT_EQ("hi", res->body);
  3644. }
  3645. {
  3646. auto res = cli.Get("/user/john");
  3647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3648. EXPECT_EQ(StatusCode::OK_200, res->status);
  3649. EXPECT_EQ("john", res->body);
  3650. }
  3651. {
  3652. auto res = cli.Get("/user/invalid-user");
  3653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3654. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3655. EXPECT_EQ("error", res->body);
  3656. }
  3657. }
  3658. // The pre-request handler must run before the request body is read, so a
  3659. // rejected request never forces the server to buffer a (potentially large)
  3660. // body. Here the posted body is larger than the payload limit: if the body
  3661. // were read first the server would answer 413, but because the pre-request
  3662. // handler runs first it answers 403 and the body is never read.
  3663. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3664. Server svr;
  3665. svr.set_payload_max_length(8);
  3666. auto handler_ran = false;
  3667. svr.Post("/reject", [&](const Request &req, Response &res) {
  3668. handler_ran = true;
  3669. res.set_content(req.body, "text/plain");
  3670. });
  3671. svr.Post("/accept", [](const Request &req, Response &res) {
  3672. res.set_content(req.body, "text/plain");
  3673. });
  3674. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3675. if (req.matched_route == "/reject") {
  3676. res.status = StatusCode::Forbidden_403;
  3677. res.set_content("denied", "text/plain");
  3678. return Server::HandlerResponse::Handled;
  3679. }
  3680. return Server::HandlerResponse::Unhandled;
  3681. });
  3682. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3683. auto se = detail::scope_exit([&] {
  3684. svr.stop();
  3685. thread.join();
  3686. ASSERT_FALSE(svr.is_running());
  3687. });
  3688. svr.wait_until_ready();
  3689. Client cli(HOST, PORT);
  3690. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3691. // rejects with 403 before the body is read, so 413 is never reached.
  3692. {
  3693. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3695. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3696. EXPECT_EQ("denied", res->body);
  3697. EXPECT_FALSE(handler_ran);
  3698. }
  3699. // An approved route still reads the body and enforces the payload limit.
  3700. {
  3701. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3703. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3704. }
  3705. }
  3706. TEST(UserDataTest, BasicOperations) {
  3707. httplib::UserData ud;
  3708. // Initially empty
  3709. EXPECT_FALSE(ud.has("key"));
  3710. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3711. // set and get
  3712. ud.set("key", 42);
  3713. EXPECT_TRUE(ud.has("key"));
  3714. auto *p = ud.get<int>("key");
  3715. ASSERT_NE(nullptr, p);
  3716. EXPECT_EQ(42, *p);
  3717. // Type mismatch → nullptr
  3718. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3719. // Overwrite with different type
  3720. ud.set("key", std::string("hello"));
  3721. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3722. auto *s = ud.get<std::string>("key");
  3723. ASSERT_NE(nullptr, s);
  3724. EXPECT_EQ("hello", *s);
  3725. // erase
  3726. ud.erase("key");
  3727. EXPECT_FALSE(ud.has("key"));
  3728. // clear
  3729. ud.set("a", 1);
  3730. ud.set("b", 2);
  3731. ud.clear();
  3732. EXPECT_FALSE(ud.has("a"));
  3733. EXPECT_FALSE(ud.has("b"));
  3734. }
  3735. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3736. struct AuthCtx {
  3737. std::string user_id;
  3738. };
  3739. Server svr;
  3740. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3741. res.user_data.set("auth", AuthCtx{"alice"});
  3742. return Server::HandlerResponse::Unhandled;
  3743. });
  3744. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3745. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3746. ASSERT_NE(nullptr, ctx);
  3747. res.set_content("Hello " + ctx->user_id, "text/plain");
  3748. });
  3749. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3750. auto se = detail::scope_exit([&] {
  3751. svr.stop();
  3752. thread.join();
  3753. ASSERT_FALSE(svr.is_running());
  3754. });
  3755. svr.wait_until_ready();
  3756. Client cli(HOST, PORT);
  3757. auto res = cli.Get("/me");
  3758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3759. EXPECT_EQ(StatusCode::OK_200, res->status);
  3760. EXPECT_EQ("Hello alice", res->body);
  3761. }
  3762. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3763. struct RoleCtx {
  3764. std::string role;
  3765. };
  3766. Server svr;
  3767. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3768. res.user_data.set("role", RoleCtx{"admin"});
  3769. return Server::HandlerResponse::Unhandled;
  3770. });
  3771. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3772. auto *ctx = res.user_data.get<RoleCtx>("role");
  3773. ASSERT_NE(nullptr, ctx);
  3774. res.set_content(ctx->role, "text/plain");
  3775. });
  3776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3777. auto se = detail::scope_exit([&] {
  3778. svr.stop();
  3779. thread.join();
  3780. ASSERT_FALSE(svr.is_running());
  3781. });
  3782. svr.wait_until_ready();
  3783. Client cli(HOST, PORT);
  3784. auto res = cli.Get("/role");
  3785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3786. EXPECT_EQ(StatusCode::OK_200, res->status);
  3787. EXPECT_EQ("admin", res->body);
  3788. }
  3789. TEST(InvalidFormatTest, StatusCode) {
  3790. Server svr;
  3791. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3792. res.set_content("Hello World!\n", "text/plain");
  3793. res.status = 9999; // Status should be a three-digit code...
  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");
  3805. ASSERT_FALSE(res);
  3806. }
  3807. }
  3808. TEST(URLFragmentTest, WithFragment) {
  3809. Server svr;
  3810. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3811. EXPECT_TRUE(req.target == "/hi");
  3812. });
  3813. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3814. auto se = detail::scope_exit([&] {
  3815. svr.stop();
  3816. thread.join();
  3817. ASSERT_FALSE(svr.is_running());
  3818. });
  3819. svr.wait_until_ready();
  3820. {
  3821. Client cli(HOST, PORT);
  3822. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3823. EXPECT_TRUE(res);
  3824. EXPECT_EQ(StatusCode::OK_200, res->status);
  3825. res = cli.Get("/hi%23key1=val1=key2=val2");
  3826. EXPECT_TRUE(res);
  3827. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3828. }
  3829. }
  3830. TEST(HeaderWriter, SetHeaderWriter) {
  3831. Server svr;
  3832. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3833. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3834. return detail::write_headers(strm, hdrs);
  3835. });
  3836. svr.Get("/hi", [](const Request &req, Response &res) {
  3837. auto it = req.headers.find("CustomClientHeader");
  3838. EXPECT_TRUE(it != req.headers.end());
  3839. EXPECT_EQ(it->second, "CustomClientValue");
  3840. res.set_content("Hello World!\n", "text/plain");
  3841. });
  3842. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3843. auto se = detail::scope_exit([&] {
  3844. svr.stop();
  3845. thread.join();
  3846. ASSERT_FALSE(svr.is_running());
  3847. });
  3848. svr.wait_until_ready();
  3849. {
  3850. Client cli(HOST, PORT);
  3851. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3852. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3853. return detail::write_headers(strm, hdrs);
  3854. });
  3855. auto res = cli.Get("/hi");
  3856. EXPECT_TRUE(res);
  3857. EXPECT_EQ(StatusCode::OK_200, res->status);
  3858. auto it = res->headers.find("CustomServerHeader");
  3859. EXPECT_TRUE(it != res->headers.end());
  3860. EXPECT_EQ(it->second, "CustomServerValue");
  3861. }
  3862. }
  3863. class ServerTest : public ::testing::Test {
  3864. protected:
  3865. ServerTest()
  3866. : cli_(HOST, PORT)
  3867. #ifdef CPPHTTPLIB_SSL_ENABLED
  3868. ,
  3869. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3870. #endif
  3871. {
  3872. #ifdef CPPHTTPLIB_SSL_ENABLED
  3873. cli_.enable_server_certificate_verification(false);
  3874. #endif
  3875. // Allow LARGE_DATA (100MB) responses
  3876. cli_.set_payload_max_length(200 * 1024 * 1024);
  3877. }
  3878. virtual void SetUp() {
  3879. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3880. svr_.set_payload_max_length(200 * 1024 * 1024);
  3881. svr_.set_mount_point("/", "./www");
  3882. svr_.set_mount_point("/mount", "./www2");
  3883. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3884. svr_.Get("/hi",
  3885. [&](const Request & /*req*/, Response &res) {
  3886. res.set_content("Hello World!", "text/plain");
  3887. })
  3888. .Get("/file_content",
  3889. [&](const Request & /*req*/, Response &res) {
  3890. res.set_file_content("./www/dir/test.html");
  3891. })
  3892. .Get("/file_content_with_content_type",
  3893. [&](const Request & /*req*/, Response &res) {
  3894. res.set_file_content("./www/file", "text/plain");
  3895. })
  3896. .Get("/invalid_file_content",
  3897. [&](const Request & /*req*/, Response &res) {
  3898. res.set_file_content("./www/dir/invalid_file_path");
  3899. })
  3900. .Get("/http_response_splitting",
  3901. [&](const Request & /*req*/, Response &res) {
  3902. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3903. EXPECT_EQ(0U, res.headers.size());
  3904. EXPECT_FALSE(res.has_header("a"));
  3905. res.set_header("a", "1\nSet-Cookie: a=1");
  3906. EXPECT_EQ(0U, res.headers.size());
  3907. EXPECT_FALSE(res.has_header("a"));
  3908. res.set_header("a", "1\rSet-Cookie: a=1");
  3909. EXPECT_EQ(0U, res.headers.size());
  3910. EXPECT_FALSE(res.has_header("a"));
  3911. res.set_header("a\r\nb", "0");
  3912. EXPECT_EQ(0U, res.headers.size());
  3913. EXPECT_FALSE(res.has_header("a"));
  3914. res.set_header("a\rb", "0");
  3915. EXPECT_EQ(0U, res.headers.size());
  3916. EXPECT_FALSE(res.has_header("a"));
  3917. res.set_header("a\nb", "0");
  3918. EXPECT_EQ(0U, res.headers.size());
  3919. EXPECT_FALSE(res.has_header("a"));
  3920. res.set_redirect("1\r\nSet-Cookie: a=1");
  3921. EXPECT_EQ(0U, res.headers.size());
  3922. EXPECT_FALSE(res.has_header("Location"));
  3923. })
  3924. .Get("/slow",
  3925. [&](const Request & /*req*/, Response &res) {
  3926. std::this_thread::sleep_for(std::chrono::seconds(4));
  3927. res.set_content("slow", "text/plain");
  3928. })
  3929. #if 0
  3930. .Post("/slowpost",
  3931. [&](const Request & /*req*/, Response &res) {
  3932. std::this_thread::sleep_for(std::chrono::seconds(2));
  3933. res.set_content("slow", "text/plain");
  3934. })
  3935. #endif
  3936. .Get("/remote_addr",
  3937. [&](const Request &req, Response &res) {
  3938. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3939. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3940. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3941. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3942. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3943. #endif
  3944. res.set_content(req.remote_addr, "text/plain");
  3945. })
  3946. .Get("/local_addr",
  3947. [&](const Request &req, Response &res) {
  3948. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3949. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3950. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3951. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3952. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3953. #endif
  3954. auto local_addr = req.local_addr;
  3955. auto local_port = std::to_string(req.local_port);
  3956. res.set_content(local_addr.append(":").append(local_port),
  3957. "text/plain");
  3958. })
  3959. .Get("/endwith%",
  3960. [&](const Request & /*req*/, Response &res) {
  3961. res.set_content("Hello World!", "text/plain");
  3962. })
  3963. .Get("/a\\+\\+b",
  3964. [&](const Request &req, Response &res) {
  3965. ASSERT_TRUE(req.has_param("a +b"));
  3966. auto val = req.get_param_value("a +b");
  3967. res.set_content(val, "text/plain");
  3968. })
  3969. .Get("/", [&](const Request & /*req*/,
  3970. Response &res) { res.set_redirect("/hi"); })
  3971. .Post("/1",
  3972. [](const Request & /*req*/, Response &res) {
  3973. res.set_redirect("/2", StatusCode::SeeOther_303);
  3974. })
  3975. .Get("/2",
  3976. [](const Request & /*req*/, Response &res) {
  3977. res.set_content("redirected.", "text/plain");
  3978. res.status = StatusCode::OK_200;
  3979. })
  3980. .Post("/person",
  3981. [&](const Request &req, Response &res) {
  3982. if (req.has_param("name") && req.has_param("note")) {
  3983. persons_[req.get_param_value("name")] =
  3984. req.get_param_value("note");
  3985. } else {
  3986. res.status = StatusCode::BadRequest_400;
  3987. }
  3988. })
  3989. .Put("/person",
  3990. [&](const Request &req, Response &res) {
  3991. if (req.has_param("name") && req.has_param("note")) {
  3992. persons_[req.get_param_value("name")] =
  3993. req.get_param_value("note");
  3994. } else {
  3995. res.status = StatusCode::BadRequest_400;
  3996. }
  3997. })
  3998. .Get("/person/(.*)",
  3999. [&](const Request &req, Response &res) {
  4000. string name = req.matches[1];
  4001. if (persons_.find(name) != persons_.end()) {
  4002. auto note = persons_[name];
  4003. res.set_content(note, "text/plain");
  4004. } else {
  4005. res.status = StatusCode::NotFound_404;
  4006. }
  4007. })
  4008. .Delete("/person",
  4009. [&](const Request &req, Response &res) {
  4010. if (req.has_param("name")) {
  4011. string name = req.get_param_value("name");
  4012. if (persons_.find(name) != persons_.end()) {
  4013. persons_.erase(name);
  4014. res.set_content("DELETED", "text/plain");
  4015. } else {
  4016. res.status = StatusCode::NotFound_404;
  4017. }
  4018. } else {
  4019. res.status = StatusCode::BadRequest_400;
  4020. }
  4021. })
  4022. .Post("/x-www-form-urlencoded-json",
  4023. [&](const Request &req, Response &res) {
  4024. auto json = req.get_param_value("json");
  4025. ASSERT_EQ(JSON_DATA, json);
  4026. res.set_content(json, "appliation/json");
  4027. res.status = StatusCode::OK_200;
  4028. })
  4029. .Get("/streamed-chunked",
  4030. [&](const Request & /*req*/, Response &res) {
  4031. res.set_chunked_content_provider(
  4032. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4033. sink.os << "123";
  4034. sink.os << "456";
  4035. sink.os << "789";
  4036. sink.done();
  4037. return true;
  4038. });
  4039. })
  4040. .Get("/streamed-chunked-with-prohibited-trailer",
  4041. [&](const Request & /*req*/, Response &res) {
  4042. auto i = new int(0);
  4043. // Declare both a prohibited trailer (Content-Length) and an
  4044. // allowed one
  4045. res.set_header("Trailer", "Content-Length, X-Allowed");
  4046. res.set_chunked_content_provider(
  4047. "text/plain",
  4048. [i](size_t /*offset*/, DataSink &sink) {
  4049. switch (*i) {
  4050. case 0: sink.os << "123"; break;
  4051. case 1: sink.os << "456"; break;
  4052. case 2: sink.os << "789"; break;
  4053. case 3: {
  4054. sink.done_with_trailer(
  4055. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4056. } break;
  4057. }
  4058. (*i)++;
  4059. return true;
  4060. },
  4061. [i](bool success) {
  4062. EXPECT_TRUE(success);
  4063. delete i;
  4064. });
  4065. })
  4066. .Get("/streamed-chunked2",
  4067. [&](const Request & /*req*/, Response &res) {
  4068. auto i = new int(0);
  4069. res.set_chunked_content_provider(
  4070. "text/plain",
  4071. [i](size_t /*offset*/, DataSink &sink) {
  4072. switch (*i) {
  4073. case 0: sink.os << "123"; break;
  4074. case 1: sink.os << "456"; break;
  4075. case 2: sink.os << "789"; break;
  4076. case 3: sink.done(); break;
  4077. }
  4078. (*i)++;
  4079. return true;
  4080. },
  4081. [i](bool success) {
  4082. EXPECT_TRUE(success);
  4083. delete i;
  4084. });
  4085. })
  4086. .Get("/streamed-chunked-with-trailer",
  4087. [&](const Request & /*req*/, Response &res) {
  4088. auto i = new int(0);
  4089. res.set_header("Trailer", "Dummy1, Dummy2");
  4090. res.set_chunked_content_provider(
  4091. "text/plain",
  4092. [i](size_t /*offset*/, DataSink &sink) {
  4093. switch (*i) {
  4094. case 0: sink.os << "123"; break;
  4095. case 1: sink.os << "456"; break;
  4096. case 2: sink.os << "789"; break;
  4097. case 3: {
  4098. sink.done_with_trailer(
  4099. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4100. } break;
  4101. }
  4102. (*i)++;
  4103. return true;
  4104. },
  4105. [i](bool success) {
  4106. EXPECT_TRUE(success);
  4107. delete i;
  4108. });
  4109. })
  4110. .Get("/streamed",
  4111. [&](const Request & /*req*/, Response &res) {
  4112. res.set_content_provider(
  4113. 6, "text/plain",
  4114. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4115. sink.os << (offset < 3 ? "a" : "b");
  4116. return true;
  4117. });
  4118. })
  4119. .Get("/streamed-without-length",
  4120. [&](const Request & /*req*/, Response &res) {
  4121. auto data = new std::string("abcdefg");
  4122. res.set_content_provider(
  4123. "text/plain",
  4124. [data](size_t offset, DataSink &sink) {
  4125. if (offset < data->size()) {
  4126. sink.os << data->substr(offset);
  4127. }
  4128. sink.done();
  4129. return true;
  4130. },
  4131. [data](bool success) {
  4132. EXPECT_TRUE(success);
  4133. delete data;
  4134. });
  4135. })
  4136. .Get("/streamed-with-range",
  4137. [&](const Request &req, Response &res) {
  4138. auto data = new std::string("abcdefg");
  4139. // An explicit status keeps the server from picking the 206 it
  4140. // would otherwise choose for a ranged request, so the response
  4141. // is not a partial representation.
  4142. auto status = req.get_param_value("status");
  4143. if (status == "200") {
  4144. res.status = StatusCode::OK_200;
  4145. } else if (status == "403") {
  4146. res.status = StatusCode::Forbidden_403;
  4147. }
  4148. res.set_content_provider(
  4149. data->size(), "text/plain",
  4150. [data](size_t offset, size_t length, DataSink &sink) {
  4151. size_t DATA_CHUNK_SIZE = 4;
  4152. const auto &d = *data;
  4153. auto out_len =
  4154. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4155. auto ret =
  4156. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4157. EXPECT_TRUE(ret);
  4158. return true;
  4159. },
  4160. [data, &req](bool success) {
  4161. EXPECT_EQ(success, !req.has_param("error"));
  4162. delete data;
  4163. });
  4164. })
  4165. .Get("/streamed-cancel",
  4166. [&](const Request & /*req*/, Response &res) {
  4167. res.set_content_provider(
  4168. size_t(-1), "text/plain",
  4169. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4170. sink.os << "data_chunk";
  4171. return true;
  4172. });
  4173. })
  4174. .Get("/regex-with-delimiter",
  4175. [&](const Request &req, Response & /*res*/) {
  4176. ASSERT_TRUE(req.has_param("key"));
  4177. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4178. })
  4179. .Get("/with-range",
  4180. [&](const Request & /*req*/, Response &res) {
  4181. res.set_content("abcdefg", "text/plain");
  4182. })
  4183. .Get("/test-start-time",
  4184. [&](const Request &req, Response & /*res*/) {
  4185. EXPECT_NE(req.start_time_,
  4186. std::chrono::steady_clock::time_point::min());
  4187. })
  4188. .Get("/with-range-customized-response",
  4189. [&](const Request & /*req*/, Response &res) {
  4190. res.status = StatusCode::BadRequest_400;
  4191. res.set_content(JSON_DATA, "application/json");
  4192. })
  4193. .Post("/chunked",
  4194. [&](const Request &req, Response & /*res*/) {
  4195. EXPECT_EQ(req.body, "dechunked post body");
  4196. })
  4197. .Post("/large-chunked",
  4198. [&](const Request &req, Response & /*res*/) {
  4199. std::string expected(6 * 30 * 1024u, 'a');
  4200. EXPECT_EQ(req.body, expected);
  4201. })
  4202. .Post("/multipart",
  4203. [&](const Request &req, Response & /*res*/) {
  4204. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4205. req.form.get_field_count("text2") +
  4206. req.form.get_field_count("file3") +
  4207. req.form.get_field_count("file4"));
  4208. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4209. req.form.get_file_count("file2"));
  4210. ASSERT_TRUE(!req.form.has_file("???"));
  4211. ASSERT_TRUE(!req.form.has_field("???"));
  4212. ASSERT_TRUE(req.body.empty());
  4213. {
  4214. const auto &text = req.form.get_field("text1");
  4215. EXPECT_EQ("text default", text);
  4216. }
  4217. {
  4218. const auto &text = req.form.get_field("text2");
  4219. EXPECT_EQ("aωb", text);
  4220. }
  4221. {
  4222. const auto &file = req.form.get_file("file1");
  4223. EXPECT_EQ("hello.txt", file.filename);
  4224. EXPECT_EQ("text/plain", file.content_type);
  4225. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4226. }
  4227. {
  4228. const auto &file = req.form.get_file("file2");
  4229. EXPECT_EQ("world.json", file.filename);
  4230. EXPECT_EQ("application/json", file.content_type);
  4231. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4232. }
  4233. {
  4234. const auto &text = req.form.get_field("file3");
  4235. EXPECT_EQ(0u, text.size());
  4236. }
  4237. {
  4238. const auto &text = req.form.get_field("file4");
  4239. EXPECT_EQ(0u, text.size());
  4240. }
  4241. })
  4242. .Post("/multipart/multi_file_values",
  4243. [&](const Request &req, Response & /*res*/) {
  4244. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4245. req.form.get_field_count("multi_text1"));
  4246. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4247. ASSERT_TRUE(!req.form.has_file("???"));
  4248. ASSERT_TRUE(!req.form.has_field("???"));
  4249. ASSERT_TRUE(req.body.empty());
  4250. {
  4251. const auto &text = req.form.get_field("text");
  4252. EXPECT_EQ("default text", text);
  4253. }
  4254. {
  4255. const auto &text1_values = req.form.get_fields("multi_text1");
  4256. EXPECT_EQ(2u, text1_values.size());
  4257. EXPECT_EQ("aaaaa", text1_values[0]);
  4258. EXPECT_EQ("bbbbb", text1_values[1]);
  4259. }
  4260. {
  4261. const auto &file1_values = req.form.get_files("multi_file1");
  4262. EXPECT_EQ(2u, file1_values.size());
  4263. auto file1 = file1_values[0];
  4264. EXPECT_EQ(file1.filename, "hello.txt");
  4265. EXPECT_EQ(file1.content_type, "text/plain");
  4266. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4267. auto file2 = file1_values[1];
  4268. EXPECT_EQ(file2.filename, "world.json");
  4269. EXPECT_EQ(file2.content_type, "application/json");
  4270. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4271. }
  4272. })
  4273. .Post("/empty",
  4274. [&](const Request &req, Response &res) {
  4275. EXPECT_EQ(req.body, "");
  4276. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4277. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4278. res.set_content("empty", "text/plain");
  4279. })
  4280. .Post("/empty-no-content-type",
  4281. [&](const Request &req, Response &res) {
  4282. EXPECT_EQ(req.body, "");
  4283. EXPECT_FALSE(req.has_header("Content-Type"));
  4284. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4285. res.set_content("empty-no-content-type", "text/plain");
  4286. })
  4287. .Post("/path-only",
  4288. [&](const Request &req, Response &res) {
  4289. EXPECT_EQ(req.body, "");
  4290. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4291. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4292. res.set_content("path-only", "text/plain");
  4293. })
  4294. .Post("/path-headers-only",
  4295. [&](const Request &req, Response &res) {
  4296. EXPECT_EQ(req.body, "");
  4297. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4298. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4299. EXPECT_EQ("world", req.get_header_value("hello"));
  4300. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4301. res.set_content("path-headers-only", "text/plain");
  4302. })
  4303. .Post("/post-large",
  4304. [&](const Request &req, Response &res) {
  4305. EXPECT_EQ(req.body, LARGE_DATA);
  4306. res.set_content(req.body, "text/plain");
  4307. })
  4308. .Post("/post-loopback",
  4309. [&](const Request &, Response &res,
  4310. ContentReader const &content_reader) {
  4311. std::string body;
  4312. content_reader([&](const char *data, size_t data_length) {
  4313. body.append(data, data_length);
  4314. return true;
  4315. });
  4316. res.set_content(body, "text/plain");
  4317. })
  4318. .Put("/put-loopback",
  4319. [&](const Request &, Response &res,
  4320. ContentReader const &content_reader) {
  4321. std::string body;
  4322. content_reader([&](const char *data, size_t data_length) {
  4323. body.append(data, data_length);
  4324. return true;
  4325. });
  4326. res.set_content(body, "text/plain");
  4327. })
  4328. .Patch("/patch-loopback",
  4329. [&](const Request &, Response &res,
  4330. ContentReader const &content_reader) {
  4331. std::string body;
  4332. content_reader([&](const char *data, size_t data_length) {
  4333. body.append(data, data_length);
  4334. return true;
  4335. });
  4336. res.set_content(body, "text/plain");
  4337. })
  4338. .Put("/empty-no-content-type",
  4339. [&](const Request &req, Response &res) {
  4340. EXPECT_EQ(req.body, "");
  4341. EXPECT_FALSE(req.has_header("Content-Type"));
  4342. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4343. res.set_content("empty-no-content-type", "text/plain");
  4344. })
  4345. .Put("/put",
  4346. [&](const Request &req, Response &res) {
  4347. EXPECT_EQ(req.body, "PUT");
  4348. res.set_content(req.body, "text/plain");
  4349. })
  4350. .Put("/put-large",
  4351. [&](const Request &req, Response &res) {
  4352. EXPECT_EQ(req.body, LARGE_DATA);
  4353. res.set_content(req.body, "text/plain");
  4354. })
  4355. .Patch("/patch",
  4356. [&](const Request &req, Response &res) {
  4357. EXPECT_EQ(req.body, "PATCH");
  4358. res.set_content(req.body, "text/plain");
  4359. })
  4360. .Delete("/delete",
  4361. [&](const Request & /*req*/, Response &res) {
  4362. res.set_content("DELETE", "text/plain");
  4363. })
  4364. .Delete("/delete-body",
  4365. [&](const Request &req, Response &res) {
  4366. EXPECT_EQ(req.body, "content");
  4367. res.set_content(req.body, "text/plain");
  4368. })
  4369. .Options(R"(\*)",
  4370. [&](const Request & /*req*/, Response &res) {
  4371. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4372. })
  4373. .Get("/request-target",
  4374. [&](const Request &req, Response & /*res*/) {
  4375. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4376. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4377. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4378. })
  4379. .Get("/long-query-value",
  4380. [&](const Request &req, Response & /*res*/) {
  4381. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4382. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4383. })
  4384. .Get("/too-long-query-value",
  4385. [&](const Request &req, Response & /*res*/) {
  4386. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4387. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4388. })
  4389. .Get("/array-param",
  4390. [&](const Request &req, Response & /*res*/) {
  4391. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4392. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4393. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4394. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4395. })
  4396. .Get("/array-param-values",
  4397. [&](const Request &req, Response & /*res*/) {
  4398. auto values = req.get_param_values("array");
  4399. EXPECT_EQ(3u, values.size());
  4400. EXPECT_EQ("value1", values[0]);
  4401. EXPECT_EQ("value2", values[1]);
  4402. EXPECT_EQ("value3", values[2]);
  4403. auto empty = req.get_param_values("nonexistent");
  4404. EXPECT_TRUE(empty.empty());
  4405. })
  4406. .Post("/validate-no-multiple-headers",
  4407. [&](const Request &req, Response & /*res*/) {
  4408. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4409. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4410. })
  4411. .Post("/content_receiver",
  4412. [&](const Request &req, Response &res,
  4413. const ContentReader &content_reader) {
  4414. if (req.is_multipart_form_data()) {
  4415. std::vector<FormData> items;
  4416. content_reader(
  4417. [&](const FormData &file) {
  4418. items.push_back(file);
  4419. return true;
  4420. },
  4421. [&](const char *data, size_t data_length) {
  4422. items.back().content.append(data, data_length);
  4423. return true;
  4424. });
  4425. EXPECT_EQ(5u, items.size());
  4426. {
  4427. const auto &file = get_file_value(items, "text1");
  4428. EXPECT_TRUE(file.filename.empty());
  4429. EXPECT_EQ("text default", file.content);
  4430. }
  4431. {
  4432. const auto &file = get_file_value(items, "text2");
  4433. EXPECT_TRUE(file.filename.empty());
  4434. EXPECT_EQ("aωb", file.content);
  4435. }
  4436. {
  4437. const auto &file = get_file_value(items, "file1");
  4438. EXPECT_EQ("hello.txt", file.filename);
  4439. EXPECT_EQ("text/plain", file.content_type);
  4440. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4441. }
  4442. {
  4443. const auto &file = get_file_value(items, "file2");
  4444. EXPECT_EQ("world.json", file.filename);
  4445. EXPECT_EQ("application/json", file.content_type);
  4446. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4447. }
  4448. {
  4449. const auto &file = get_file_value(items, "file3");
  4450. EXPECT_TRUE(file.filename.empty());
  4451. EXPECT_EQ("application/octet-stream", file.content_type);
  4452. EXPECT_EQ(0u, file.content.size());
  4453. }
  4454. } else {
  4455. std::string body;
  4456. content_reader([&](const char *data, size_t data_length) {
  4457. EXPECT_EQ(7U, data_length);
  4458. body.append(data, data_length);
  4459. return true;
  4460. });
  4461. EXPECT_EQ(body, "content");
  4462. res.set_content(body, "text/plain");
  4463. }
  4464. })
  4465. .Put("/content_receiver",
  4466. [&](const Request & /*req*/, Response &res,
  4467. const ContentReader &content_reader) {
  4468. std::string body;
  4469. content_reader([&](const char *data, size_t data_length) {
  4470. body.append(data, data_length);
  4471. return true;
  4472. });
  4473. EXPECT_EQ(body, "content");
  4474. res.set_content(body, "text/plain");
  4475. })
  4476. .Patch("/content_receiver",
  4477. [&](const Request & /*req*/, Response &res,
  4478. const ContentReader &content_reader) {
  4479. std::string body;
  4480. content_reader([&](const char *data, size_t data_length) {
  4481. body.append(data, data_length);
  4482. return true;
  4483. });
  4484. EXPECT_EQ(body, "content");
  4485. res.set_content(body, "text/plain");
  4486. })
  4487. .Post("/query-string-and-body",
  4488. [&](const Request &req, Response & /*res*/) {
  4489. ASSERT_TRUE(req.has_param("key"));
  4490. EXPECT_EQ(req.get_param_value("key"), "value");
  4491. EXPECT_EQ(req.body, "content");
  4492. })
  4493. .Get("/last-request",
  4494. [&](const Request &req, Response & /*res*/) {
  4495. EXPECT_EQ("close", req.get_header_value("Connection"));
  4496. })
  4497. .Get(R"(/redirect/(\d+))",
  4498. [&](const Request &req, Response &res) {
  4499. auto num = std::stoi(req.matches[1]) + 1;
  4500. std::string url = "/redirect/" + std::to_string(num);
  4501. res.set_redirect(url);
  4502. })
  4503. .Post("/binary",
  4504. [&](const Request &req, Response &res) {
  4505. EXPECT_EQ(4U, req.body.size());
  4506. EXPECT_EQ("application/octet-stream",
  4507. req.get_header_value("Content-Type"));
  4508. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4509. res.set_content(req.body, "application/octet-stream");
  4510. })
  4511. .Put("/binary",
  4512. [&](const Request &req, Response &res) {
  4513. EXPECT_EQ(4U, req.body.size());
  4514. EXPECT_EQ("application/octet-stream",
  4515. req.get_header_value("Content-Type"));
  4516. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4517. res.set_content(req.body, "application/octet-stream");
  4518. })
  4519. .Patch("/binary",
  4520. [&](const Request &req, Response &res) {
  4521. EXPECT_EQ(4U, req.body.size());
  4522. EXPECT_EQ("application/octet-stream",
  4523. req.get_header_value("Content-Type"));
  4524. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4525. res.set_content(req.body, "application/octet-stream");
  4526. })
  4527. .Delete("/binary",
  4528. [&](const Request &req, Response &res) {
  4529. EXPECT_EQ(4U, req.body.size());
  4530. EXPECT_EQ("application/octet-stream",
  4531. req.get_header_value("Content-Type"));
  4532. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4533. res.set_content(req.body, "application/octet-stream");
  4534. })
  4535. .Get("/issue1772",
  4536. [&](const Request & /*req*/, Response &res) {
  4537. res.status = 401;
  4538. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4539. })
  4540. .Delete("/issue609",
  4541. [](const httplib::Request &, httplib::Response &res,
  4542. const httplib::ContentReader &) {
  4543. res.set_content("ok", "text/plain");
  4544. })
  4545. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4546. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4547. .Get("/compress",
  4548. [&](const Request & /*req*/, Response &res) {
  4549. res.set_content(
  4550. "12345678901234567890123456789012345678901234567890123456789"
  4551. "01234567890123456789012345678901234567890",
  4552. "text/plain");
  4553. })
  4554. .Get("/compress-with-charset",
  4555. [&](const Request & /*req*/, Response &res) {
  4556. res.set_content(
  4557. "12345678901234567890123456789012345678901234567890123456789"
  4558. "01234567890123456789012345678901234567890",
  4559. "application/json; charset=utf-8");
  4560. })
  4561. .Get("/nocompress",
  4562. [&](const Request & /*req*/, Response &res) {
  4563. res.set_content(
  4564. "12345678901234567890123456789012345678901234567890123456789"
  4565. "01234567890123456789012345678901234567890",
  4566. "application/octet-stream");
  4567. })
  4568. .Post("/compress-multipart",
  4569. [&](const Request &req, Response & /*res*/) {
  4570. EXPECT_EQ(2u, req.form.fields.size());
  4571. ASSERT_TRUE(!req.form.has_field("???"));
  4572. {
  4573. const auto &text = req.form.get_field("key1");
  4574. EXPECT_EQ("test", text);
  4575. }
  4576. {
  4577. const auto &text = req.form.get_field("key2");
  4578. EXPECT_EQ("--abcdefg123", text);
  4579. }
  4580. })
  4581. #endif
  4582. ;
  4583. persons_["john"] = "programmer";
  4584. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4585. svr_.wait_until_ready();
  4586. }
  4587. virtual void TearDown() {
  4588. svr_.stop();
  4589. if (!request_threads_.empty()) {
  4590. std::this_thread::sleep_for(std::chrono::seconds(1));
  4591. for (auto &t : request_threads_) {
  4592. t.join();
  4593. }
  4594. }
  4595. t_.join();
  4596. }
  4597. map<string, string> persons_;
  4598. #ifdef CPPHTTPLIB_SSL_ENABLED
  4599. SSLClient cli_;
  4600. SSLServer svr_;
  4601. #else
  4602. Client cli_;
  4603. Server svr_;
  4604. #endif
  4605. thread t_;
  4606. std::vector<thread> request_threads_;
  4607. };
  4608. TEST_F(ServerTest, GetMethod200) {
  4609. auto res = cli_.Get("/hi");
  4610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4611. EXPECT_EQ("HTTP/1.1", res->version);
  4612. EXPECT_EQ(StatusCode::OK_200, res->status);
  4613. EXPECT_EQ("OK", res->reason);
  4614. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4615. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4616. EXPECT_EQ("Hello World!", res->body);
  4617. }
  4618. TEST_F(ServerTest, GetEmptyFile) {
  4619. auto res = cli_.Get("/empty_file");
  4620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4621. EXPECT_EQ(StatusCode::OK_200, res->status);
  4622. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4623. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4624. EXPECT_EQ("", res->body);
  4625. }
  4626. TEST_F(ServerTest, GetFileContent) {
  4627. auto res = cli_.Get("/file_content");
  4628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4629. EXPECT_EQ(StatusCode::OK_200, res->status);
  4630. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4631. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4632. EXPECT_EQ("test.html", res->body);
  4633. }
  4634. TEST_F(ServerTest, GetFileContentWithRange) {
  4635. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4637. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4638. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4639. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4640. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4641. EXPECT_EQ("est", res->body);
  4642. }
  4643. TEST_F(ServerTest, GetFileContentWithContentType) {
  4644. auto res = cli_.Get("/file_content_with_content_type");
  4645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4646. EXPECT_EQ(StatusCode::OK_200, res->status);
  4647. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4648. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4649. EXPECT_EQ("file\n", res->body);
  4650. }
  4651. TEST_F(ServerTest, GetInvalidFileContent) {
  4652. auto res = cli_.Get("/invalid_file_content");
  4653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4654. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4655. }
  4656. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4657. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4659. EXPECT_EQ("HTTP/1.1", res->version);
  4660. EXPECT_EQ(StatusCode::OK_200, res->status);
  4661. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4662. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4663. EXPECT_EQ("Hello World!", res->body);
  4664. }
  4665. TEST_F(ServerTest, GetMethod302) {
  4666. auto res = cli_.Get("/");
  4667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4668. EXPECT_EQ(StatusCode::Found_302, res->status);
  4669. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4670. }
  4671. TEST_F(ServerTest, GetMethod302Redirect) {
  4672. cli_.set_follow_location(true);
  4673. auto res = cli_.Get("/");
  4674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4675. EXPECT_EQ(StatusCode::OK_200, res->status);
  4676. EXPECT_EQ("Hello World!", res->body);
  4677. EXPECT_EQ("/hi", res->location);
  4678. }
  4679. TEST_F(ServerTest, GetMethod404) {
  4680. auto res = cli_.Get("/invalid");
  4681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4682. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4683. }
  4684. TEST_F(ServerTest, HeadMethod200) {
  4685. auto res = cli_.Head("/hi");
  4686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4687. EXPECT_EQ(StatusCode::OK_200, res->status);
  4688. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4689. EXPECT_TRUE(res->body.empty());
  4690. }
  4691. TEST_F(ServerTest, HeadMethod200Static) {
  4692. auto res = cli_.Head("/mount/dir/index.html");
  4693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4694. EXPECT_EQ(StatusCode::OK_200, res->status);
  4695. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4696. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4697. EXPECT_TRUE(res->body.empty());
  4698. }
  4699. TEST_F(ServerTest, HeadMethod404) {
  4700. auto res = cli_.Head("/invalid");
  4701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4702. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4703. EXPECT_TRUE(res->body.empty());
  4704. }
  4705. TEST_F(ServerTest, GetMethodPersonJohn) {
  4706. auto res = cli_.Get("/person/john");
  4707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4708. EXPECT_EQ(StatusCode::OK_200, res->status);
  4709. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4710. EXPECT_EQ("programmer", res->body);
  4711. }
  4712. TEST_F(ServerTest, PostMethod1) {
  4713. auto res = cli_.Get("/person/john1");
  4714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4715. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4716. res = cli_.Post("/person", "name=john1&note=coder",
  4717. "application/x-www-form-urlencoded");
  4718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4719. ASSERT_EQ(StatusCode::OK_200, res->status);
  4720. res = cli_.Get("/person/john1");
  4721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4722. ASSERT_EQ(StatusCode::OK_200, res->status);
  4723. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4724. ASSERT_EQ("coder", res->body);
  4725. }
  4726. TEST_F(ServerTest, PostMethod2) {
  4727. auto res = cli_.Get("/person/john2");
  4728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4729. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4730. Params params;
  4731. params.emplace("name", "john2");
  4732. params.emplace("note", "coder");
  4733. res = cli_.Post("/person", params);
  4734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4735. ASSERT_EQ(StatusCode::OK_200, res->status);
  4736. res = cli_.Get("/person/john2");
  4737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4738. ASSERT_EQ(StatusCode::OK_200, res->status);
  4739. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4740. ASSERT_EQ("coder", res->body);
  4741. }
  4742. TEST_F(ServerTest, PutMethod3) {
  4743. auto res = cli_.Get("/person/john3");
  4744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4745. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4746. Params params;
  4747. params.emplace("name", "john3");
  4748. params.emplace("note", "coder");
  4749. res = cli_.Put("/person", params);
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. ASSERT_EQ(StatusCode::OK_200, res->status);
  4752. res = cli_.Get("/person/john3");
  4753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4754. ASSERT_EQ(StatusCode::OK_200, res->status);
  4755. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4756. ASSERT_EQ("coder", res->body);
  4757. }
  4758. TEST_F(ServerTest, DeleteMethod1) {
  4759. auto res = cli_.Get("/person/john4");
  4760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4761. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4762. Params params;
  4763. params.emplace("name", "john4");
  4764. params.emplace("note", "coder");
  4765. res = cli_.Post("/person", params);
  4766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4767. ASSERT_EQ(StatusCode::OK_200, res->status);
  4768. res = cli_.Get("/person/john4");
  4769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4770. ASSERT_EQ(StatusCode::OK_200, res->status);
  4771. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4772. ASSERT_EQ("coder", res->body);
  4773. Params delete_params;
  4774. delete_params.emplace("name", "john4");
  4775. res = cli_.Delete("/person", delete_params);
  4776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4777. ASSERT_EQ(StatusCode::OK_200, res->status);
  4778. ASSERT_EQ("DELETED", res->body);
  4779. res = cli_.Get("/person/john4");
  4780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4781. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4782. }
  4783. TEST_F(ServerTest, DeleteMethod2) {
  4784. auto res = cli_.Get("/person/john5");
  4785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4786. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4787. Params params;
  4788. params.emplace("name", "john5");
  4789. params.emplace("note", "developer");
  4790. res = cli_.Post("/person", params);
  4791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4792. ASSERT_EQ(StatusCode::OK_200, res->status);
  4793. res = cli_.Get("/person/john5");
  4794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4795. ASSERT_EQ(StatusCode::OK_200, res->status);
  4796. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4797. ASSERT_EQ("developer", res->body);
  4798. Params delete_params;
  4799. delete_params.emplace("name", "john5");
  4800. Headers headers;
  4801. headers.emplace("Custom-Header", "test-value");
  4802. res = cli_.Delete("/person", headers, delete_params);
  4803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4804. ASSERT_EQ(StatusCode::OK_200, res->status);
  4805. ASSERT_EQ("DELETED", res->body);
  4806. res = cli_.Get("/person/john5");
  4807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4808. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4809. }
  4810. TEST_F(ServerTest, DeleteMethod3) {
  4811. auto res = cli_.Get("/person/john6");
  4812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4813. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4814. Params params;
  4815. params.emplace("name", "john6");
  4816. params.emplace("note", "tester");
  4817. res = cli_.Post("/person", params);
  4818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4819. ASSERT_EQ(StatusCode::OK_200, res->status);
  4820. res = cli_.Get("/person/john6");
  4821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4822. ASSERT_EQ(StatusCode::OK_200, res->status);
  4823. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4824. ASSERT_EQ("tester", res->body);
  4825. Params delete_params;
  4826. delete_params.emplace("name", "john6");
  4827. Headers headers;
  4828. headers.emplace("Custom-Header", "test-value");
  4829. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4831. ASSERT_EQ(StatusCode::OK_200, res->status);
  4832. ASSERT_EQ("DELETED", res->body);
  4833. res = cli_.Get("/person/john6");
  4834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4835. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4836. }
  4837. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4838. Params params;
  4839. params.emplace("json", JSON_DATA);
  4840. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4842. ASSERT_EQ(StatusCode::OK_200, res->status);
  4843. ASSERT_EQ(JSON_DATA, res->body);
  4844. }
  4845. TEST_F(ServerTest, PostEmptyContent) {
  4846. auto res = cli_.Post("/empty", "", "text/plain");
  4847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4848. ASSERT_EQ(StatusCode::OK_200, res->status);
  4849. ASSERT_EQ("empty", res->body);
  4850. }
  4851. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4852. auto res = cli_.Post("/empty-no-content-type");
  4853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4854. ASSERT_EQ(StatusCode::OK_200, res->status);
  4855. ASSERT_EQ("empty-no-content-type", res->body);
  4856. }
  4857. TEST_F(ServerTest, PostPathOnly) {
  4858. auto res = cli_.Post("/path-only");
  4859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4860. ASSERT_EQ(StatusCode::OK_200, res->status);
  4861. ASSERT_EQ("path-only", res->body);
  4862. }
  4863. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4864. auto res = cli_.Post("/path-headers-only",
  4865. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4867. ASSERT_EQ(StatusCode::OK_200, res->status);
  4868. ASSERT_EQ("path-headers-only", res->body);
  4869. }
  4870. TEST_F(ServerTest, PostLarge) {
  4871. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4873. ASSERT_EQ(StatusCode::OK_200, res->status);
  4874. EXPECT_EQ(LARGE_DATA, res->body);
  4875. }
  4876. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4877. auto res = cli_.Put("/empty-no-content-type");
  4878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4879. ASSERT_EQ(StatusCode::OK_200, res->status);
  4880. ASSERT_EQ("empty-no-content-type", res->body);
  4881. }
  4882. TEST_F(ServerTest, GetMethodDir) {
  4883. auto res = cli_.Get("/dir/");
  4884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4885. EXPECT_EQ(StatusCode::OK_200, res->status);
  4886. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4887. auto body = R"(<html>
  4888. <head>
  4889. </head>
  4890. <body>
  4891. <a href="/dir/test.html">Test</a>
  4892. <a href="/hi">hi</a>
  4893. </body>
  4894. </html>
  4895. )";
  4896. EXPECT_EQ(body, res->body);
  4897. }
  4898. TEST_F(ServerTest, GetMethodDirTest) {
  4899. auto res = cli_.Get("/dir/test.html");
  4900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4901. EXPECT_EQ(StatusCode::OK_200, res->status);
  4902. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4903. EXPECT_EQ("test.html", res->body);
  4904. }
  4905. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4906. auto res = cli_.Get("/dir/../dir/test.html");
  4907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4908. EXPECT_EQ(StatusCode::OK_200, res->status);
  4909. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4910. EXPECT_EQ("test.html", res->body);
  4911. }
  4912. TEST_F(ServerTest, GetMethodInvalidPath) {
  4913. auto res = cli_.Get("/dir/../test.html");
  4914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4915. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4916. }
  4917. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4918. auto res = cli_.Get("/../www/dir/test.html");
  4919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4920. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4921. }
  4922. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4923. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4925. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4926. }
  4927. TEST_F(ServerTest, GetMethodDirMountTest) {
  4928. auto res = cli_.Get("/mount/dir/test.html");
  4929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4930. EXPECT_EQ(StatusCode::OK_200, res->status);
  4931. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4932. EXPECT_EQ("test.html", res->body);
  4933. }
  4934. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4935. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4937. EXPECT_EQ(StatusCode::OK_200, res->status);
  4938. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4939. EXPECT_EQ("test.html", res->body);
  4940. }
  4941. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4942. auto res = cli_.Get("/mount/dir/../test.html");
  4943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4944. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4945. }
  4946. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4947. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4949. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4950. }
  4951. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4952. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4954. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4955. }
  4956. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4957. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4959. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4960. }
  4961. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4962. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4964. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4965. }
  4966. TEST_F(ServerTest, PostMethod303) {
  4967. auto res = cli_.Post("/1", "body", "text/plain");
  4968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4969. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4970. EXPECT_EQ("/2", res->get_header_value("Location"));
  4971. }
  4972. TEST_F(ServerTest, PostMethod303Redirect) {
  4973. cli_.set_follow_location(true);
  4974. auto res = cli_.Post("/1", "body", "text/plain");
  4975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4976. EXPECT_EQ(StatusCode::OK_200, res->status);
  4977. EXPECT_EQ("redirected.", res->body);
  4978. EXPECT_EQ("/2", res->location);
  4979. }
  4980. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4981. auto res = cli_.Get("/dir/test.abcde");
  4982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4983. EXPECT_EQ(StatusCode::OK_200, res->status);
  4984. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4985. EXPECT_EQ("abcde", res->body);
  4986. }
  4987. TEST_F(ServerTest, StaticFileRange) {
  4988. auto res =
  4989. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4991. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4992. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4993. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4994. EXPECT_EQ(true, res->has_header("Content-Range"));
  4995. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4996. EXPECT_EQ(std::string("cd"), res->body);
  4997. }
  4998. TEST_F(ServerTest, StaticFileRanges) {
  4999. auto res = cli_.Get("/dir/test.abcde",
  5000. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5002. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5003. EXPECT_TRUE(
  5004. res->get_header_value("Content-Type")
  5005. .find(
  5006. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5007. 0);
  5008. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5009. }
  5010. TEST_F(ServerTest, StaticFileRangeHead) {
  5011. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5013. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5014. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5015. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5016. EXPECT_EQ(true, res->has_header("Content-Range"));
  5017. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5018. }
  5019. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5020. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5022. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5023. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5024. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5025. EXPECT_EQ(true, res->has_header("Content-Range"));
  5026. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5027. res->get_header_value("Content-Range"));
  5028. EXPECT_EQ("LAST\n", res->body);
  5029. }
  5030. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5031. auto res =
  5032. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5034. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5035. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5036. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5037. EXPECT_EQ(true, res->has_header("Content-Range"));
  5038. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5039. }
  5040. TEST_F(ServerTest, StaticFileBigFile) {
  5041. auto res = cli_.Get("/dir/1MB.txt");
  5042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5043. EXPECT_EQ(StatusCode::OK_200, res->status);
  5044. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5045. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5046. }
  5047. TEST_F(ServerTest, InvalidBaseDirMount) {
  5048. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5049. }
  5050. TEST_F(ServerTest, Binary) {
  5051. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5052. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5053. "application/octet-stream");
  5054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5055. ASSERT_EQ(StatusCode::OK_200, res->status);
  5056. ASSERT_EQ(4U, res->body.size());
  5057. res = cli_.Put("/binary", binary.data(), binary.size(),
  5058. "application/octet-stream");
  5059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5060. ASSERT_EQ(StatusCode::OK_200, res->status);
  5061. ASSERT_EQ(4U, res->body.size());
  5062. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5063. "application/octet-stream");
  5064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5065. ASSERT_EQ(StatusCode::OK_200, res->status);
  5066. ASSERT_EQ(4U, res->body.size());
  5067. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5068. "application/octet-stream");
  5069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5070. ASSERT_EQ(StatusCode::OK_200, res->status);
  5071. ASSERT_EQ(4U, res->body.size());
  5072. }
  5073. TEST_F(ServerTest, BinaryString) {
  5074. auto binary = std::string("\x00\x01\x02\x03", 4);
  5075. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5077. ASSERT_EQ(StatusCode::OK_200, res->status);
  5078. ASSERT_EQ(4U, res->body.size());
  5079. res = cli_.Put("/binary", binary, "application/octet-stream");
  5080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5081. ASSERT_EQ(StatusCode::OK_200, res->status);
  5082. ASSERT_EQ(4U, res->body.size());
  5083. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5085. ASSERT_EQ(StatusCode::OK_200, res->status);
  5086. ASSERT_EQ(4U, res->body.size());
  5087. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5089. ASSERT_EQ(StatusCode::OK_200, res->status);
  5090. ASSERT_EQ(4U, res->body.size());
  5091. }
  5092. TEST_F(ServerTest, EmptyRequest) {
  5093. auto res = cli_.Get("");
  5094. ASSERT_TRUE(!res);
  5095. EXPECT_EQ(Error::Connection, res.error());
  5096. }
  5097. TEST_F(ServerTest, LongRequest) {
  5098. std::string request;
  5099. for (size_t i = 0; i < 545; i++) {
  5100. request += "/TooLongRequest";
  5101. }
  5102. request += "OK";
  5103. auto res = cli_.Get(request.c_str());
  5104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5105. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5106. }
  5107. TEST_F(ServerTest, TooLongRequest) {
  5108. std::string request;
  5109. for (size_t i = 0; i < 546; i++) {
  5110. request += "/TooLongRequest";
  5111. }
  5112. request += "_NG";
  5113. auto start = std::chrono::high_resolution_clock::now();
  5114. cli_.set_keep_alive(true);
  5115. auto res = cli_.Get(request.c_str());
  5116. auto end = std::chrono::high_resolution_clock::now();
  5117. auto elapsed =
  5118. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5119. .count();
  5120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5121. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5122. EXPECT_LE(elapsed, 1000);
  5123. EXPECT_EQ("close", res->get_header_value("Connection"));
  5124. EXPECT_FALSE(cli_.is_socket_open());
  5125. }
  5126. TEST_F(ServerTest, AlmostTooLongRequest) {
  5127. // test for #2046 - URI length check shouldn't include other content on req
  5128. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5129. // leading /, space, HTTP/1.1)
  5130. std::string request =
  5131. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5132. auto res = cli_.Get(request.c_str());
  5133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5134. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5135. }
  5136. TEST_F(ServerTest, LongHeader) {
  5137. Request req;
  5138. req.method = "GET";
  5139. req.path = "/hi";
  5140. std::string host_and_port;
  5141. host_and_port += HOST;
  5142. host_and_port += ":";
  5143. host_and_port += std::to_string(PORT);
  5144. req.headers.emplace("Host", host_and_port.c_str());
  5145. req.headers.emplace("Accept", "*/*");
  5146. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5147. req.headers.emplace(
  5148. "Header-Name",
  5149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5169. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5170. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5171. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5172. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5173. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5174. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5175. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5176. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5177. "@@@@@@@@@@@@@@@@");
  5178. auto res = std::make_shared<Response>();
  5179. auto error = Error::Success;
  5180. auto ret = cli_.send(req, *res, error);
  5181. ASSERT_TRUE(ret);
  5182. EXPECT_EQ(StatusCode::OK_200, res->status);
  5183. }
  5184. TEST_F(ServerTest, LongQueryValue) {
  5185. auto start = std::chrono::high_resolution_clock::now();
  5186. cli_.set_keep_alive(true);
  5187. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5188. auto end = std::chrono::high_resolution_clock::now();
  5189. auto elapsed =
  5190. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5191. .count();
  5192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5193. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5194. EXPECT_LE(elapsed, 1000);
  5195. EXPECT_EQ("close", res->get_header_value("Connection"));
  5196. EXPECT_FALSE(cli_.is_socket_open());
  5197. }
  5198. TEST_F(ServerTest, TooLongQueryValue) {
  5199. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5200. ASSERT_FALSE(res);
  5201. EXPECT_EQ(Error::Read, res.error());
  5202. }
  5203. TEST_F(ServerTest, TooLongHeader) {
  5204. Request req;
  5205. req.method = "GET";
  5206. req.path = "/hi";
  5207. std::string host_and_port;
  5208. host_and_port += HOST;
  5209. host_and_port += ":";
  5210. host_and_port += std::to_string(PORT);
  5211. req.headers.emplace("Host", host_and_port.c_str());
  5212. req.headers.emplace("Accept", "*/*");
  5213. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5214. req.headers.emplace(
  5215. "Header-Name",
  5216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5219. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5220. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5221. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5222. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5223. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5224. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5225. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5226. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5227. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5228. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5229. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5230. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5231. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5232. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5233. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5234. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5235. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5236. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5237. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5238. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5239. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5240. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5241. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5242. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5243. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5244. "@@@@@@@@@@@@@@@@@");
  5245. auto res = std::make_shared<Response>();
  5246. auto error = Error::Success;
  5247. auto ret = cli_.send(req, *res, error);
  5248. ASSERT_TRUE(ret);
  5249. EXPECT_EQ(StatusCode::OK_200, res->status);
  5250. }
  5251. TEST_F(ServerTest, HeaderCountAtLimit) {
  5252. // Test with headers just under the 100 limit
  5253. httplib::Headers headers;
  5254. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5255. // This should keep us just under the 100 header limit
  5256. for (int i = 0; i < 95; i++) {
  5257. std::string name = "X-Test-Header-" + std::to_string(i);
  5258. std::string value = "value" + std::to_string(i);
  5259. headers.emplace(name, value);
  5260. }
  5261. // This should work fine as we're under the limit
  5262. auto res = cli_.Get("/hi", headers);
  5263. EXPECT_TRUE(res);
  5264. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5265. }
  5266. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5267. // Test with many headers to exceed the 100 limit
  5268. httplib::Headers headers;
  5269. // Add 150 headers to definitely exceed the 100 limit
  5270. for (int i = 0; i < 150; i++) {
  5271. std::string name = "X-Test-Header-" + std::to_string(i);
  5272. std::string value = "value" + std::to_string(i);
  5273. headers.emplace(name, value);
  5274. }
  5275. // This should fail due to exceeding header count limit
  5276. cli_.set_keep_alive(true);
  5277. auto res = cli_.Get("/hi", headers);
  5278. // The server should respond with 400 Bad Request
  5279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5280. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5281. EXPECT_EQ("close", res->get_header_value("Connection"));
  5282. EXPECT_FALSE(cli_.is_socket_open());
  5283. }
  5284. TEST_F(ServerTest, PercentEncoding) {
  5285. auto res = cli_.Get("/e%6edwith%");
  5286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5287. EXPECT_EQ(StatusCode::OK_200, res->status);
  5288. }
  5289. TEST_F(ServerTest, PercentEncodingUnicode) {
  5290. auto res = cli_.Get("/e%u006edwith%");
  5291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5292. EXPECT_EQ(StatusCode::OK_200, res->status);
  5293. }
  5294. TEST_F(ServerTest, InvalidPercentEncoding) {
  5295. auto res = cli_.Get("/%endwith%");
  5296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5297. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5298. }
  5299. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5300. auto res = cli_.Get("/%uendwith%");
  5301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5302. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5303. }
  5304. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5305. auto res = cli_.Get("/hello?aaa=bbb%");
  5306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5307. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5308. }
  5309. TEST_F(ServerTest, PlusSignEncoding) {
  5310. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5312. EXPECT_EQ(StatusCode::OK_200, res->status);
  5313. EXPECT_EQ("a +b", res->body);
  5314. }
  5315. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5316. // This test simulates a potential DoS attack using many headers
  5317. // to verify our security fix prevents memory exhaustion
  5318. httplib::Headers attack_headers;
  5319. // Attempt to add many headers like an attacker would (200 headers to far
  5320. // exceed limit)
  5321. for (int i = 0; i < 200; i++) {
  5322. std::string name = "X-Attack-Header-" + std::to_string(i);
  5323. std::string value = "attack_payload_" + std::to_string(i);
  5324. attack_headers.emplace(name, value);
  5325. }
  5326. // Try to POST with excessive headers
  5327. cli_.set_keep_alive(true);
  5328. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5329. // Should either fail or return 400 Bad Request due to security limit
  5330. if (res) {
  5331. // If we get a response, it should be 400 Bad Request
  5332. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5333. EXPECT_EQ("close", res->get_header_value("Connection"));
  5334. }
  5335. EXPECT_FALSE(cli_.is_socket_open());
  5336. }
  5337. TEST_F(ServerTest, MultipartFormData) {
  5338. UploadFormDataItems items = {
  5339. {"text1", "text default", "", ""},
  5340. {"text2", "aωb", "", ""},
  5341. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5342. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5343. {"file3", "", "", "application/octet-stream"},
  5344. {"file4", "", "", " application/json tmp-string "}};
  5345. auto res = cli_.Post("/multipart", items);
  5346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5347. EXPECT_EQ(StatusCode::OK_200, res->status);
  5348. }
  5349. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5350. UploadFormDataItems items = {
  5351. {"text", "default text", "", ""},
  5352. {"multi_text1", "aaaaa", "", ""},
  5353. {"multi_text1", "bbbbb", "", ""},
  5354. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5355. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5356. "application/json"},
  5357. };
  5358. auto res = cli_.Post("/multipart/multi_file_values", items);
  5359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5360. EXPECT_EQ(StatusCode::OK_200, res->status);
  5361. }
  5362. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5363. auto res = cli_.Get("/hi");
  5364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5365. EXPECT_EQ(StatusCode::OK_200, res->status);
  5366. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5367. EXPECT_EQ("Hello World!", res->body);
  5368. }
  5369. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5370. Request req;
  5371. req.method = "POST";
  5372. req.path = "/chunked";
  5373. std::string host_and_port;
  5374. host_and_port += HOST;
  5375. host_and_port += ":";
  5376. host_and_port += std::to_string(PORT);
  5377. req.headers.emplace("Host", host_and_port.c_str());
  5378. req.headers.emplace("Accept", "*/*");
  5379. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5380. req.headers.emplace("Content-Type", "text/plain");
  5381. req.headers.emplace("Content-Length", "0");
  5382. req.headers.emplace(
  5383. "Transfer-Encoding",
  5384. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5385. // Client does not chunk, so make a chunked body manually.
  5386. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5387. auto res = std::make_shared<Response>();
  5388. auto error = Error::Success;
  5389. auto ret = cli_.send(req, *res, error);
  5390. ASSERT_TRUE(ret);
  5391. EXPECT_EQ(StatusCode::OK_200, res->status);
  5392. }
  5393. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5394. // rather than treat them as valid lengths.
  5395. template <typename ClientT>
  5396. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5397. Request req;
  5398. req.method = "POST";
  5399. req.path = "/chunked";
  5400. std::string host_and_port;
  5401. host_and_port += HOST;
  5402. host_and_port += ":";
  5403. host_and_port += std::to_string(PORT);
  5404. req.headers.emplace("Host", host_and_port.c_str());
  5405. req.headers.emplace("Content-Length", "0");
  5406. req.headers.emplace("Transfer-Encoding", "chunked");
  5407. req.body = body;
  5408. auto res = std::make_shared<Response>();
  5409. auto error = Error::Success;
  5410. ASSERT_TRUE(cli.send(req, *res, error));
  5411. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5412. }
  5413. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5414. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5415. }
  5416. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5417. expect_chunked_body_rejected(
  5418. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5419. }
  5420. TEST_F(ServerTest, GetStreamed2) {
  5421. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5423. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5424. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5425. EXPECT_EQ(true, res->has_header("Content-Range"));
  5426. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5427. EXPECT_EQ(std::string("ab"), res->body);
  5428. }
  5429. TEST_F(ServerTest, GetStreamed) {
  5430. auto res = cli_.Get("/streamed");
  5431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5432. EXPECT_EQ(StatusCode::OK_200, res->status);
  5433. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5434. EXPECT_EQ(std::string("aaabbb"), res->body);
  5435. }
  5436. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5437. auto res = cli_.Get("/streamed-without-length",
  5438. Headers{make_range_header({{0, -1}})});
  5439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5440. EXPECT_EQ(StatusCode::OK_200, res->status);
  5441. EXPECT_EQ(false, res->has_header("Content-Length"));
  5442. EXPECT_EQ(false, res->has_header("Content-Range"));
  5443. EXPECT_EQ(std::string("abcdefg"), res->body);
  5444. }
  5445. TEST_F(ServerTest, GetStreamedWithRange1) {
  5446. auto res =
  5447. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5449. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5450. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5451. EXPECT_EQ(true, res->has_header("Content-Range"));
  5452. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5453. EXPECT_EQ(std::string("def"), res->body);
  5454. }
  5455. TEST_F(ServerTest, GetStreamedWithRange2) {
  5456. auto res =
  5457. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5460. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5461. EXPECT_EQ(true, res->has_header("Content-Range"));
  5462. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5463. EXPECT_EQ(std::string("bcdefg"), res->body);
  5464. }
  5465. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5466. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5468. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5469. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5470. EXPECT_EQ(true, res->has_header("Content-Range"));
  5471. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5472. EXPECT_EQ(std::string("efg"), res->body);
  5473. }
  5474. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5475. auto res =
  5476. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5479. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5480. EXPECT_EQ(false, res->has_header("Content-Range"));
  5481. EXPECT_EQ(0U, res->body.size());
  5482. }
  5483. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5484. // Only a 206 is served as a partial representation. Under any other status
  5485. // `apply_ranges()` reported the full content length, so the body must match
  5486. // that header, and the content provider must never be asked for an offset
  5487. // outside the representation.
  5488. auto check = [&](int status, const char *range) {
  5489. auto path =
  5490. std::string("/streamed-with-range?status=") + std::to_string(status);
  5491. auto ctx = path + " Range: " + range;
  5492. auto res = cli_.Get(path, Headers{{"Range", range}});
  5493. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5494. EXPECT_EQ(status, res->status) << ctx;
  5495. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5496. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5497. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5498. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5499. };
  5500. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5501. check(403, "bytes=3-5");
  5502. // The offset is far past the representation.
  5503. check(403, "bytes=100000-100200");
  5504. // `first_pos` is still -1 here, and the bounds asserts in
  5505. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5506. check(403, "bytes=-3");
  5507. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5508. // multipart branch would have written one that is empty.
  5509. check(403, "bytes=1-2, 4-5");
  5510. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5511. // covers the whole representation.
  5512. check(200, "bytes=3-5");
  5513. check(200, "bytes=1-2, 4-5");
  5514. }
  5515. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5516. auto res =
  5517. cli_.Get("/streamed-with-range",
  5518. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5519. "92233720368547758079223372036854775807"}});
  5520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5521. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5522. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5523. EXPECT_EQ(false, res->has_header("Content-Range"));
  5524. EXPECT_EQ(0U, res->body.size());
  5525. }
  5526. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5527. auto res = cli_.Get(
  5528. "/with-range",
  5529. Headers{{"Range",
  5530. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5531. {"Accept-Encoding", ""}});
  5532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5533. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5534. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5535. EXPECT_EQ(true, res->has_header("Content-Range"));
  5536. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5537. EXPECT_EQ(std::string("abcdefg"), res->body);
  5538. }
  5539. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5540. auto res = cli_.Get("/with-range", Headers{
  5541. {"Range", "bytes=0-"},
  5542. {"Accept-Encoding", ""},
  5543. });
  5544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5545. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5546. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5547. EXPECT_EQ(true, res->has_header("Content-Range"));
  5548. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5549. EXPECT_EQ(std::string("abcdefg"), res->body);
  5550. }
  5551. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5552. auto res = cli_.Get("/streamed-with-range",
  5553. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5555. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5556. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5557. EXPECT_EQ(false, res->has_header("Content-Range"));
  5558. EXPECT_EQ(267U, res->body.size());
  5559. // Check that both range contents are present
  5560. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5561. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5562. // Check that Content-Range headers are present for both ranges
  5563. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5564. std::string::npos);
  5565. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5566. std::string::npos);
  5567. }
  5568. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5569. Ranges ranges;
  5570. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5571. ranges.emplace_back(0, -1);
  5572. }
  5573. auto res = cli_.Get("/streamed-with-range?error",
  5574. Headers{{make_range_header(ranges)}});
  5575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5576. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5577. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5578. EXPECT_EQ(false, res->has_header("Content-Range"));
  5579. EXPECT_EQ(0U, res->body.size());
  5580. }
  5581. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5582. auto res = cli_.Get("/streamed-with-range",
  5583. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5585. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5586. EXPECT_EQ(5U, res->body.size());
  5587. // Check that overlapping ranges are coalesced into a single range
  5588. EXPECT_EQ("bcdef", res->body);
  5589. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5590. // Should be single range, not multipart
  5591. EXPECT_TRUE(res->has_header("Content-Range"));
  5592. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5593. }
  5594. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5595. auto res = cli_.Get("/streamed-with-range",
  5596. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5598. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5599. EXPECT_EQ(268U, res->body.size());
  5600. // Check that both range contents are present
  5601. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5602. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5603. // Check that Content-Range headers are present for both ranges
  5604. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5605. std::string::npos);
  5606. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5607. std::string::npos);
  5608. }
  5609. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5610. auto res = cli_.Get("/streamed-with-range",
  5611. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5613. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5614. EXPECT_EQ(269U, res->body.size());
  5615. // Check that both duplicate range contents are present
  5616. size_t first_abc = res->body.find("abc\r\n");
  5617. EXPECT_TRUE(first_abc != std::string::npos);
  5618. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5619. EXPECT_TRUE(second_abc != std::string::npos);
  5620. // Check that Content-Range headers are present for both ranges
  5621. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5622. EXPECT_TRUE(first_range != std::string::npos);
  5623. size_t second_range =
  5624. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5625. EXPECT_TRUE(second_range != std::string::npos);
  5626. }
  5627. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5628. auto res =
  5629. cli_.Get("/streamed-with-range?error",
  5630. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5632. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5633. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5634. EXPECT_EQ(false, res->has_header("Content-Range"));
  5635. EXPECT_EQ(0U, res->body.size());
  5636. }
  5637. TEST_F(ServerTest, GetStreamedEndless) {
  5638. uint64_t offset = 0;
  5639. auto res = cli_.Get("/streamed-cancel",
  5640. [&](const char * /*data*/, uint64_t data_length) {
  5641. if (offset < 100) {
  5642. offset += data_length;
  5643. return true;
  5644. }
  5645. return false;
  5646. });
  5647. ASSERT_TRUE(!res);
  5648. EXPECT_EQ(Error::Canceled, res.error());
  5649. }
  5650. TEST_F(ServerTest, ClientStop) {
  5651. std::atomic_size_t count{4};
  5652. std::vector<std::thread> threads;
  5653. for (auto i = count.load(); i != 0; --i) {
  5654. threads.emplace_back([&]() {
  5655. auto res = cli_.Get("/streamed-cancel",
  5656. [&](const char *, uint64_t) { return true; });
  5657. --count;
  5658. ASSERT_TRUE(!res);
  5659. EXPECT_TRUE(res.error() == Error::Canceled ||
  5660. res.error() == Error::Read || res.error() == Error::Write);
  5661. });
  5662. }
  5663. std::this_thread::sleep_for(std::chrono::seconds(2));
  5664. while (count != 0) {
  5665. cli_.stop();
  5666. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5667. }
  5668. for (auto &t : threads) {
  5669. t.join();
  5670. }
  5671. }
  5672. TEST_F(ServerTest, GetWithRange1) {
  5673. auto res = cli_.Get("/with-range", Headers{
  5674. make_range_header({{3, 5}}),
  5675. {"Accept-Encoding", ""},
  5676. });
  5677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5678. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5679. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5680. EXPECT_EQ(true, res->has_header("Content-Range"));
  5681. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5682. EXPECT_EQ(std::string("def"), res->body);
  5683. }
  5684. TEST_F(ServerTest, GetWithRange2) {
  5685. auto res = cli_.Get("/with-range", Headers{
  5686. make_range_header({{1, -1}}),
  5687. {"Accept-Encoding", ""},
  5688. });
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5691. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5692. EXPECT_EQ(true, res->has_header("Content-Range"));
  5693. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5694. EXPECT_EQ(std::string("bcdefg"), res->body);
  5695. }
  5696. TEST_F(ServerTest, GetWithRange3) {
  5697. auto res = cli_.Get("/with-range", Headers{
  5698. make_range_header({{0, 0}}),
  5699. {"Accept-Encoding", ""},
  5700. });
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5703. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5704. EXPECT_EQ(true, res->has_header("Content-Range"));
  5705. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5706. EXPECT_EQ(std::string("a"), res->body);
  5707. }
  5708. TEST_F(ServerTest, GetWithRange4) {
  5709. auto res = cli_.Get("/with-range", Headers{
  5710. make_range_header({{-1, 2}}),
  5711. {"Accept-Encoding", ""},
  5712. });
  5713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5714. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5715. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5716. EXPECT_EQ(true, res->has_header("Content-Range"));
  5717. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5718. EXPECT_EQ(std::string("fg"), res->body);
  5719. }
  5720. TEST_F(ServerTest, GetWithRange5) {
  5721. auto res = cli_.Get("/with-range", Headers{
  5722. make_range_header({{0, 5}}),
  5723. {"Accept-Encoding", ""},
  5724. });
  5725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5726. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5727. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5728. EXPECT_EQ(true, res->has_header("Content-Range"));
  5729. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5730. EXPECT_EQ(std::string("abcdef"), res->body);
  5731. }
  5732. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5733. auto res =
  5734. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5736. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5737. }
  5738. TEST_F(ServerTest, GetWithRangeMultipart) {
  5739. auto res =
  5740. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5742. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5743. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5744. EXPECT_EQ(false, res->has_header("Content-Range"));
  5745. EXPECT_EQ(267U, res->body.size());
  5746. }
  5747. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5748. auto res = cli_.Get("/with-range",
  5749. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5751. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5752. }
  5753. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5754. auto res = cli_.Get("/with-range-customized-response",
  5755. Headers{{make_range_header({{1, 2}})}});
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5758. EXPECT_EQ(true, res->has_header("Content-Length"));
  5759. EXPECT_EQ(false, res->has_header("Content-Range"));
  5760. EXPECT_EQ(JSON_DATA, res->body);
  5761. }
  5762. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5763. auto res = cli_.Get("/with-range-customized-response",
  5764. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5766. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5767. EXPECT_EQ(true, res->has_header("Content-Length"));
  5768. EXPECT_EQ(false, res->has_header("Content-Range"));
  5769. EXPECT_EQ(JSON_DATA, res->body);
  5770. }
  5771. TEST_F(ServerTest, Issue1772) {
  5772. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5774. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5775. }
  5776. TEST_F(ServerTest, Issue609) {
  5777. auto res = cli_.Delete("/issue609");
  5778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5779. EXPECT_EQ(StatusCode::OK_200, res->status);
  5780. EXPECT_EQ(std::string("ok"), res->body);
  5781. }
  5782. TEST_F(ServerTest, GetStreamedChunked) {
  5783. auto res = cli_.Get("/streamed-chunked");
  5784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5785. EXPECT_EQ(StatusCode::OK_200, res->status);
  5786. EXPECT_EQ(std::string("123456789"), res->body);
  5787. }
  5788. TEST_F(ServerTest, GetStreamedChunked2) {
  5789. auto res = cli_.Get("/streamed-chunked2");
  5790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5791. EXPECT_EQ(StatusCode::OK_200, res->status);
  5792. EXPECT_EQ(std::string("123456789"), res->body);
  5793. }
  5794. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5795. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5797. EXPECT_EQ(StatusCode::OK_200, res->status);
  5798. EXPECT_EQ(std::string("123456789"), res->body);
  5799. EXPECT_TRUE(res->has_header("Trailer"));
  5800. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5801. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5802. // Trailers are now stored separately from headers (security fix)
  5803. EXPECT_EQ(2U, res->trailers.size());
  5804. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5805. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5806. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5807. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5808. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5809. // Verify trailers are NOT in headers (security verification)
  5810. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5811. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5812. }
  5813. TEST_F(ServerTest, LargeChunkedPost) {
  5814. Request req;
  5815. req.method = "POST";
  5816. req.path = "/large-chunked";
  5817. std::string host_and_port;
  5818. host_and_port += HOST;
  5819. host_and_port += ":";
  5820. host_and_port += std::to_string(PORT);
  5821. req.headers.emplace("Host", host_and_port.c_str());
  5822. req.headers.emplace("Accept", "*/*");
  5823. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5824. req.headers.emplace("Content-Type", "text/plain");
  5825. req.headers.emplace("Content-Length", "0");
  5826. req.headers.emplace("Transfer-Encoding", "chunked");
  5827. std::string long_string(30 * 1024u, 'a');
  5828. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5829. // Attempt to make a large enough post to exceed OS buffers, to test that
  5830. // the server handles short reads if the full chunk data isn't available.
  5831. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5832. auto res = std::make_shared<Response>();
  5833. auto error = Error::Success;
  5834. auto ret = cli_.send(req, *res, error);
  5835. ASSERT_TRUE(ret);
  5836. EXPECT_EQ(StatusCode::OK_200, res->status);
  5837. }
  5838. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5839. auto res = cli_.Get("/remote_addr");
  5840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5841. EXPECT_EQ(StatusCode::OK_200, res->status);
  5842. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5843. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5844. }
  5845. TEST_F(ServerTest, GetMethodLocalAddr) {
  5846. auto res = cli_.Get("/local_addr");
  5847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5848. EXPECT_EQ(StatusCode::OK_200, res->status);
  5849. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5850. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5851. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5852. }
  5853. TEST_F(ServerTest, HTTPResponseSplitting) {
  5854. auto res = cli_.Get("/http_response_splitting");
  5855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5856. EXPECT_EQ(StatusCode::OK_200, res->status);
  5857. }
  5858. TEST_F(ServerTest, SlowRequest) {
  5859. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5860. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5861. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5862. }
  5863. #if 0
  5864. TEST_F(ServerTest, SlowPost) {
  5865. char buffer[64 * 1024];
  5866. memset(buffer, 0x42, sizeof(buffer));
  5867. auto res = cli_.Post(
  5868. "/slowpost", 64 * 1024 * 1024,
  5869. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5870. auto ret = sink.write(buffer, sizeof(buffer));
  5871. EXPECT_TRUE(ret);
  5872. return true;
  5873. },
  5874. "text/plain");
  5875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5876. EXPECT_EQ(StatusCode::OK_200, res->status);
  5877. }
  5878. TEST_F(ServerTest, SlowPostFail) {
  5879. char buffer[64 * 1024];
  5880. memset(buffer, 0x42, sizeof(buffer));
  5881. cli_.set_write_timeout(std::chrono::seconds(0));
  5882. auto res = cli_.Post(
  5883. "/slowpost", 64 * 1024 * 1024,
  5884. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5885. sink.write(buffer, sizeof(buffer));
  5886. return true;
  5887. },
  5888. "text/plain");
  5889. ASSERT_TRUE(!res);
  5890. EXPECT_EQ(Error::Write, res.error());
  5891. }
  5892. #endif
  5893. TEST_F(ServerTest, Put) {
  5894. auto res = cli_.Put("/put", "PUT", "text/plain");
  5895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5896. EXPECT_EQ(StatusCode::OK_200, res->status);
  5897. EXPECT_EQ("PUT", res->body);
  5898. }
  5899. TEST_F(ServerTest, PutWithContentProvider) {
  5900. auto res = cli_.Put(
  5901. "/put", 3,
  5902. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5903. sink.os << "PUT";
  5904. return true;
  5905. },
  5906. "text/plain");
  5907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5908. EXPECT_EQ(StatusCode::OK_200, res->status);
  5909. EXPECT_EQ("PUT", res->body);
  5910. }
  5911. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5912. auto res = cli_.Post(
  5913. "/post", 42,
  5914. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5915. return false;
  5916. },
  5917. "text/plain");
  5918. ASSERT_TRUE(!res);
  5919. EXPECT_EQ(Error::Canceled, res.error());
  5920. }
  5921. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5922. auto res = cli_.Put(
  5923. "/put",
  5924. [](size_t /*offset*/, DataSink &sink) {
  5925. sink.os << "PUT";
  5926. sink.done();
  5927. return true;
  5928. },
  5929. "text/plain");
  5930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5931. EXPECT_EQ(StatusCode::OK_200, res->status);
  5932. EXPECT_EQ("PUT", res->body);
  5933. }
  5934. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5935. auto res = cli_.Post(
  5936. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5937. "text/plain");
  5938. ASSERT_TRUE(!res);
  5939. EXPECT_EQ(Error::Canceled, res.error());
  5940. }
  5941. TEST_F(ServerTest, PostLoopBack) {
  5942. std::string body;
  5943. auto res = cli_.Post(
  5944. "/post-loopback", 9,
  5945. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5946. EXPECT_EQ(9u, length);
  5947. sink.write("123", 3);
  5948. sink.write("456", 3);
  5949. sink.write("789", 3);
  5950. return true;
  5951. },
  5952. "text/plain",
  5953. [&body](const char *data, size_t data_length) {
  5954. body.append(data, data_length);
  5955. return true;
  5956. });
  5957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5958. EXPECT_EQ(StatusCode::OK_200, res->status);
  5959. EXPECT_EQ("123456789", body);
  5960. }
  5961. TEST_F(ServerTest, PutLoopBack) {
  5962. std::string body;
  5963. auto res = cli_.Put(
  5964. "/put-loopback", 9,
  5965. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5966. EXPECT_EQ(9u, length);
  5967. sink.write("123", 3);
  5968. sink.write("456", 3);
  5969. sink.write("789", 3);
  5970. return true;
  5971. },
  5972. "text/plain",
  5973. [&body](const char *data, size_t data_length) {
  5974. body.append(data, data_length);
  5975. return true;
  5976. });
  5977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5978. EXPECT_EQ(StatusCode::OK_200, res->status);
  5979. EXPECT_EQ("123456789", body);
  5980. }
  5981. TEST_F(ServerTest, PatchLoopBack) {
  5982. std::string body;
  5983. auto res = cli_.Patch(
  5984. "/patch-loopback", 9,
  5985. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5986. EXPECT_EQ(9u, length);
  5987. sink.write("123", 3);
  5988. sink.write("456", 3);
  5989. sink.write("789", 3);
  5990. return true;
  5991. },
  5992. "text/plain",
  5993. [&body](const char *data, size_t data_length) {
  5994. body.append(data, data_length);
  5995. return true;
  5996. });
  5997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5998. EXPECT_EQ(StatusCode::OK_200, res->status);
  5999. EXPECT_EQ("123456789", body);
  6000. }
  6001. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6002. std::string body;
  6003. auto res = cli_.Post(
  6004. "/post-loopback",
  6005. [](size_t /*offset*/, DataSink &sink) {
  6006. sink.write("123", 3);
  6007. sink.write("456", 3);
  6008. sink.write("789", 3);
  6009. sink.done();
  6010. return true;
  6011. },
  6012. "text/plain",
  6013. [&body](const char *data, size_t data_length) {
  6014. body.append(data, data_length);
  6015. return true;
  6016. });
  6017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6018. EXPECT_EQ(StatusCode::OK_200, res->status);
  6019. EXPECT_EQ("123456789", body);
  6020. }
  6021. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6022. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6023. cli_.set_compress(true);
  6024. auto res = cli_.Put(
  6025. "/put", 3,
  6026. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6027. sink.os << "PUT";
  6028. return true;
  6029. },
  6030. "text/plain");
  6031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6032. EXPECT_EQ(StatusCode::OK_200, res->status);
  6033. EXPECT_EQ("PUT", res->body);
  6034. }
  6035. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6036. cli_.set_compress(true);
  6037. auto res = cli_.Post(
  6038. "/post", 42,
  6039. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6040. return false;
  6041. },
  6042. "text/plain");
  6043. ASSERT_TRUE(!res);
  6044. EXPECT_EQ(Error::Canceled, res.error());
  6045. }
  6046. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6047. cli_.set_compress(true);
  6048. auto res = cli_.Put(
  6049. "/put",
  6050. [](size_t /*offset*/, DataSink &sink) {
  6051. sink.os << "PUT";
  6052. sink.done();
  6053. return true;
  6054. },
  6055. "text/plain");
  6056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6057. EXPECT_EQ(StatusCode::OK_200, res->status);
  6058. EXPECT_EQ("PUT", res->body);
  6059. }
  6060. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6061. cli_.set_compress(true);
  6062. auto res = cli_.Post(
  6063. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6064. "text/plain");
  6065. ASSERT_TRUE(!res);
  6066. EXPECT_EQ(Error::Canceled, res.error());
  6067. }
  6068. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6069. cli_.set_compress(true);
  6070. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. EXPECT_EQ(StatusCode::OK_200, res->status);
  6073. EXPECT_EQ(LARGE_DATA, res->body);
  6074. }
  6075. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6076. #ifdef CPPHTTPLIB_SSL_ENABLED
  6077. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6078. Client cli(s.c_str());
  6079. cli.enable_server_certificate_verification(false);
  6080. #else
  6081. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6082. Client cli(s.c_str());
  6083. #endif
  6084. cli.set_compress(true);
  6085. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6087. EXPECT_EQ(StatusCode::OK_200, res->status);
  6088. EXPECT_EQ(LARGE_DATA, res->body);
  6089. // The compressed size should be less than a 10th of the original. May vary
  6090. // depending on the zlib library.
  6091. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6092. static_cast<uint64_t>(10 * 1024 * 1024));
  6093. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6094. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6095. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6096. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6097. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6098. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6099. #endif
  6100. }
  6101. TEST_F(ServerTest, PutContentWithDeflate) {
  6102. cli_.set_compress(false);
  6103. Headers headers;
  6104. headers.emplace("Content-Encoding", "deflate");
  6105. // PUT in deflate format:
  6106. auto res = cli_.Put("/put", headers,
  6107. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6109. EXPECT_EQ(StatusCode::OK_200, res->status);
  6110. EXPECT_EQ("PUT", res->body);
  6111. }
  6112. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6113. Headers headers;
  6114. headers.emplace("Accept-Encoding", "gzip, deflate");
  6115. auto res = cli_.Get("/streamed-chunked", headers);
  6116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6117. EXPECT_EQ(StatusCode::OK_200, res->status);
  6118. EXPECT_EQ(std::string("123456789"), res->body);
  6119. }
  6120. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6121. Headers headers;
  6122. headers.emplace("Accept-Encoding", "gzip, deflate");
  6123. auto res = cli_.Get("/streamed-chunked2", headers);
  6124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6125. EXPECT_EQ(StatusCode::OK_200, res->status);
  6126. EXPECT_EQ(std::string("123456789"), res->body);
  6127. }
  6128. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6129. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6131. EXPECT_EQ(StatusCode::OK_200, res->status);
  6132. }
  6133. TEST(GzipDecompressor, ChunkedDecompression) {
  6134. std::string data;
  6135. for (size_t i = 0; i < 32 * 1024; ++i) {
  6136. data.push_back(static_cast<char>('a' + i % 26));
  6137. }
  6138. std::string compressed_data;
  6139. {
  6140. httplib::detail::gzip_compressor compressor;
  6141. bool result = compressor.compress(
  6142. data.data(), data.size(),
  6143. /*last=*/true,
  6144. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6145. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6146. compressed_data_size);
  6147. return true;
  6148. });
  6149. ASSERT_TRUE(result);
  6150. }
  6151. std::string decompressed_data;
  6152. {
  6153. httplib::detail::gzip_decompressor decompressor;
  6154. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6155. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6156. size_t chunk_size = 130;
  6157. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6158. chunk_begin += chunk_size) {
  6159. size_t current_chunk_size =
  6160. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6161. bool result = decompressor.decompress(
  6162. compressed_data.data() + chunk_begin, current_chunk_size,
  6163. [&](const char *decompressed_data_chunk,
  6164. size_t decompressed_data_chunk_size) {
  6165. decompressed_data.insert(decompressed_data.size(),
  6166. decompressed_data_chunk,
  6167. decompressed_data_chunk_size);
  6168. return true;
  6169. });
  6170. ASSERT_TRUE(result);
  6171. }
  6172. }
  6173. ASSERT_EQ(data, decompressed_data);
  6174. }
  6175. TEST(GzipDecompressor, DeflateDecompression) {
  6176. std::string original_text = "Raw deflate without gzip";
  6177. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6178. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6179. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6180. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6181. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6182. std::string decompressed_data;
  6183. {
  6184. httplib::detail::gzip_decompressor decompressor;
  6185. bool result = decompressor.decompress(
  6186. compressed_data.data(), compressed_data.size(),
  6187. [&](const char *decompressed_data_chunk,
  6188. size_t decompressed_data_chunk_size) {
  6189. decompressed_data.insert(decompressed_data.size(),
  6190. decompressed_data_chunk,
  6191. decompressed_data_chunk_size);
  6192. return true;
  6193. });
  6194. ASSERT_TRUE(result);
  6195. }
  6196. ASSERT_EQ(original_text, decompressed_data);
  6197. }
  6198. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6199. std::string original_text = "Raw deflate without gzip";
  6200. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6201. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6202. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6203. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6204. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6205. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6206. std::string decompressed_data;
  6207. {
  6208. httplib::detail::gzip_decompressor decompressor;
  6209. bool result = decompressor.decompress(
  6210. compressed_data.data(), compressed_data.size(),
  6211. [&](const char *decompressed_data_chunk,
  6212. size_t decompressed_data_chunk_size) {
  6213. decompressed_data.insert(decompressed_data.size(),
  6214. decompressed_data_chunk,
  6215. decompressed_data_chunk_size);
  6216. return true;
  6217. });
  6218. ASSERT_TRUE(result);
  6219. }
  6220. ASSERT_EQ(original_text, decompressed_data);
  6221. }
  6222. #endif
  6223. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6224. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6225. Headers headers;
  6226. headers.emplace("Accept-Encoding", "br");
  6227. auto res = cli_.Get("/streamed-chunked", headers);
  6228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6229. EXPECT_EQ(StatusCode::OK_200, res->status);
  6230. EXPECT_EQ(std::string("123456789"), res->body);
  6231. }
  6232. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6233. Headers headers;
  6234. headers.emplace("Accept-Encoding", "br");
  6235. auto res = cli_.Get("/streamed-chunked2", headers);
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. EXPECT_EQ(StatusCode::OK_200, res->status);
  6238. EXPECT_EQ(std::string("123456789"), res->body);
  6239. }
  6240. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6241. cli_.set_compress(true);
  6242. auto res = cli_.Put(
  6243. "/put", 3,
  6244. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6245. sink.os << "PUT";
  6246. return true;
  6247. },
  6248. "text/plain");
  6249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6250. EXPECT_EQ(StatusCode::OK_200, res->status);
  6251. EXPECT_EQ("PUT", res->body);
  6252. }
  6253. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6254. cli_.set_compress(true);
  6255. auto res = cli_.Put(
  6256. "/put",
  6257. [](size_t /*offset*/, DataSink &sink) {
  6258. sink.os << "PUT";
  6259. sink.done();
  6260. return true;
  6261. },
  6262. "text/plain");
  6263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6264. EXPECT_EQ(StatusCode::OK_200, res->status);
  6265. EXPECT_EQ("PUT", res->body);
  6266. }
  6267. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6268. cli_.set_compress(true);
  6269. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6271. EXPECT_EQ(StatusCode::OK_200, res->status);
  6272. EXPECT_EQ(LARGE_DATA, res->body);
  6273. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6274. }
  6275. #endif
  6276. TEST_F(ServerTest, Patch) {
  6277. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. EXPECT_EQ(StatusCode::OK_200, res->status);
  6280. EXPECT_EQ("PATCH", res->body);
  6281. }
  6282. TEST_F(ServerTest, Delete) {
  6283. auto res = cli_.Delete("/delete");
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. EXPECT_EQ(StatusCode::OK_200, res->status);
  6286. EXPECT_EQ("DELETE", res->body);
  6287. }
  6288. TEST_F(ServerTest, DeleteContentReceiver) {
  6289. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. EXPECT_EQ(StatusCode::OK_200, res->status);
  6292. EXPECT_EQ("content", res->body);
  6293. }
  6294. TEST_F(ServerTest, Options) {
  6295. auto res = cli_.Options("*");
  6296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6297. EXPECT_EQ(StatusCode::OK_200, res->status);
  6298. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6299. EXPECT_TRUE(res->body.empty());
  6300. }
  6301. TEST_F(ServerTest, URL) {
  6302. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::OK_200, res->status);
  6305. }
  6306. TEST_F(ServerTest, ArrayParam) {
  6307. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6309. EXPECT_EQ(StatusCode::OK_200, res->status);
  6310. }
  6311. TEST_F(ServerTest, ArrayParamValues) {
  6312. auto res =
  6313. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6315. EXPECT_EQ(StatusCode::OK_200, res->status);
  6316. }
  6317. TEST_F(ServerTest, NoMultipleHeaders) {
  6318. Headers headers = {{"Content-Length", "5"}};
  6319. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6320. "text/plain");
  6321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6322. EXPECT_EQ(StatusCode::OK_200, res->status);
  6323. }
  6324. TEST_F(ServerTest, PostContentReceiver) {
  6325. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6327. ASSERT_EQ(StatusCode::OK_200, res->status);
  6328. ASSERT_EQ("content", res->body);
  6329. }
  6330. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6331. UploadFormDataItems items = {
  6332. {"text1", "text default", "", ""},
  6333. {"text2", "aωb", "", ""},
  6334. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6335. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6336. {"file3", "", "", "application/octet-stream"},
  6337. };
  6338. auto res = cli_.Post("/content_receiver", items);
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::OK_200, res->status);
  6341. }
  6342. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6343. UploadFormDataItems items = {
  6344. {"text1", "text default", "", ""},
  6345. {"text2", "aωb", "", ""},
  6346. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6347. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6348. {"file3", "", "", "application/octet-stream"},
  6349. };
  6350. auto boundary = std::string("+++++");
  6351. std::string body;
  6352. for (const auto &item : items) {
  6353. body += "--" + boundary + "\r\n";
  6354. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6355. if (!item.filename.empty()) {
  6356. body += "; filename=\"" + item.filename + "\"";
  6357. }
  6358. body += "\r\n";
  6359. if (!item.content_type.empty()) {
  6360. body += "Content-Type: " + item.content_type + "\r\n";
  6361. }
  6362. body += "\r\n";
  6363. body += item.content + "\r\n";
  6364. }
  6365. body += "--" + boundary + "--\r\n";
  6366. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6367. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. EXPECT_EQ(StatusCode::OK_200, res->status);
  6370. }
  6371. TEST(MultipartFormDataTest, FieldEscaping) {
  6372. Server svr;
  6373. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6374. const ContentReader &content_reader) {
  6375. ASSERT_TRUE(req.is_multipart_form_data());
  6376. std::vector<FormData> received;
  6377. content_reader(
  6378. [&](const FormData &file) {
  6379. received.push_back(file);
  6380. return true;
  6381. },
  6382. [&](const char *data, size_t data_length) {
  6383. received.back().content.append(data, data_length);
  6384. return true;
  6385. });
  6386. // '"', CR and LF in names and filenames are escaped following the
  6387. // WHATWG HTML standard, so each part still parses as a single part
  6388. // with no injected headers. Content types get CR/LF escaped too,
  6389. // while '"' (legal there, e.g. quoted charset) is preserved.
  6390. ASSERT_EQ(4U, received.size());
  6391. EXPECT_EQ("na%22me", received[0].name);
  6392. EXPECT_EQ("quoted name", received[0].content);
  6393. EXPECT_EQ("file", received[1].name);
  6394. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6395. received[1].filename);
  6396. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6397. EXPECT_EQ("injected", received[1].content);
  6398. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6399. EXPECT_EQ("my%22file.txt", received[2].filename);
  6400. EXPECT_EQ("cr lf name", received[2].content);
  6401. EXPECT_EQ("typed", received[3].name);
  6402. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6403. received[3].content_type);
  6404. EXPECT_EQ("typed content", received[3].content);
  6405. });
  6406. auto port = svr.bind_to_any_port("localhost");
  6407. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6408. auto se = detail::scope_exit([&] {
  6409. svr.stop();
  6410. t.join();
  6411. ASSERT_FALSE(svr.is_running());
  6412. });
  6413. svr.wait_until_ready();
  6414. Client cli("localhost", port);
  6415. UploadFormDataItems items = {
  6416. {"na\"me", "quoted name", "", ""},
  6417. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6418. "application/octet-stream"},
  6419. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6420. {"typed", "typed content", "",
  6421. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6422. };
  6423. auto res = cli.Post("/post", items);
  6424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6425. EXPECT_EQ(StatusCode::OK_200, res->status);
  6426. }
  6427. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6428. const UploadFormDataItems items = {
  6429. {"name1", "Content 1", "", ""},
  6430. {"name2", "Content 2", "file2.txt", "text/plain"},
  6431. };
  6432. Server svr;
  6433. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6434. const ContentReader &content_reader) {
  6435. ASSERT_TRUE(req.is_multipart_form_data());
  6436. std::vector<FormData> received;
  6437. content_reader(
  6438. [&](const FormData &file) {
  6439. received.push_back(file);
  6440. return true;
  6441. },
  6442. [&](const char *data, size_t data_length) {
  6443. received.back().content.append(data, data_length);
  6444. return true;
  6445. });
  6446. ASSERT_EQ(2U, received.size());
  6447. EXPECT_EQ("name1", received[0].name);
  6448. EXPECT_EQ("Content 1", received[0].content);
  6449. EXPECT_EQ("name2", received[1].name);
  6450. EXPECT_EQ("Content 2", received[1].content);
  6451. EXPECT_EQ("file2.txt", received[1].filename);
  6452. EXPECT_EQ("text/plain", received[1].content_type);
  6453. });
  6454. auto port = svr.bind_to_any_port("localhost");
  6455. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6456. auto se = detail::scope_exit([&] {
  6457. svr.stop();
  6458. t.join();
  6459. ASSERT_FALSE(svr.is_running());
  6460. });
  6461. svr.wait_until_ready();
  6462. Client cli("localhost", port);
  6463. // Whole-body serialization with a generated boundary
  6464. {
  6465. MultipartFormDataWriter writer;
  6466. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6467. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6468. writer.content_type());
  6469. auto body = writer.serialize(items);
  6470. EXPECT_EQ(body.size(), writer.content_length(items));
  6471. auto res = cli.Post("/post", body, writer.content_type());
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::OK_200, res->status);
  6474. }
  6475. // Per-part framing with a custom boundary via a content provider
  6476. {
  6477. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6478. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6479. MultipartFormDataWriter writer("custom-boundary_123");
  6480. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6481. std::string body;
  6482. for (const auto &item : items) {
  6483. body += writer.item_begin(item);
  6484. body += item.content;
  6485. body += MultipartFormDataWriter::item_end();
  6486. }
  6487. body += writer.finish();
  6488. EXPECT_EQ(body.size(), writer.content_length(items));
  6489. auto res = cli.Post(
  6490. "/post", body.size(),
  6491. [&](size_t offset, size_t length, DataSink &sink) {
  6492. sink.write(body.data() + offset, length);
  6493. return true;
  6494. },
  6495. writer.content_type());
  6496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6497. EXPECT_EQ(StatusCode::OK_200, res->status);
  6498. }
  6499. }
  6500. TEST_F(ServerTest, PostContentReceiverGzip) {
  6501. cli_.set_compress(true);
  6502. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6504. ASSERT_EQ(StatusCode::OK_200, res->status);
  6505. ASSERT_EQ("content", res->body);
  6506. }
  6507. TEST_F(ServerTest, PutContentReceiver) {
  6508. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6510. ASSERT_EQ(StatusCode::OK_200, res->status);
  6511. ASSERT_EQ("content", res->body);
  6512. }
  6513. TEST_F(ServerTest, PatchContentReceiver) {
  6514. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. ASSERT_EQ(StatusCode::OK_200, res->status);
  6517. ASSERT_EQ("content", res->body);
  6518. }
  6519. template <typename ClientType>
  6520. void TestWithHeadersAndContentReceiver(
  6521. ClientType &cli,
  6522. std::function<Result(ClientType &, const std::string &, const Headers &,
  6523. const std::string &, const std::string &,
  6524. ContentReceiver, DownloadProgress)>
  6525. request_func) {
  6526. Headers headers;
  6527. headers.emplace("X-Custom-Header", "test-value");
  6528. std::string received_body;
  6529. auto res = request_func(
  6530. cli, "/content_receiver", headers, "content", "application/json",
  6531. [&](const char *data, size_t data_length) {
  6532. received_body.append(data, data_length);
  6533. return true;
  6534. },
  6535. nullptr);
  6536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6537. EXPECT_EQ(StatusCode::OK_200, res->status);
  6538. EXPECT_EQ("content", received_body);
  6539. }
  6540. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6541. #ifdef CPPHTTPLIB_SSL_ENABLED
  6542. using ClientT = SSLClient;
  6543. #else
  6544. using ClientT = Client;
  6545. #endif
  6546. TestWithHeadersAndContentReceiver<ClientT>(
  6547. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6548. const std::string &body, const std::string &content_type,
  6549. ContentReceiver receiver, DownloadProgress progress) {
  6550. return cli.Post(path, headers, body, content_type, receiver, progress);
  6551. });
  6552. }
  6553. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6554. #ifdef CPPHTTPLIB_SSL_ENABLED
  6555. using ClientT = SSLClient;
  6556. #else
  6557. using ClientT = Client;
  6558. #endif
  6559. TestWithHeadersAndContentReceiver<ClientT>(
  6560. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6561. const std::string &body, const std::string &content_type,
  6562. ContentReceiver receiver, DownloadProgress progress) {
  6563. return cli.Put(path, headers, body, content_type, receiver, progress);
  6564. });
  6565. }
  6566. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6567. #ifdef CPPHTTPLIB_SSL_ENABLED
  6568. using ClientT = SSLClient;
  6569. #else
  6570. using ClientT = Client;
  6571. #endif
  6572. TestWithHeadersAndContentReceiver<ClientT>(
  6573. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6574. const std::string &body, const std::string &content_type,
  6575. ContentReceiver receiver, DownloadProgress progress) {
  6576. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6577. });
  6578. }
  6579. template <typename ClientType>
  6580. void TestWithHeadersAndContentReceiverWithProgress(
  6581. ClientType &cli,
  6582. std::function<Result(ClientType &, const std::string &, const Headers &,
  6583. const std::string &, const std::string &,
  6584. ContentReceiver, DownloadProgress)>
  6585. request_func) {
  6586. Headers headers;
  6587. headers.emplace("X-Test-Header", "progress-test");
  6588. std::string received_body;
  6589. auto progress_called = false;
  6590. auto res = request_func(
  6591. cli, "/content_receiver", headers, "content", "text/plain",
  6592. [&](const char *data, size_t data_length) {
  6593. received_body.append(data, data_length);
  6594. return true;
  6595. },
  6596. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6597. progress_called = true;
  6598. return true;
  6599. });
  6600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6601. EXPECT_EQ(StatusCode::OK_200, res->status);
  6602. EXPECT_EQ("content", received_body);
  6603. EXPECT_TRUE(progress_called);
  6604. }
  6605. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6606. #ifdef CPPHTTPLIB_SSL_ENABLED
  6607. using ClientT = SSLClient;
  6608. #else
  6609. using ClientT = Client;
  6610. #endif
  6611. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6612. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6613. const std::string &body, const std::string &content_type,
  6614. ContentReceiver receiver, DownloadProgress progress) {
  6615. return cli.Post(path, headers, body, content_type, receiver, progress);
  6616. });
  6617. }
  6618. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6619. #ifdef CPPHTTPLIB_SSL_ENABLED
  6620. using ClientT = SSLClient;
  6621. #else
  6622. using ClientT = Client;
  6623. #endif
  6624. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6625. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6626. const std::string &body, const std::string &content_type,
  6627. ContentReceiver receiver, DownloadProgress progress) {
  6628. return cli.Put(path, headers, body, content_type, receiver, progress);
  6629. });
  6630. }
  6631. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6632. #ifdef CPPHTTPLIB_SSL_ENABLED
  6633. using ClientT = SSLClient;
  6634. #else
  6635. using ClientT = Client;
  6636. #endif
  6637. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6638. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6639. const std::string &body, const std::string &content_type,
  6640. ContentReceiver receiver, DownloadProgress progress) {
  6641. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6642. });
  6643. }
  6644. template <typename ClientType>
  6645. void TestWithHeadersAndContentReceiverError(
  6646. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6647. const Headers &, const std::string &,
  6648. const std::string &, ContentReceiver)>
  6649. request_func) {
  6650. Headers headers;
  6651. headers.emplace("X-Error-Test", "true");
  6652. std::string received_body;
  6653. auto receiver_failed = false;
  6654. auto res =
  6655. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6656. [&](const char *data, size_t data_length) {
  6657. received_body.append(data, data_length);
  6658. receiver_failed = true;
  6659. return false;
  6660. });
  6661. ASSERT_FALSE(res);
  6662. EXPECT_TRUE(receiver_failed);
  6663. }
  6664. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6665. #ifdef CPPHTTPLIB_SSL_ENABLED
  6666. using ClientT = SSLClient;
  6667. #else
  6668. using ClientT = Client;
  6669. #endif
  6670. TestWithHeadersAndContentReceiverError<ClientT>(
  6671. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6672. const std::string &body, const std::string &content_type,
  6673. ContentReceiver receiver) {
  6674. return cli.Post(path, headers, body, content_type, receiver);
  6675. });
  6676. }
  6677. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6678. #ifdef CPPHTTPLIB_SSL_ENABLED
  6679. using ClientT = SSLClient;
  6680. #else
  6681. using ClientT = Client;
  6682. #endif
  6683. TestWithHeadersAndContentReceiverError<ClientT>(
  6684. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6685. const std::string &body, const std::string &content_type,
  6686. ContentReceiver receiver) {
  6687. return cli.Put(path, headers, body, content_type, receiver);
  6688. });
  6689. }
  6690. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6691. #ifdef CPPHTTPLIB_SSL_ENABLED
  6692. using ClientT = SSLClient;
  6693. #else
  6694. using ClientT = Client;
  6695. #endif
  6696. TestWithHeadersAndContentReceiverError<ClientT>(
  6697. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6698. const std::string &body, const std::string &content_type,
  6699. ContentReceiver receiver) {
  6700. return cli.Patch(path, headers, body, content_type, receiver);
  6701. });
  6702. }
  6703. TEST_F(ServerTest, PostQueryStringAndBody) {
  6704. auto res =
  6705. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6707. ASSERT_EQ(StatusCode::OK_200, res->status);
  6708. }
  6709. TEST_F(ServerTest, HTTP2Magic) {
  6710. Request req;
  6711. req.method = "PRI";
  6712. req.path = "*";
  6713. req.body = "SM";
  6714. auto res = std::make_shared<Response>();
  6715. auto error = Error::Success;
  6716. auto ret = cli_.send(req, *res, error);
  6717. ASSERT_TRUE(ret);
  6718. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6719. }
  6720. TEST_F(ServerTest, KeepAlive) {
  6721. auto res = cli_.Get("/hi");
  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("Hello World!", res->body);
  6726. res = cli_.Get("/hi");
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::OK_200, res->status);
  6729. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6730. EXPECT_EQ("Hello World!", res->body);
  6731. res = cli_.Get("/hi");
  6732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6733. EXPECT_EQ(StatusCode::OK_200, res->status);
  6734. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6735. EXPECT_EQ("Hello World!", res->body);
  6736. res = cli_.Get("/not-exist");
  6737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6738. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6739. res = cli_.Post("/empty", "", "text/plain");
  6740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6741. EXPECT_EQ(StatusCode::OK_200, res->status);
  6742. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6743. EXPECT_EQ("empty", res->body);
  6744. EXPECT_EQ("close", res->get_header_value("Connection"));
  6745. res = cli_.Post(
  6746. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6747. "text/plain");
  6748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6749. EXPECT_EQ(StatusCode::OK_200, res->status);
  6750. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6751. EXPECT_EQ("empty", res->body);
  6752. cli_.set_keep_alive(false);
  6753. res = cli_.Get("/last-request");
  6754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6755. EXPECT_EQ(StatusCode::OK_200, res->status);
  6756. EXPECT_EQ("close", res->get_header_value("Connection"));
  6757. }
  6758. TEST_F(ServerTest, TooManyRedirect) {
  6759. cli_.set_follow_location(true);
  6760. auto res = cli_.Get("/redirect/0");
  6761. ASSERT_TRUE(!res);
  6762. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6763. }
  6764. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6765. Request req;
  6766. req.method = "FOOBAR";
  6767. req.path = "/hi";
  6768. cli_.set_keep_alive(true);
  6769. auto res = cli_.send(req);
  6770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6771. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6772. EXPECT_EQ("close", res->get_header_value("Connection"));
  6773. EXPECT_FALSE(cli_.is_socket_open());
  6774. }
  6775. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6776. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6777. TEST_F(ServerTest, Gzip) {
  6778. Headers headers;
  6779. headers.emplace("Accept-Encoding", "gzip, deflate");
  6780. auto res = cli_.Get("/compress", headers);
  6781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6782. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6783. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6784. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6785. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6786. "7890123456789012345678901234567890",
  6787. res->body);
  6788. EXPECT_EQ(StatusCode::OK_200, res->status);
  6789. }
  6790. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6791. Headers headers;
  6792. headers.emplace("Accept-Encoding", "gzip, deflate");
  6793. auto res = cli_.Get("/compress-with-charset", headers);
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6796. EXPECT_EQ("application/json; charset=utf-8",
  6797. res->get_header_value("Content-Type"));
  6798. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6799. "7890123456789012345678901234567890",
  6800. res->body);
  6801. EXPECT_EQ(StatusCode::OK_200, res->status);
  6802. }
  6803. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6804. Headers headers;
  6805. headers.emplace("Accept-Encoding", "");
  6806. auto res = cli_.Get("/compress", headers);
  6807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6808. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6809. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6810. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6811. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6812. "7890123456789012345678901234567890",
  6813. res->body);
  6814. EXPECT_EQ(StatusCode::OK_200, res->status);
  6815. }
  6816. TEST_F(ServerTest, GzipWithContentReceiver) {
  6817. Headers headers;
  6818. headers.emplace("Accept-Encoding", "gzip, deflate");
  6819. std::string body;
  6820. auto res = cli_.Get("/compress", headers,
  6821. [&](const char *data, uint64_t data_length) {
  6822. EXPECT_EQ(100U, data_length);
  6823. body.append(data, data_length);
  6824. return true;
  6825. });
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6828. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6829. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6830. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6831. "7890123456789012345678901234567890",
  6832. body);
  6833. EXPECT_EQ(StatusCode::OK_200, res->status);
  6834. }
  6835. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6836. Headers headers;
  6837. headers.emplace("Accept-Encoding", "gzip, deflate");
  6838. cli_.set_decompress(false);
  6839. auto res = cli_.Get("/compress", headers);
  6840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6841. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6842. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6843. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6844. EXPECT_EQ(33U, res->body.size());
  6845. EXPECT_EQ(StatusCode::OK_200, res->status);
  6846. }
  6847. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6848. Headers headers;
  6849. headers.emplace("Accept-Encoding", "");
  6850. std::string body;
  6851. auto res = cli_.Get("/compress", headers,
  6852. [&](const char *data, uint64_t data_length) {
  6853. EXPECT_EQ(100U, data_length);
  6854. body.append(data, data_length);
  6855. return true;
  6856. });
  6857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6858. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6859. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6860. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6861. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6862. "7890123456789012345678901234567890",
  6863. body);
  6864. EXPECT_EQ(StatusCode::OK_200, res->status);
  6865. }
  6866. TEST_F(ServerTest, NoGzip) {
  6867. Headers headers;
  6868. headers.emplace("Accept-Encoding", "gzip, deflate");
  6869. auto res = cli_.Get("/nocompress", headers);
  6870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6871. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6872. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6873. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6874. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6875. "7890123456789012345678901234567890",
  6876. res->body);
  6877. EXPECT_EQ(StatusCode::OK_200, res->status);
  6878. }
  6879. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6880. Headers headers;
  6881. headers.emplace("Accept-Encoding", "gzip, deflate");
  6882. std::string body;
  6883. auto res = cli_.Get("/nocompress", headers,
  6884. [&](const char *data, uint64_t data_length) {
  6885. EXPECT_EQ(100U, data_length);
  6886. body.append(data, data_length);
  6887. return true;
  6888. });
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6891. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6892. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6893. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6894. "7890123456789012345678901234567890",
  6895. body);
  6896. EXPECT_EQ(StatusCode::OK_200, res->status);
  6897. }
  6898. TEST_F(ServerTest, MultipartFormDataGzip) {
  6899. UploadFormDataItems items = {
  6900. {"key1", "test", "", ""},
  6901. {"key2", "--abcdefg123", "", ""},
  6902. };
  6903. cli_.set_compress(true);
  6904. auto res = cli_.Post("/compress-multipart", items);
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::OK_200, res->status);
  6907. }
  6908. #endif
  6909. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6910. TEST_F(ServerTest, Brotli) {
  6911. Headers headers;
  6912. headers.emplace("Accept-Encoding", "br");
  6913. auto res = cli_.Get("/compress", headers);
  6914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6915. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6916. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6917. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6918. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6919. "7890123456789012345678901234567890",
  6920. res->body);
  6921. EXPECT_EQ(StatusCode::OK_200, res->status);
  6922. }
  6923. #endif
  6924. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6925. TEST_F(ServerTest, Zstd) {
  6926. Headers headers;
  6927. headers.emplace("Accept-Encoding", "zstd");
  6928. auto res = cli_.Get("/compress", headers);
  6929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6930. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6931. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6932. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6933. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6934. "7890123456789012345678901234567890",
  6935. res->body);
  6936. EXPECT_EQ(StatusCode::OK_200, res->status);
  6937. }
  6938. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6939. Headers headers;
  6940. headers.emplace("Accept-Encoding", "");
  6941. auto res = cli_.Get("/compress", headers);
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6944. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6945. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6946. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6947. "7890123456789012345678901234567890",
  6948. res->body);
  6949. EXPECT_EQ(StatusCode::OK_200, res->status);
  6950. }
  6951. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6952. Headers headers;
  6953. headers.emplace("Accept-Encoding", "zstd");
  6954. std::string body;
  6955. auto res = cli_.Get("/compress", headers,
  6956. [&](const char *data, uint64_t data_length) {
  6957. EXPECT_EQ(100U, data_length);
  6958. body.append(data, data_length);
  6959. return true;
  6960. });
  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("123456789012345678901234567890123456789012345678901234567890123456"
  6966. "7890123456789012345678901234567890",
  6967. body);
  6968. EXPECT_EQ(StatusCode::OK_200, res->status);
  6969. }
  6970. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6971. Headers headers;
  6972. headers.emplace("Accept-Encoding", "zstd");
  6973. cli_.set_decompress(false);
  6974. auto res = cli_.Get("/compress", headers);
  6975. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6976. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6977. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6978. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6980. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6981. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6982. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6983. EXPECT_EQ(StatusCode::OK_200, res->status);
  6984. ASSERT_EQ(26U, res->body.size());
  6985. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6986. 0);
  6987. }
  6988. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6989. Headers headers;
  6990. headers.emplace("Accept-Encoding", "");
  6991. std::string body;
  6992. auto res = cli_.Get("/compress", headers,
  6993. [&](const char *data, uint64_t data_length) {
  6994. EXPECT_EQ(100U, data_length);
  6995. body.append(data, data_length);
  6996. return true;
  6997. });
  6998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6999. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7000. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7001. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7002. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7003. "7890123456789012345678901234567890",
  7004. body);
  7005. EXPECT_EQ(StatusCode::OK_200, res->status);
  7006. }
  7007. TEST_F(ServerTest, NoZstd) {
  7008. Headers headers;
  7009. headers.emplace("Accept-Encoding", "zstd");
  7010. auto res = cli_.Get("/nocompress", headers);
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7013. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7014. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7015. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7016. "7890123456789012345678901234567890",
  7017. res->body);
  7018. EXPECT_EQ(StatusCode::OK_200, res->status);
  7019. }
  7020. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7021. Headers headers;
  7022. headers.emplace("Accept-Encoding", "zstd");
  7023. std::string body;
  7024. auto res = cli_.Get("/nocompress", headers,
  7025. [&](const char *data, uint64_t data_length) {
  7026. EXPECT_EQ(100U, data_length);
  7027. body.append(data, data_length);
  7028. return true;
  7029. });
  7030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7031. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7032. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7033. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7034. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7035. "7890123456789012345678901234567890",
  7036. body);
  7037. EXPECT_EQ(StatusCode::OK_200, res->status);
  7038. }
  7039. // TODO: How to enable zstd ??
  7040. TEST_F(ServerTest, MultipartFormDataZstd) {
  7041. UploadFormDataItems items = {
  7042. {"key1", "test", "", ""},
  7043. {"key2", "--abcdefg123", "", ""},
  7044. };
  7045. Headers headers;
  7046. headers.emplace("Accept-Encoding", "zstd");
  7047. cli_.set_compress(true);
  7048. auto res = cli_.Post("/compress-multipart", headers, items);
  7049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7050. EXPECT_EQ(StatusCode::OK_200, res->status);
  7051. }
  7052. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7053. Headers headers;
  7054. headers.emplace("Accept-Encoding", "zstd");
  7055. cli_.set_compress(true);
  7056. auto res = cli_.Put(
  7057. "/put", headers, 3,
  7058. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7059. sink.os << "PUT";
  7060. return true;
  7061. },
  7062. "text/plain");
  7063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7064. EXPECT_EQ(StatusCode::OK_200, res->status);
  7065. EXPECT_EQ("PUT", res->body);
  7066. }
  7067. // Pre-compression logging tests
  7068. TEST_F(ServerTest, PreCompressionLogging) {
  7069. // Test data for compression (matches the actual /compress endpoint content)
  7070. const std::string test_content =
  7071. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7072. "3456789012345678901234567890";
  7073. // Variables to capture logging data
  7074. std::string pre_compression_body;
  7075. std::string pre_compression_content_type;
  7076. std::string pre_compression_content_encoding;
  7077. std::string post_compression_body;
  7078. std::string post_compression_content_type;
  7079. std::string post_compression_content_encoding;
  7080. // Set up pre-compression logger
  7081. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7082. const Response &res) {
  7083. pre_compression_body = res.body;
  7084. pre_compression_content_type = res.get_header_value("Content-Type");
  7085. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7086. });
  7087. // Set up post-compression logger
  7088. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7089. post_compression_body = res.body;
  7090. post_compression_content_type = res.get_header_value("Content-Type");
  7091. post_compression_content_encoding =
  7092. res.get_header_value("Content-Encoding");
  7093. });
  7094. // Test with gzip compression
  7095. Headers headers;
  7096. headers.emplace("Accept-Encoding", "gzip");
  7097. auto res = cli_.Get("/compress", headers);
  7098. // Verify response was compressed
  7099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7100. EXPECT_EQ(StatusCode::OK_200, res->status);
  7101. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7102. // Verify pre-compression logger captured uncompressed content
  7103. EXPECT_EQ(test_content, pre_compression_body);
  7104. EXPECT_EQ("text/plain", pre_compression_content_type);
  7105. EXPECT_TRUE(pre_compression_content_encoding
  7106. .empty()); // No encoding header before compression
  7107. // Verify post-compression logger captured compressed content
  7108. EXPECT_NE(test_content,
  7109. post_compression_body); // Should be different after compression
  7110. EXPECT_EQ("text/plain", post_compression_content_type);
  7111. EXPECT_EQ("gzip", post_compression_content_encoding);
  7112. // Verify compressed content is smaller
  7113. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7114. }
  7115. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7116. const std::string test_content =
  7117. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7118. "3456789012345678901234567890";
  7119. std::string pre_compression_body;
  7120. std::string post_compression_body;
  7121. svr_.set_pre_compression_logger(
  7122. [&](const Request & /*req*/, const Response &res) {
  7123. pre_compression_body = res.body;
  7124. });
  7125. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7126. post_compression_body = res.body;
  7127. });
  7128. Headers headers;
  7129. headers.emplace("Accept-Encoding", "br");
  7130. auto res = cli_.Get("/compress", headers);
  7131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7132. EXPECT_EQ(StatusCode::OK_200, res->status);
  7133. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7134. // Verify pre-compression content is uncompressed
  7135. EXPECT_EQ(test_content, pre_compression_body);
  7136. // Verify post-compression content is compressed
  7137. EXPECT_NE(test_content, post_compression_body);
  7138. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7139. }
  7140. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7141. const std::string test_content =
  7142. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7143. "3456789012345678901234567890";
  7144. std::string pre_compression_body;
  7145. std::string post_compression_body;
  7146. svr_.set_pre_compression_logger(
  7147. [&](const Request & /*req*/, const Response &res) {
  7148. pre_compression_body = res.body;
  7149. });
  7150. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7151. post_compression_body = res.body;
  7152. });
  7153. // Request without compression (use /nocompress endpoint)
  7154. Headers headers;
  7155. auto res = cli_.Get("/nocompress", headers);
  7156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7157. EXPECT_EQ(StatusCode::OK_200, res->status);
  7158. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7159. // Pre-compression logger should not be called when no compression is applied
  7160. EXPECT_TRUE(
  7161. pre_compression_body.empty()); // Pre-compression logger not called
  7162. EXPECT_EQ(
  7163. test_content,
  7164. post_compression_body); // Post-compression logger captures final content
  7165. }
  7166. TEST_F(ServerTest, LoggerSeesContentLength) {
  7167. size_t logged_content_length = 0;
  7168. std::string logged_content_length_header;
  7169. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7170. logged_content_length = res.content_length_;
  7171. logged_content_length_header = res.get_header_value("Content-Length");
  7172. });
  7173. auto res = cli_.Get("/nocompress");
  7174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7175. EXPECT_EQ(StatusCode::OK_200, res->status);
  7176. EXPECT_EQ(res->body.size(), logged_content_length);
  7177. EXPECT_EQ(std::to_string(logged_content_length),
  7178. logged_content_length_header);
  7179. }
  7180. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7181. const std::string test_content =
  7182. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7183. "3456789012345678901234567890";
  7184. std::string pre_compression_body;
  7185. bool pre_logger_called = false;
  7186. // Set only pre-compression logger
  7187. svr_.set_pre_compression_logger(
  7188. [&](const Request & /*req*/, const Response &res) {
  7189. pre_compression_body = res.body;
  7190. pre_logger_called = true;
  7191. });
  7192. Headers headers;
  7193. headers.emplace("Accept-Encoding", "gzip");
  7194. auto res = cli_.Get("/compress", headers);
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::OK_200, res->status);
  7197. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7198. // Verify pre-compression logger was called
  7199. EXPECT_TRUE(pre_logger_called);
  7200. EXPECT_EQ(test_content, pre_compression_body);
  7201. }
  7202. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7203. {
  7204. // Test with Expect: 100-continue header - success case
  7205. // Server returns 100 Continue, client sends body, server returns 200 OK
  7206. Request req;
  7207. req.method = "POST";
  7208. req.path = "/post-large";
  7209. req.set_header("Expect", "100-continue");
  7210. req.body = LARGE_DATA;
  7211. Response res;
  7212. auto error = Error::Success;
  7213. cli_.set_keep_alive(true);
  7214. auto ret = cli_.send(req, res, error);
  7215. EXPECT_TRUE(ret);
  7216. EXPECT_EQ(StatusCode::OK_200, res.status);
  7217. EXPECT_EQ(LARGE_DATA, res.body);
  7218. }
  7219. {
  7220. // Test with Expect: 100-continue header - error case
  7221. // Client should not send the body when server returns an error
  7222. Request req;
  7223. req.method = "POST";
  7224. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7225. req.set_header("Expect", "100-continue");
  7226. req.body = LARGE_DATA;
  7227. Response res;
  7228. auto error = Error::Success;
  7229. auto start = std::chrono::high_resolution_clock::now();
  7230. cli_.set_keep_alive(true);
  7231. auto ret = cli_.send(req, res, error);
  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. // With Expect: 100-continue, request completes successfully but with error
  7237. EXPECT_TRUE(ret);
  7238. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7239. EXPECT_EQ("close", res.get_header_value("Connection"));
  7240. EXPECT_FALSE(cli_.is_socket_open());
  7241. EXPECT_LE(elapsed, 2000);
  7242. }
  7243. {
  7244. // Send an extra GET request to ensure error recovery without hanging
  7245. Request req;
  7246. req.method = "GET";
  7247. req.path = "/hi";
  7248. auto start = std::chrono::high_resolution_clock::now();
  7249. auto res = cli_.send(req);
  7250. auto end = std::chrono::high_resolution_clock::now();
  7251. auto elapsed =
  7252. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7253. .count();
  7254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7255. EXPECT_EQ(StatusCode::OK_200, res->status);
  7256. EXPECT_EQ("Hello World!", res->body);
  7257. EXPECT_LE(elapsed, 500);
  7258. }
  7259. }
  7260. TEST(ZstdDecompressor, ChunkedDecompression) {
  7261. std::string data;
  7262. for (size_t i = 0; i < 32 * 1024; ++i) {
  7263. data.push_back(static_cast<char>('a' + i % 26));
  7264. }
  7265. std::string compressed_data;
  7266. {
  7267. httplib::detail::zstd_compressor compressor;
  7268. bool result = compressor.compress(
  7269. data.data(), data.size(),
  7270. /*last=*/true,
  7271. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7272. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7273. compressed_data_size);
  7274. return true;
  7275. });
  7276. ASSERT_TRUE(result);
  7277. }
  7278. std::string decompressed_data;
  7279. {
  7280. httplib::detail::zstd_decompressor decompressor;
  7281. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7282. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7283. size_t chunk_size = 130;
  7284. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7285. chunk_begin += chunk_size) {
  7286. size_t current_chunk_size =
  7287. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7288. bool result = decompressor.decompress(
  7289. compressed_data.data() + chunk_begin, current_chunk_size,
  7290. [&](const char *decompressed_data_chunk,
  7291. size_t decompressed_data_chunk_size) {
  7292. decompressed_data.insert(decompressed_data.size(),
  7293. decompressed_data_chunk,
  7294. decompressed_data_chunk_size);
  7295. return true;
  7296. });
  7297. ASSERT_TRUE(result);
  7298. }
  7299. }
  7300. ASSERT_EQ(data, decompressed_data);
  7301. }
  7302. TEST(ZstdDecompressor, Decompress) {
  7303. std::string original_text = "Compressed with ZSTD";
  7304. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7305. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7306. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7307. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7308. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7309. std::string decompressed_data;
  7310. {
  7311. httplib::detail::zstd_decompressor decompressor;
  7312. bool result = decompressor.decompress(
  7313. compressed_data.data(), compressed_data.size(),
  7314. [&](const char *decompressed_data_chunk,
  7315. size_t decompressed_data_chunk_size) {
  7316. decompressed_data.insert(decompressed_data.size(),
  7317. decompressed_data_chunk,
  7318. decompressed_data_chunk_size);
  7319. return true;
  7320. });
  7321. ASSERT_TRUE(result);
  7322. }
  7323. ASSERT_EQ(original_text, decompressed_data);
  7324. }
  7325. #endif
  7326. // Sends a raw request to a server listening at HOST:PORT.
  7327. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7328. std::string *resp = nullptr, int port = PORT) {
  7329. auto error = Error::Success;
  7330. auto client_sock = detail::create_client_socket(
  7331. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7332. /*connection_timeout_sec=*/5, 0,
  7333. /*read_timeout_sec=*/5, 0,
  7334. /*write_timeout_sec=*/5, 0, std::string(), error);
  7335. if (client_sock == INVALID_SOCKET) { return false; }
  7336. auto ret = detail::process_client_socket(
  7337. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7338. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7339. if (req.size() !=
  7340. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  7341. return false;
  7342. }
  7343. char buf[512];
  7344. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7345. while (line_reader.getline()) {
  7346. if (resp) { *resp += line_reader.ptr(); }
  7347. }
  7348. return true;
  7349. });
  7350. detail::close_socket(client_sock);
  7351. return ret;
  7352. }
  7353. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7354. Server svr;
  7355. std::string header_value;
  7356. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7357. header_value = req.get_header_value("foo");
  7358. res.set_content("ok", "text/plain");
  7359. });
  7360. thread t = thread([&] { svr.listen(HOST, PORT); });
  7361. auto se = detail::scope_exit([&] {
  7362. svr.stop();
  7363. t.join();
  7364. ASSERT_FALSE(svr.is_running());
  7365. });
  7366. svr.wait_until_ready();
  7367. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7368. // like characters are not treated the same - use vertical tab and escape.
  7369. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7370. "foo: \t \v bar \x1B\t \r\n"
  7371. "Connection: close\r\n"
  7372. "\r\n";
  7373. std::string res;
  7374. ASSERT_TRUE(send_request(5, req, &res));
  7375. EXPECT_EQ(header_value, "");
  7376. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7377. }
  7378. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7379. Server svr;
  7380. std::string received;
  7381. svr.Get("/order", [&](const Request &req, Response &res) {
  7382. received = entries_to_string(req.headers);
  7383. res.set_content("ok", "text/plain");
  7384. });
  7385. auto port = svr.bind_to_any_port(HOST);
  7386. thread t = thread([&] { svr.listen_after_bind(); });
  7387. auto se = detail::scope_exit([&] {
  7388. svr.stop();
  7389. t.join();
  7390. ASSERT_FALSE(svr.is_running());
  7391. });
  7392. svr.wait_until_ready();
  7393. const std::string req = "GET /order HTTP/1.1\r\n"
  7394. "X-First: 1\r\n"
  7395. "X-Dup: a\r\n"
  7396. "X-Second: 2\r\n"
  7397. "X-Dup: b\r\n"
  7398. "Connection: close\r\n"
  7399. "\r\n";
  7400. std::string res;
  7401. ASSERT_TRUE(send_request(5, req, &res, port));
  7402. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7403. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7404. }
  7405. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7406. Server svr;
  7407. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7408. res.set_header("Set-Cookie", "first=1");
  7409. res.set_header("X-Between", "y");
  7410. res.set_header("Set-Cookie", "second=2");
  7411. res.set_content("ok", "text/plain");
  7412. });
  7413. auto port = svr.bind_to_any_port(HOST);
  7414. thread t = thread([&] { svr.listen_after_bind(); });
  7415. auto se = detail::scope_exit([&] {
  7416. svr.stop();
  7417. t.join();
  7418. ASSERT_FALSE(svr.is_running());
  7419. });
  7420. svr.wait_until_ready();
  7421. Client cli(HOST, port);
  7422. auto res = cli.Get("/cookies");
  7423. ASSERT_TRUE(res);
  7424. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7425. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7426. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7427. }
  7428. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7429. Server svr;
  7430. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7431. auto i = new int(0);
  7432. res.set_header("Trailer", "X-Safe, X-Reflected");
  7433. res.set_chunked_content_provider(
  7434. "text/plain",
  7435. [i](size_t /*offset*/, DataSink &sink) {
  7436. if (*i == 0) {
  7437. sink.os << "body";
  7438. } else {
  7439. Headers trailer;
  7440. // A valid trailer that must survive.
  7441. trailer.emplace("X-Safe", "safe");
  7442. // Attacker-controlled value carrying CR/LF (response splitting).
  7443. trailer.emplace("X-Reflected",
  7444. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7445. // Attacker-controlled name carrying CR/LF.
  7446. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7447. sink.done_with_trailer(trailer);
  7448. }
  7449. (*i)++;
  7450. return true;
  7451. },
  7452. [i](bool /*success*/) { delete i; });
  7453. });
  7454. thread t = thread([&] { svr.listen(HOST, PORT); });
  7455. auto se = detail::scope_exit([&] {
  7456. svr.stop();
  7457. t.join();
  7458. ASSERT_FALSE(svr.is_running());
  7459. });
  7460. svr.wait_until_ready();
  7461. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7462. "Host: " + HOST +
  7463. "\r\n"
  7464. "Connection: close\r\n"
  7465. "\r\n";
  7466. std::string res;
  7467. ASSERT_TRUE(send_request(5, req, &res));
  7468. // The injected fields must not appear anywhere in the raw response.
  7469. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7470. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7471. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7472. // Invalid trailers are dropped entirely, matching set_header().
  7473. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7474. // The valid trailer still passes through.
  7475. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7476. }
  7477. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7478. Server svr;
  7479. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7480. // res.headers is a public field an application can populate directly,
  7481. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7482. // A valid header that must survive.
  7483. res.headers.emplace("X-Safe", "safe");
  7484. // Attacker-controlled value carrying CR/LF (response splitting).
  7485. res.headers.emplace("X-Reflected",
  7486. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7487. // Attacker-controlled name carrying CR/LF.
  7488. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7489. res.set_content("body", "text/plain");
  7490. });
  7491. thread t = thread([&] { svr.listen(HOST, PORT); });
  7492. auto se = detail::scope_exit([&] {
  7493. svr.stop();
  7494. t.join();
  7495. ASSERT_FALSE(svr.is_running());
  7496. });
  7497. svr.wait_until_ready();
  7498. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7499. "Host: " + HOST +
  7500. "\r\n"
  7501. "Connection: close\r\n"
  7502. "\r\n";
  7503. std::string res;
  7504. ASSERT_TRUE(send_request(5, req, &res));
  7505. // The injected fields must not appear anywhere in the raw response.
  7506. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7507. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7508. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7509. // Invalid headers are dropped entirely, matching set_header().
  7510. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7511. // The valid header still passes through.
  7512. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7513. }
  7514. // Forward declaration: in split builds split.py strips `inline` and moves the
  7515. // definition into httplib.cc, so detail::write_request_line is not visible from
  7516. // the public httplib.h. Re-declaring it here lets the tests link against the
  7517. // symbol in both header-only and split builds.
  7518. namespace httplib {
  7519. namespace detail {
  7520. ssize_t write_request_line(Stream &strm, const std::string &method,
  7521. const std::string &path);
  7522. } // namespace detail
  7523. } // namespace httplib
  7524. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7525. // A well-formed target is written verbatim.
  7526. {
  7527. detail::BufferStream strm;
  7528. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7529. EXPECT_GT(n, 0);
  7530. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7531. }
  7532. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7533. // otherwise it splits the request line and injects a header or a whole
  7534. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7535. // when path encoding is disabled.
  7536. const std::string evil_targets[] = {
  7537. "/a\r\nInjected: pwned",
  7538. "/a\rInjected",
  7539. "/a\nInjected",
  7540. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7541. };
  7542. for (const auto &evil : evil_targets) {
  7543. detail::BufferStream strm;
  7544. auto n = detail::write_request_line(strm, "GET", evil);
  7545. EXPECT_LT(n, 0);
  7546. EXPECT_TRUE(strm.get_buffer().empty());
  7547. }
  7548. }
  7549. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7550. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7551. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7552. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7553. // client must fail cleanly with Error::Write instead of putting a
  7554. // request-line-less, header-injecting request on the wire.
  7555. Server svr;
  7556. svr.Get("/a", [](const Request &, Response &res) {
  7557. res.set_content("ok", "text/plain");
  7558. });
  7559. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7560. auto se = detail::scope_exit([&] {
  7561. svr.stop();
  7562. thread.join();
  7563. ASSERT_FALSE(svr.is_running());
  7564. });
  7565. svr.wait_until_ready();
  7566. {
  7567. Client cli(HOST, PORT);
  7568. cli.set_path_encode(false);
  7569. // The request is rejected before anything is written, so the connection
  7570. // stays silent and the subsequent response read would otherwise block for
  7571. // the full default read timeout. Shorten it -- the assertion is on the
  7572. // error, not the timeout.
  7573. cli.set_read_timeout(1, 0);
  7574. auto res = cli.Get("/a\r\nInjected: pwned");
  7575. EXPECT_FALSE(res);
  7576. EXPECT_EQ(Error::Write, res.error());
  7577. }
  7578. }
  7579. // Sends a raw request and verifies that there isn't a crash or exception.
  7580. static void test_raw_request(const std::string &req,
  7581. std::string *out = nullptr) {
  7582. Server svr;
  7583. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7584. res.set_content("ok", "text/plain");
  7585. });
  7586. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7587. res.set_content("ok", "text/plain");
  7588. });
  7589. svr.Get("/header_field_value_check",
  7590. [&](const Request & /*req*/, Response &res) {
  7591. res.set_content("ok", "text/plain");
  7592. });
  7593. // Server read timeout must be longer than the client read timeout for the
  7594. // bug to reproduce, probably to force the server to process a request
  7595. // without a trailing blank line.
  7596. const time_t client_read_timeout_sec = 1;
  7597. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7598. bool listen_thread_ok = false;
  7599. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7600. auto se = detail::scope_exit([&] {
  7601. svr.stop();
  7602. t.join();
  7603. ASSERT_FALSE(svr.is_running());
  7604. EXPECT_TRUE(listen_thread_ok);
  7605. });
  7606. svr.wait_until_ready();
  7607. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7608. }
  7609. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7610. // A certain header line causes an exception if the header property is parsed
  7611. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7612. test_raw_request(
  7613. "GET /hi HTTP/1.1\r\n"
  7614. " : "
  7615. " "
  7616. " ");
  7617. }
  7618. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7619. // A certain header line causes an exception if the header property *name* is
  7620. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7621. // greedy matcher and requires backtracking when there are a lot of ":"
  7622. // characters.
  7623. // This occurs with libc++ but not libstdc++.
  7624. test_raw_request(
  7625. "GET /hi HTTP/1.1\r\n"
  7626. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7627. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7628. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7629. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7630. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7631. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7632. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7633. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7634. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7635. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7636. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7637. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7638. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7639. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7640. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7641. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7642. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7643. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7644. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7645. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7646. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7647. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7648. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7649. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7650. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7651. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7652. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7653. "&&&%%%");
  7654. }
  7655. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7656. // Make sure this doesn't crash the server.
  7657. // In a previous version of the header line regex, the "\r" rendered the line
  7658. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7659. // a new position where the leading white space ended and the field value
  7660. // began.
  7661. // The crash occurs with libc++ but not libstdc++.
  7662. test_raw_request("GET /hi HTTP/1.1\r\n"
  7663. "a:" +
  7664. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7665. "\r\n"
  7666. "\r\n");
  7667. }
  7668. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7669. std::string out;
  7670. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7671. "Content-Type: text/plain\r\n"
  7672. "Transfer-Encoding: chunked\r\n"
  7673. "\r\n"
  7674. "nothex\r\n",
  7675. &out);
  7676. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7677. }
  7678. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7679. std::string out;
  7680. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7681. "Content-Type: text/plain\r\n"
  7682. "Transfer-Encoding: chunked\r\n"
  7683. "\r\n"
  7684. "3\r\n"
  7685. "xyz\r\n"
  7686. "NaN\r\n",
  7687. &out);
  7688. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7689. }
  7690. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7691. std::string out;
  7692. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7693. "Content-Type: text/plain\r\n"
  7694. "Transfer-Encoding: chunked\r\n"
  7695. "\r\n"
  7696. // Length is too large for 64 bits.
  7697. "1ffffffffffffffff\r\n"
  7698. "xyz\r\n",
  7699. &out);
  7700. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7701. }
  7702. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7703. test_raw_request("GET /hi HTTP/1.1\r\n"
  7704. "Content-Type: text/plain\r\n\r");
  7705. }
  7706. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7707. std::string out;
  7708. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7709. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7710. }
  7711. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7712. Server svr;
  7713. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7714. EXPECT_TRUE(!req.remote_addr.empty());
  7715. });
  7716. thread t = thread([&] { svr.listen(HOST, PORT); });
  7717. auto se = detail::scope_exit([&] {
  7718. svr.stop();
  7719. t.join();
  7720. ASSERT_FALSE(svr.is_running());
  7721. });
  7722. svr.wait_until_ready();
  7723. // Send an invalid request line to trigger Bad Request
  7724. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7725. std::string out;
  7726. ASSERT_TRUE(send_request(5, bad_req, &out));
  7727. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7728. }
  7729. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7730. std::string out;
  7731. std::string request(
  7732. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7733. test_raw_request(request, &out);
  7734. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7735. }
  7736. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7737. std::string out;
  7738. std::string request(
  7739. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7740. test_raw_request(request, &out);
  7741. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7742. }
  7743. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7744. std::string out;
  7745. std::string request(
  7746. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7747. test_raw_request(request, &out);
  7748. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7749. }
  7750. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7751. std::string out;
  7752. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7753. "Test: \r\n\r\n",
  7754. &out);
  7755. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7756. }
  7757. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7758. Server svr;
  7759. std::string x_custom;
  7760. std::string cookie;
  7761. std::string xff;
  7762. std::string x_unicode;
  7763. std::string x_iis;
  7764. svr.Get("/check", [&](const Request &req, Response &res) {
  7765. x_custom = req.get_header_value("X-Custom");
  7766. cookie = req.get_header_value("Cookie");
  7767. xff = req.get_header_value("X-Forwarded-For");
  7768. x_unicode = req.get_header_value("X-Unicode");
  7769. x_iis = req.get_header_value("X-IIS");
  7770. res.set_content("ok", "text/plain");
  7771. });
  7772. thread t = thread([&] { svr.listen(HOST, PORT); });
  7773. auto se = detail::scope_exit([&] {
  7774. svr.stop();
  7775. t.join();
  7776. ASSERT_FALSE(svr.is_running());
  7777. });
  7778. svr.wait_until_ready();
  7779. const std::string req = "GET /check HTTP/1.1\r\n"
  7780. "Host: localhost\r\n"
  7781. "X-Custom: a%0D%0AInjected: b\r\n"
  7782. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7783. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7784. "X-Unicode: %E3%81%82\r\n"
  7785. "X-IIS: %u00E9\r\n"
  7786. "Connection: close\r\n"
  7787. "\r\n";
  7788. std::string res;
  7789. ASSERT_TRUE(send_request(5, req, &res));
  7790. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7791. // Every value must be returned verbatim (wire form), with no decoding.
  7792. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7793. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7794. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7795. EXPECT_EQ("%E3%81%82", x_unicode);
  7796. EXPECT_EQ("%u00E9", x_iis);
  7797. }
  7798. // Applications that previously relied on automatic percent-decoding can
  7799. // reproduce the old behavior by explicitly calling decode_path_component()
  7800. // or, for RFC 3986 conformance, decode_uri_component().
  7801. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7802. Server svr;
  7803. std::string decoded;
  7804. svr.Get("/check", [&](const Request &req, Response &res) {
  7805. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7806. res.set_content("ok", "text/plain");
  7807. });
  7808. thread t = thread([&] { svr.listen(HOST, PORT); });
  7809. auto se = detail::scope_exit([&] {
  7810. svr.stop();
  7811. t.join();
  7812. ASSERT_FALSE(svr.is_running());
  7813. });
  7814. svr.wait_until_ready();
  7815. const std::string req = "GET /check HTTP/1.1\r\n"
  7816. "Host: localhost\r\n"
  7817. "X-Custom: hello%20world\r\n"
  7818. "Connection: close\r\n"
  7819. "\r\n";
  7820. std::string res;
  7821. ASSERT_TRUE(send_request(5, req, &res));
  7822. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7823. EXPECT_EQ("hello world", decoded);
  7824. }
  7825. // Regression test for #2033. Browsers send Referer values that include
  7826. // percent-encoded characters such as %0A inside the URL. Decoding the
  7827. // header value would either trip the post-decode CR/LF/NUL guard (the
  7828. // original bug, returning 400) or, after that guard was relaxed, silently
  7829. // store a literal LF — both unacceptable. The wire form must round-trip.
  7830. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7831. Server svr;
  7832. std::string referer;
  7833. svr.Get("/check", [&](const Request &req, Response &res) {
  7834. referer = req.get_header_value("Referer");
  7835. res.set_content("ok", "text/plain");
  7836. });
  7837. thread t = thread([&] { svr.listen(HOST, PORT); });
  7838. auto se = detail::scope_exit([&] {
  7839. svr.stop();
  7840. t.join();
  7841. ASSERT_FALSE(svr.is_running());
  7842. });
  7843. svr.wait_until_ready();
  7844. const std::string req = "GET /check HTTP/1.1\r\n"
  7845. "Host: localhost\r\n"
  7846. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7847. "Connection: close\r\n"
  7848. "\r\n";
  7849. std::string res;
  7850. ASSERT_TRUE(send_request(5, req, &res));
  7851. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7852. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7853. }
  7854. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7855. Server svr;
  7856. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7857. res.set_header("Cache-Control", "no-cache");
  7858. res.set_chunked_content_provider(
  7859. "text/event-stream", [](size_t offset, DataSink &sink) {
  7860. std::string s = "data:";
  7861. s += std::to_string(offset);
  7862. s += "\n\n";
  7863. auto ret = sink.write(s.data(), s.size());
  7864. EXPECT_TRUE(ret);
  7865. std::this_thread::sleep_for(std::chrono::seconds(1));
  7866. return true;
  7867. });
  7868. });
  7869. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7870. svr.wait_until_ready();
  7871. Client client(HOST, PORT);
  7872. const Headers headers = {{"Accept", "text/event-stream"}};
  7873. auto get_thread = std::thread([&client, &headers]() {
  7874. auto res = client.Get(
  7875. "/events", headers,
  7876. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7877. });
  7878. auto se = detail::scope_exit([&] {
  7879. svr.stop();
  7880. get_thread.join();
  7881. listen_thread.join();
  7882. ASSERT_FALSE(svr.is_running());
  7883. });
  7884. // Give GET time to get a few messages.
  7885. std::this_thread::sleep_for(std::chrono::seconds(2));
  7886. }
  7887. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7888. httplib::Server svr;
  7889. svr.Post("/hi",
  7890. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7891. res.status = StatusCode::OK_200;
  7892. });
  7893. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7894. svr.wait_until_ready();
  7895. Client cli(HOST, PORT);
  7896. auto res = cli.Post("/hi", "data", "text/plain");
  7897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7898. EXPECT_EQ(StatusCode::OK_200, res->status);
  7899. svr.stop();
  7900. thread.join();
  7901. ASSERT_FALSE(svr.is_running());
  7902. res = cli.Post("/hi", "data", "text/plain");
  7903. ASSERT_FALSE(res);
  7904. }
  7905. TEST(ServerStopTest, ListenFailure) {
  7906. Server svr;
  7907. auto t = thread([&]() {
  7908. auto ret = svr.listen("????", PORT);
  7909. EXPECT_FALSE(ret);
  7910. });
  7911. svr.wait_until_ready();
  7912. svr.stop();
  7913. t.join();
  7914. }
  7915. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7916. TEST(ServerStopTest, Decommision) {
  7917. Server svr;
  7918. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7919. for (int i = 0; i < 4; i++) {
  7920. auto is_even = !(i % 2);
  7921. std::thread t{[&] {
  7922. try {
  7923. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7924. if (is_even) {
  7925. throw std::runtime_error("Some thing that happens to go wrong.");
  7926. }
  7927. svr.listen(HOST, PORT);
  7928. } catch (...) { svr.decommission(); }
  7929. }};
  7930. svr.wait_until_ready();
  7931. // Server is up
  7932. {
  7933. Client cli(HOST, PORT);
  7934. auto res = cli.Get("/hi");
  7935. if (is_even) {
  7936. EXPECT_FALSE(res);
  7937. } else {
  7938. EXPECT_TRUE(res);
  7939. EXPECT_EQ("hi...", res->body);
  7940. }
  7941. }
  7942. svr.stop();
  7943. t.join();
  7944. // Server is down...
  7945. {
  7946. Client cli(HOST, PORT);
  7947. auto res = cli.Get("/hi");
  7948. EXPECT_FALSE(res);
  7949. }
  7950. }
  7951. }
  7952. #endif
  7953. // Helper function for string body upload progress tests
  7954. template <typename SetupHandler, typename ClientCall>
  7955. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7956. ClientCall &&client_call,
  7957. const string &body) {
  7958. Server svr;
  7959. setup_handler(svr);
  7960. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7961. auto se = detail::scope_exit([&] {
  7962. svr.stop();
  7963. t.join();
  7964. });
  7965. svr.wait_until_ready();
  7966. Client cli(HOST, PORT);
  7967. vector<uint64_t> progress_values;
  7968. bool progress_called = false;
  7969. auto res =
  7970. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7971. progress_values.push_back(current);
  7972. progress_called = true;
  7973. return true;
  7974. });
  7975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7976. EXPECT_EQ(200, res->status);
  7977. EXPECT_TRUE(progress_called);
  7978. }
  7979. TEST(UploadProgressTest, PostStringBodyBasic) {
  7980. TestStringBodyUploadProgress(
  7981. [](Server &svr) {
  7982. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7983. res.set_content("received", "text/plain");
  7984. });
  7985. },
  7986. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7987. return cli.Post("/test", body, "text/plain", progress_callback);
  7988. },
  7989. "test data for upload progress");
  7990. }
  7991. TEST(UploadProgressTest, PutStringBodyBasic) {
  7992. TestStringBodyUploadProgress(
  7993. [](Server &svr) {
  7994. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7995. res.set_content("put received", "text/plain");
  7996. });
  7997. },
  7998. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7999. return cli.Put("/test", body, "text/plain", progress_callback);
  8000. },
  8001. "put test data for upload progress");
  8002. }
  8003. TEST(UploadProgressTest, PatchStringBodyBasic) {
  8004. TestStringBodyUploadProgress(
  8005. [](Server &svr) {
  8006. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  8007. res.set_content("patch received", "text/plain");
  8008. });
  8009. },
  8010. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8011. return cli.Patch("/test", body, "text/plain", progress_callback);
  8012. },
  8013. "patch test data for upload progress");
  8014. }
  8015. // Helper function for content provider upload progress tests
  8016. template <typename SetupHandler, typename ClientCall>
  8017. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  8018. ClientCall &&client_call) {
  8019. Server svr;
  8020. setup_handler(svr);
  8021. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8022. auto se = detail::scope_exit([&] {
  8023. svr.stop();
  8024. t.join();
  8025. });
  8026. svr.wait_until_ready();
  8027. Client cli(HOST, PORT);
  8028. vector<uint64_t> progress_values;
  8029. auto res =
  8030. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8031. progress_values.push_back(current);
  8032. return true;
  8033. });
  8034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8035. EXPECT_EQ(200, res->status);
  8036. EXPECT_FALSE(progress_values.empty());
  8037. }
  8038. TEST(UploadProgressTest, PostContentProviderProgress) {
  8039. TestContentProviderUploadProgress(
  8040. [](Server &svr) {
  8041. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8042. res.set_content("provider received", "text/plain");
  8043. });
  8044. },
  8045. [](Client &cli, UploadProgress progress_callback) {
  8046. return cli.Post(
  8047. "/test", 10,
  8048. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  8049. sink.os << "test data";
  8050. return true;
  8051. },
  8052. "text/plain", progress_callback);
  8053. });
  8054. }
  8055. // Helper function for multipart upload progress tests
  8056. template <typename SetupHandler, typename ClientCall>
  8057. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  8058. ClientCall &&client_call,
  8059. const string &endpoint) {
  8060. Server svr;
  8061. setup_handler(svr);
  8062. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8063. auto se = detail::scope_exit([&] {
  8064. svr.stop();
  8065. t.join();
  8066. });
  8067. svr.wait_until_ready();
  8068. Client cli(HOST, PORT);
  8069. vector<uint64_t> progress_values;
  8070. UploadFormDataItems items = {
  8071. {"field1", "value1", "", ""},
  8072. {"field2", "longer value for progress tracking test", "", ""},
  8073. {"file1", "file content data for upload progress", "test.txt",
  8074. "text/plain"}};
  8075. auto res = client_call(cli, endpoint, items,
  8076. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8077. progress_values.push_back(current);
  8078. return true;
  8079. });
  8080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8081. EXPECT_EQ(200, res->status);
  8082. EXPECT_FALSE(progress_values.empty());
  8083. }
  8084. TEST(UploadProgressTest, PostMultipartProgress) {
  8085. TestMultipartUploadProgress(
  8086. [](Server &svr) {
  8087. svr.Post("/multipart", [](const Request &req, Response &res) {
  8088. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  8089. res.set_content("multipart received", "text/plain");
  8090. });
  8091. },
  8092. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  8093. UploadProgress progress_callback) {
  8094. return cli.Post(endpoint, items, progress_callback);
  8095. },
  8096. "/multipart");
  8097. }
  8098. // Helper function for basic download progress tests
  8099. template <typename SetupHandler, typename ClientCall>
  8100. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8101. ClientCall &&client_call, const string &endpoint,
  8102. size_t expected_content_size) {
  8103. Server svr;
  8104. setup_handler(svr);
  8105. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8106. auto se = detail::scope_exit([&] {
  8107. svr.stop();
  8108. t.join();
  8109. });
  8110. svr.wait_until_ready();
  8111. Client cli(HOST, PORT);
  8112. vector<uint64_t> progress_values;
  8113. auto res = client_call(cli, endpoint,
  8114. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8115. progress_values.push_back(current);
  8116. return true;
  8117. });
  8118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8119. EXPECT_EQ(200, res->status);
  8120. EXPECT_FALSE(progress_values.empty());
  8121. EXPECT_EQ(expected_content_size, res->body.size());
  8122. }
  8123. TEST(DownloadProgressTest, GetBasic) {
  8124. TestBasicDownloadProgress(
  8125. [](Server &svr) {
  8126. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8127. string content(1000, 'D');
  8128. res.set_content(content, "text/plain");
  8129. });
  8130. },
  8131. [](Client &cli, const string &endpoint,
  8132. DownloadProgress progress_callback) {
  8133. return cli.Get(endpoint, progress_callback);
  8134. },
  8135. "/download", 1000u);
  8136. }
  8137. // Helper function for content receiver download progress tests
  8138. template <typename SetupHandler, typename ClientCall>
  8139. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8140. ClientCall &&client_call,
  8141. const string &endpoint,
  8142. size_t expected_content_size) {
  8143. Server svr;
  8144. setup_handler(svr);
  8145. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8146. auto se = detail::scope_exit([&] {
  8147. svr.stop();
  8148. t.join();
  8149. });
  8150. svr.wait_until_ready();
  8151. Client cli(HOST, PORT);
  8152. vector<uint64_t> progress_values;
  8153. string received_body;
  8154. auto res = client_call(
  8155. cli, endpoint,
  8156. [&](const char *data, size_t data_length) -> bool {
  8157. received_body.append(data, data_length);
  8158. return true;
  8159. },
  8160. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8161. progress_values.push_back(current);
  8162. return true;
  8163. });
  8164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8165. EXPECT_EQ(200, res->status);
  8166. EXPECT_FALSE(progress_values.empty());
  8167. EXPECT_EQ(expected_content_size, received_body.size());
  8168. EXPECT_TRUE(res->body.empty());
  8169. }
  8170. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8171. TestContentReceiverDownloadProgress(
  8172. [](Server &svr) {
  8173. svr.Get("/download-receiver",
  8174. [](const Request & /*req*/, Response &res) {
  8175. string content(2000, 'R');
  8176. res.set_content(content, "text/plain");
  8177. });
  8178. },
  8179. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8180. DownloadProgress progress_callback) {
  8181. return cli.Get(endpoint, content_receiver, progress_callback);
  8182. },
  8183. "/download-receiver", 2000u);
  8184. }
  8185. TEST(StreamingTest, NoContentLengthStreaming) {
  8186. Server svr;
  8187. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8188. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8189. if (offset < 6) {
  8190. sink.os << (offset < 3 ? "a" : "b");
  8191. } else {
  8192. sink.done();
  8193. }
  8194. return true;
  8195. });
  8196. });
  8197. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8198. auto listen_se = detail::scope_exit([&] {
  8199. svr.stop();
  8200. listen_thread.join();
  8201. ASSERT_FALSE(svr.is_running());
  8202. });
  8203. svr.wait_until_ready();
  8204. Client client(HOST, PORT);
  8205. auto get_thread = std::thread([&client]() {
  8206. std::string s;
  8207. auto res =
  8208. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8209. s += std::string(data, len);
  8210. return true;
  8211. });
  8212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8213. EXPECT_EQ(StatusCode::OK_200, res->status);
  8214. EXPECT_EQ("aaabbb", s);
  8215. });
  8216. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8217. // Give GET time to get a few messages.
  8218. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8219. }
  8220. TEST(MountTest, Unmount) {
  8221. Server svr;
  8222. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8223. auto se = detail::scope_exit([&] {
  8224. svr.stop();
  8225. listen_thread.join();
  8226. ASSERT_FALSE(svr.is_running());
  8227. });
  8228. svr.wait_until_ready();
  8229. Client cli("localhost", PORT);
  8230. svr.set_mount_point("/mount2", "./www2");
  8231. auto res = cli.Get("/");
  8232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8234. res = cli.Get("/mount2/dir/test.html");
  8235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8236. EXPECT_EQ(StatusCode::OK_200, res->status);
  8237. svr.set_mount_point("/", "./www");
  8238. res = cli.Get("/dir/");
  8239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8240. EXPECT_EQ(StatusCode::OK_200, res->status);
  8241. svr.remove_mount_point("/");
  8242. res = cli.Get("/dir/");
  8243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8244. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8245. svr.remove_mount_point("/mount2");
  8246. res = cli.Get("/mount2/dir/test.html");
  8247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8248. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8249. }
  8250. TEST(MountTest, PathSegmentBoundary) {
  8251. Server svr;
  8252. svr.set_mount_point("/mount2", "./www2");
  8253. svr.set_mount_point("/", "./www");
  8254. auto port = svr.bind_to_any_port(HOST);
  8255. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8256. auto se = detail::scope_exit([&] {
  8257. svr.stop();
  8258. listen_thread.join();
  8259. ASSERT_FALSE(svr.is_running());
  8260. });
  8261. svr.wait_until_ready();
  8262. Client cli(HOST, port);
  8263. auto res = cli.Get("/mount2/dir/test.html");
  8264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8265. EXPECT_EQ(StatusCode::OK_200, res->status);
  8266. // "/mount2" must not match part-way through a path segment.
  8267. res = cli.Get("/mount2dir/test.html");
  8268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8269. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8270. // A mount point ending in '/' keeps matching every path below it.
  8271. res = cli.Get("/dir/test.html");
  8272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8273. EXPECT_EQ(StatusCode::OK_200, res->status);
  8274. }
  8275. TEST(MountTest, Redicect) {
  8276. Server svr;
  8277. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8278. auto se = detail::scope_exit([&] {
  8279. svr.stop();
  8280. listen_thread.join();
  8281. ASSERT_FALSE(svr.is_running());
  8282. });
  8283. svr.set_mount_point("/", "./www");
  8284. svr.wait_until_ready();
  8285. Client cli("localhost", PORT);
  8286. auto res = cli.Get("/dir/");
  8287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8288. EXPECT_EQ(StatusCode::OK_200, res->status);
  8289. res = cli.Get("/dir");
  8290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8291. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8292. res = cli.Get("/file");
  8293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8294. EXPECT_EQ(StatusCode::OK_200, res->status);
  8295. res = cli.Get("/file/");
  8296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8297. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8298. cli.set_follow_location(true);
  8299. res = cli.Get("/dir");
  8300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8301. EXPECT_EQ(StatusCode::OK_200, res->status);
  8302. }
  8303. TEST(MountTest, MultibytesPathName) {
  8304. Server svr;
  8305. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8306. auto se = detail::scope_exit([&] {
  8307. svr.stop();
  8308. listen_thread.join();
  8309. ASSERT_FALSE(svr.is_running());
  8310. });
  8311. svr.set_mount_point("/", "./www");
  8312. svr.wait_until_ready();
  8313. Client cli("localhost", PORT);
  8314. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8316. EXPECT_EQ(StatusCode::OK_200, res->status);
  8317. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8318. }
  8319. #ifdef _WIN32
  8320. // Issue #2435: mmap::open() must succeed even when another handle holds
  8321. // the file open for writing (e.g. an active log file).
  8322. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8323. const char *path = "mmap_concurrent_writer_test.txt";
  8324. const char *content = "hello";
  8325. {
  8326. std::ofstream f(path, std::ios::binary);
  8327. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8328. }
  8329. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8330. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8331. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8332. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8333. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8334. detail::mmap m(path);
  8335. ASSERT_TRUE(m.is_open());
  8336. EXPECT_EQ(strlen(content), m.size());
  8337. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8338. }
  8339. #endif
  8340. #ifndef _WIN32
  8341. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8342. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8343. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8344. TEST(MmapTest, FailedMappingIsNotOpen) {
  8345. const char *path = "./mmap_failed_mapping_test_dir";
  8346. ASSERT_EQ(0, ::mkdir(path, 0755));
  8347. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8348. detail::mmap m(path);
  8349. EXPECT_FALSE(m.is_open());
  8350. EXPECT_EQ(0U, m.size());
  8351. EXPECT_NE(static_cast<const void *>(m.data()),
  8352. static_cast<const void *>(MAP_FAILED));
  8353. }
  8354. #endif
  8355. TEST(KeepAliveTest, ReadTimeout) {
  8356. Server svr;
  8357. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8358. std::this_thread::sleep_for(std::chrono::seconds(2));
  8359. res.set_content("a", "text/plain");
  8360. });
  8361. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8362. res.set_content("b", "text/plain");
  8363. });
  8364. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8365. auto se = detail::scope_exit([&] {
  8366. svr.stop();
  8367. listen_thread.join();
  8368. ASSERT_FALSE(svr.is_running());
  8369. });
  8370. svr.wait_until_ready();
  8371. Client cli("localhost", PORT);
  8372. cli.set_keep_alive(true);
  8373. cli.set_read_timeout(std::chrono::seconds(1));
  8374. auto resa = cli.Get("/a");
  8375. ASSERT_FALSE(resa);
  8376. EXPECT_EQ(Error::Read, resa.error());
  8377. auto resb = cli.Get("/b");
  8378. ASSERT_TRUE(resb);
  8379. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8380. EXPECT_EQ("b", resb->body);
  8381. }
  8382. TEST(KeepAliveTest, MaxCount) {
  8383. size_t keep_alive_max_count = 3;
  8384. Server svr;
  8385. svr.set_keep_alive_max_count(keep_alive_max_count);
  8386. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8387. res.set_content("Hello World!", "text/plain");
  8388. });
  8389. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8390. auto se = detail::scope_exit([&] {
  8391. svr.stop();
  8392. listen_thread.join();
  8393. ASSERT_FALSE(svr.is_running());
  8394. });
  8395. svr.wait_until_ready();
  8396. Client cli(HOST, PORT);
  8397. cli.set_keep_alive(true);
  8398. for (size_t i = 0; i < 5; i++) {
  8399. auto result = cli.Get("/hi");
  8400. ASSERT_TRUE(result);
  8401. EXPECT_EQ(StatusCode::OK_200, result->status);
  8402. if (i == keep_alive_max_count - 1) {
  8403. EXPECT_EQ("close", result->get_header_value("Connection"));
  8404. } else {
  8405. EXPECT_FALSE(result->has_header("Connection"));
  8406. }
  8407. }
  8408. }
  8409. TEST(KeepAliveTest, Issue1041) {
  8410. Server svr;
  8411. svr.set_keep_alive_timeout(3);
  8412. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8413. res.set_content("Hello World!", "text/plain");
  8414. });
  8415. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8416. auto se = detail::scope_exit([&] {
  8417. svr.stop();
  8418. listen_thread.join();
  8419. ASSERT_FALSE(svr.is_running());
  8420. });
  8421. svr.wait_until_ready();
  8422. Client cli(HOST, PORT);
  8423. cli.set_keep_alive(true);
  8424. auto result = cli.Get("/hi");
  8425. ASSERT_TRUE(result);
  8426. EXPECT_EQ(StatusCode::OK_200, result->status);
  8427. std::this_thread::sleep_for(std::chrono::seconds(5));
  8428. result = cli.Get("/hi");
  8429. ASSERT_TRUE(result);
  8430. EXPECT_EQ(StatusCode::OK_200, result->status);
  8431. }
  8432. TEST(KeepAliveTest, Issue1959) {
  8433. Server svr;
  8434. svr.set_keep_alive_timeout(5);
  8435. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8436. res.set_content("a", "text/plain");
  8437. });
  8438. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8439. auto se = detail::scope_exit([&] {
  8440. if (!svr.is_running()) return;
  8441. svr.stop();
  8442. listen_thread.join();
  8443. ASSERT_FALSE(svr.is_running());
  8444. });
  8445. svr.wait_until_ready();
  8446. Client cli("localhost", PORT);
  8447. cli.set_keep_alive(true);
  8448. using namespace std::chrono;
  8449. auto start = steady_clock::now();
  8450. cli.Get("/a");
  8451. svr.stop();
  8452. listen_thread.join();
  8453. auto end = steady_clock::now();
  8454. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8455. EXPECT_LT(elapsed, 5000);
  8456. }
  8457. #ifdef CPPHTTPLIB_SSL_ENABLED
  8458. TEST(KeepAliveTest, SSLClientReconnection) {
  8459. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8460. ASSERT_TRUE(svr.is_valid());
  8461. svr.set_keep_alive_timeout(1);
  8462. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8463. res.set_content("Hello World!", "text/plain");
  8464. });
  8465. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8466. auto se = detail::scope_exit([&] {
  8467. svr.stop();
  8468. listen_thread.join();
  8469. ASSERT_FALSE(svr.is_running());
  8470. });
  8471. svr.wait_until_ready();
  8472. SSLClient cli(HOST, PORT);
  8473. cli.enable_server_certificate_verification(false);
  8474. cli.set_keep_alive(true);
  8475. auto result = cli.Get("/hi");
  8476. ASSERT_TRUE(result);
  8477. EXPECT_EQ(StatusCode::OK_200, result->status);
  8478. result = cli.Get("/hi");
  8479. ASSERT_TRUE(result);
  8480. EXPECT_EQ(StatusCode::OK_200, result->status);
  8481. std::this_thread::sleep_for(std::chrono::seconds(2));
  8482. // Recoonect
  8483. result = cli.Get("/hi");
  8484. ASSERT_TRUE(result);
  8485. EXPECT_EQ(StatusCode::OK_200, result->status);
  8486. result = cli.Get("/hi");
  8487. ASSERT_TRUE(result);
  8488. EXPECT_EQ(StatusCode::OK_200, result->status);
  8489. }
  8490. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8491. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8492. ASSERT_TRUE(svr.is_valid());
  8493. svr.set_keep_alive_timeout(1);
  8494. std::string content = "reconnect";
  8495. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8496. res.set_content("Hello World!", "text/plain");
  8497. });
  8498. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8499. auto se = detail::scope_exit([&] {
  8500. svr.stop();
  8501. listen_thread.join();
  8502. ASSERT_FALSE(svr.is_running());
  8503. });
  8504. svr.wait_until_ready();
  8505. SSLClient cli(HOST, PORT);
  8506. cli.enable_server_certificate_verification(false);
  8507. cli.set_keep_alive(true);
  8508. auto result = cli.Post(
  8509. "/hi", content.size(),
  8510. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8511. sink.write(content.c_str(), content.size());
  8512. return true;
  8513. },
  8514. "text/plain");
  8515. ASSERT_TRUE(result);
  8516. EXPECT_EQ(200, result->status);
  8517. std::this_thread::sleep_for(std::chrono::seconds(2));
  8518. // Recoonect
  8519. result = cli.Post(
  8520. "/hi", content.size(),
  8521. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8522. sink.write(content.c_str(), content.size());
  8523. return true;
  8524. },
  8525. "text/plain");
  8526. ASSERT_TRUE(result);
  8527. EXPECT_EQ(200, result->status);
  8528. result = cli.Post(
  8529. "/hi", content.size(),
  8530. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8531. sink.write(content.c_str(), content.size());
  8532. return true;
  8533. },
  8534. "text/plain");
  8535. ASSERT_TRUE(result);
  8536. EXPECT_EQ(200, result->status);
  8537. }
  8538. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8539. using namespace httplib::tls;
  8540. {
  8541. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8542. ASSERT_TRUE(svr.is_valid());
  8543. svr.Get("/sni", [&](const Request &req, Response &res) {
  8544. std::string expected = req.sni();
  8545. EXPECT_EQ(expected, req.get_param_value("expected"));
  8546. res.set_content("ok", "text/plain");
  8547. });
  8548. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8549. auto se = detail::scope_exit([&] {
  8550. svr.stop();
  8551. listen_thread.join();
  8552. ASSERT_FALSE(svr.is_running());
  8553. });
  8554. svr.wait_until_ready();
  8555. {
  8556. SSLClient cli("localhost", PORT);
  8557. cli.enable_server_certificate_verification(false);
  8558. auto res = cli.Get("/sni?expected=localhost");
  8559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8560. }
  8561. {
  8562. SSLClient cli("::1", PORT);
  8563. cli.enable_server_certificate_verification(false);
  8564. auto res = cli.Get("/sni?expected=");
  8565. // NOTE: This may fail if the server is listening on IPv4 only
  8566. // (e.g., when localhost resolves to 127.0.0.1 only)
  8567. if (res) {
  8568. EXPECT_EQ(StatusCode::OK_200, res->status);
  8569. } else {
  8570. EXPECT_EQ(Error::Connection, res.error());
  8571. }
  8572. }
  8573. }
  8574. }
  8575. #endif
  8576. TEST(ClientProblemDetectionTest, ContentProvider) {
  8577. Server svr;
  8578. size_t content_length = 1024 * 1024;
  8579. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8580. res.set_content_provider(
  8581. content_length, "text/plain",
  8582. [&](size_t offset, size_t length, DataSink &sink) {
  8583. auto out_len = std::min(length, static_cast<size_t>(1024));
  8584. std::string out(out_len, '@');
  8585. sink.write(out.data(), out_len);
  8586. return offset < 4096;
  8587. },
  8588. [](bool success) { ASSERT_FALSE(success); });
  8589. });
  8590. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8591. res.set_content_provider(
  8592. 0, "text/plain",
  8593. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8594. EXPECT_TRUE(false);
  8595. return true;
  8596. },
  8597. [](bool success) { ASSERT_FALSE(success); });
  8598. });
  8599. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8600. auto se = detail::scope_exit([&] {
  8601. svr.stop();
  8602. listen_thread.join();
  8603. ASSERT_FALSE(svr.is_running());
  8604. });
  8605. svr.wait_until_ready();
  8606. Client cli("localhost", PORT);
  8607. {
  8608. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8609. size_t /*data_length*/) { return false; });
  8610. ASSERT_FALSE(res);
  8611. }
  8612. {
  8613. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8614. size_t /*data_length*/) { return false; });
  8615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8616. }
  8617. }
  8618. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8619. Server svr;
  8620. svr.set_error_handler([](Request const &, Response &res) -> void {
  8621. res.set_chunked_content_provider(
  8622. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8623. sink.os << "hello";
  8624. sink.os << "world";
  8625. sink.done();
  8626. return true;
  8627. });
  8628. });
  8629. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8630. auto se = detail::scope_exit([&] {
  8631. svr.stop();
  8632. listen_thread.join();
  8633. ASSERT_FALSE(svr.is_running());
  8634. });
  8635. svr.wait_until_ready();
  8636. Client cli("localhost", PORT);
  8637. auto res = cli.Get("/");
  8638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8639. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8640. EXPECT_EQ("helloworld", res->body);
  8641. }
  8642. TEST(LongPollingTest, ClientCloseDetection) {
  8643. Server svr;
  8644. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8645. res.set_chunked_content_provider(
  8646. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8647. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8648. sink.os << "hello";
  8649. auto count = 10;
  8650. while (count > 0 && sink.is_writable()) {
  8651. this_thread::sleep_for(chrono::milliseconds(10));
  8652. count--;
  8653. }
  8654. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8655. return true;
  8656. });
  8657. });
  8658. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8659. auto se = detail::scope_exit([&] {
  8660. svr.stop();
  8661. listen_thread.join();
  8662. ASSERT_FALSE(svr.is_running());
  8663. });
  8664. svr.wait_until_ready();
  8665. Client cli("localhost", PORT);
  8666. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8667. EXPECT_EQ("hello", string(data, data_length));
  8668. return false; // close the socket immediately.
  8669. });
  8670. ASSERT_FALSE(res);
  8671. }
  8672. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8673. Server svr;
  8674. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8675. res.set_chunked_content_provider(
  8676. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8677. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8678. sink.os << "hello";
  8679. EXPECT_TRUE(sink.os.good());
  8680. // Wait for the client to close the connection
  8681. auto count = 10;
  8682. while (count > 0 && sink.is_writable()) {
  8683. this_thread::sleep_for(chrono::milliseconds(10));
  8684. count--;
  8685. }
  8686. // After client disconnect, write repeatedly until the socket
  8687. // write actually fails (small writes may be absorbed by the
  8688. // kernel buffer)
  8689. std::string chunk(1024, 'x');
  8690. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8691. sink.os << chunk;
  8692. }
  8693. EXPECT_TRUE(sink.os.fail());
  8694. return true;
  8695. });
  8696. });
  8697. auto port = svr.bind_to_any_port("localhost");
  8698. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8699. auto se = detail::scope_exit([&] {
  8700. svr.stop();
  8701. listen_thread.join();
  8702. ASSERT_FALSE(svr.is_running());
  8703. });
  8704. svr.wait_until_ready();
  8705. Client cli("localhost", port);
  8706. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8707. EXPECT_EQ("hello", string(data, data_length));
  8708. return false; // close the socket immediately.
  8709. });
  8710. ASSERT_FALSE(res);
  8711. }
  8712. TEST(GetWithParametersTest, GetWithParameters) {
  8713. Server svr;
  8714. svr.Get("/", [&](const Request &req, Response &) {
  8715. EXPECT_EQ("world", req.get_param_value("hello"));
  8716. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8717. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8718. });
  8719. svr.Get("/params", [&](const Request &req, Response &) {
  8720. EXPECT_EQ("world", req.get_param_value("hello"));
  8721. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8722. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8723. });
  8724. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8725. EXPECT_EQ("resource-id", req.matches[1]);
  8726. EXPECT_EQ("foo", req.get_param_value("param1"));
  8727. EXPECT_EQ("bar", req.get_param_value("param2"));
  8728. });
  8729. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8730. EXPECT_EQ("user-id", req.path_params.at("id"));
  8731. EXPECT_EQ("foo", req.get_param_value("param1"));
  8732. EXPECT_EQ("bar", req.get_param_value("param2"));
  8733. });
  8734. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8735. auto se = detail::scope_exit([&] {
  8736. svr.stop();
  8737. listen_thread.join();
  8738. ASSERT_FALSE(svr.is_running());
  8739. });
  8740. svr.wait_until_ready();
  8741. {
  8742. Client cli(HOST, PORT);
  8743. Params params;
  8744. params.emplace("hello", "world");
  8745. params.emplace("hello2", "world2");
  8746. params.emplace("hello3", "world3");
  8747. auto res = cli.Get("/", params, Headers{});
  8748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8749. EXPECT_EQ(StatusCode::OK_200, res->status);
  8750. }
  8751. {
  8752. Client cli(HOST, PORT);
  8753. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8755. EXPECT_EQ(StatusCode::OK_200, res->status);
  8756. }
  8757. {
  8758. Client cli(HOST, PORT);
  8759. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8761. EXPECT_EQ(StatusCode::OK_200, res->status);
  8762. }
  8763. {
  8764. Client cli(HOST, PORT);
  8765. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8767. EXPECT_EQ(StatusCode::OK_200, res->status);
  8768. }
  8769. }
  8770. TEST(GetWithParametersTest, GetWithParameters2) {
  8771. Server svr;
  8772. svr.Get("/", [&](const Request &req, Response &res) {
  8773. auto text = req.get_param_value("hello");
  8774. res.set_content(text, "text/plain");
  8775. });
  8776. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8777. auto se = detail::scope_exit([&] {
  8778. svr.stop();
  8779. listen_thread.join();
  8780. ASSERT_FALSE(svr.is_running());
  8781. });
  8782. svr.wait_until_ready();
  8783. Client cli("localhost", PORT);
  8784. Params params;
  8785. params.emplace("hello", "world");
  8786. std::string body;
  8787. auto res = cli.Get("/", params, Headers{},
  8788. [&](const char *data, size_t data_length) {
  8789. body.append(data, data_length);
  8790. return true;
  8791. });
  8792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8793. EXPECT_EQ(StatusCode::OK_200, res->status);
  8794. EXPECT_EQ("world", body);
  8795. }
  8796. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8797. Server svr;
  8798. svr.Get("/search", [&](const Request &req, Response &res) {
  8799. auto q = req.get_param_value("q");
  8800. res.set_content(q, "text/plain");
  8801. });
  8802. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8803. auto se = detail::scope_exit([&] {
  8804. svr.stop();
  8805. listen_thread.join();
  8806. ASSERT_FALSE(svr.is_running());
  8807. });
  8808. svr.wait_until_ready();
  8809. Client cli("localhost", PORT);
  8810. // Verify that Get(path, params) works without requiring Headers argument
  8811. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8813. EXPECT_EQ(StatusCode::OK_200, res->status);
  8814. EXPECT_EQ("cpp-httplib", res->body);
  8815. }
  8816. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8817. auto host = "httpbingo.org";
  8818. auto path = std::string{"/range/32"};
  8819. #ifdef CPPHTTPLIB_SSL_ENABLED
  8820. SSLClient cli(host);
  8821. #else
  8822. Client cli(host);
  8823. #endif
  8824. cli.set_default_headers({make_range_header({{1, 10}})});
  8825. cli.set_connection_timeout(5);
  8826. {
  8827. auto res = cli.Get(path);
  8828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8829. EXPECT_EQ("bcdefghijk", res->body);
  8830. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8831. }
  8832. {
  8833. auto res = cli.Get(path);
  8834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8835. EXPECT_EQ("bcdefghijk", res->body);
  8836. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8837. }
  8838. }
  8839. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8840. Server svr;
  8841. svr.set_default_headers({{"Hello", "World"}});
  8842. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8843. res.set_content("ok", "text/plain");
  8844. });
  8845. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8846. auto se = detail::scope_exit([&] {
  8847. svr.stop();
  8848. listen_thread.join();
  8849. ASSERT_FALSE(svr.is_running());
  8850. });
  8851. svr.wait_until_ready();
  8852. Client cli("localhost", PORT);
  8853. auto res = cli.Get("/");
  8854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8855. EXPECT_EQ(StatusCode::OK_200, res->status);
  8856. EXPECT_EQ("ok", res->body);
  8857. EXPECT_EQ("World", res->get_header_value("Hello"));
  8858. }
  8859. #ifdef CPPHTTPLIB_SSL_ENABLED
  8860. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8861. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8862. ASSERT_TRUE(svr.is_valid());
  8863. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8864. std::this_thread::sleep_for(std::chrono::seconds(2));
  8865. res.set_content("a", "text/plain");
  8866. });
  8867. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8868. res.set_content("b", "text/plain");
  8869. });
  8870. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8871. auto se = detail::scope_exit([&] {
  8872. svr.stop();
  8873. listen_thread.join();
  8874. ASSERT_FALSE(svr.is_running());
  8875. });
  8876. svr.wait_until_ready();
  8877. SSLClient cli("localhost", PORT);
  8878. cli.enable_server_certificate_verification(false);
  8879. cli.set_keep_alive(true);
  8880. cli.set_read_timeout(std::chrono::seconds(1));
  8881. auto resa = cli.Get("/a");
  8882. ASSERT_TRUE(!resa);
  8883. EXPECT_EQ(Error::Read, resa.error());
  8884. auto resb = cli.Get("/b");
  8885. ASSERT_TRUE(resb);
  8886. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8887. EXPECT_EQ("b", resb->body);
  8888. }
  8889. #endif
  8890. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8891. protected:
  8892. ServerTestWithAI_PASSIVE()
  8893. : cli_(HOST, PORT)
  8894. #ifdef CPPHTTPLIB_SSL_ENABLED
  8895. ,
  8896. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8897. #endif
  8898. {
  8899. #ifdef CPPHTTPLIB_SSL_ENABLED
  8900. cli_.enable_server_certificate_verification(false);
  8901. #endif
  8902. }
  8903. virtual void SetUp() {
  8904. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8905. res.set_content("Hello World!", "text/plain");
  8906. });
  8907. t_ = thread(
  8908. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8909. svr_.wait_until_ready();
  8910. }
  8911. virtual void TearDown() {
  8912. svr_.stop();
  8913. t_.join();
  8914. }
  8915. #ifdef CPPHTTPLIB_SSL_ENABLED
  8916. SSLClient cli_;
  8917. SSLServer svr_;
  8918. #else
  8919. Client cli_;
  8920. Server svr_;
  8921. #endif
  8922. thread t_;
  8923. };
  8924. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8925. auto res = cli_.Get("/hi");
  8926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8927. EXPECT_EQ(StatusCode::OK_200, res->status);
  8928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8929. EXPECT_EQ("Hello World!", res->body);
  8930. }
  8931. class ServerUpDownTest : public ::testing::Test {
  8932. protected:
  8933. ServerUpDownTest() : cli_(HOST, PORT) {}
  8934. virtual void SetUp() {
  8935. t_ = thread([&]() {
  8936. svr_.bind_to_any_port(HOST);
  8937. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8938. ASSERT_TRUE(svr_.listen_after_bind());
  8939. });
  8940. svr_.wait_until_ready();
  8941. }
  8942. virtual void TearDown() {
  8943. svr_.stop();
  8944. t_.join();
  8945. }
  8946. Client cli_;
  8947. Server svr_;
  8948. thread t_;
  8949. };
  8950. TEST_F(ServerUpDownTest, QuickStartStop) {
  8951. // Should not crash, especially when run with
  8952. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8953. }
  8954. class PayloadMaxLengthTest : public ::testing::Test {
  8955. protected:
  8956. PayloadMaxLengthTest()
  8957. : cli_(HOST, PORT)
  8958. #ifdef CPPHTTPLIB_SSL_ENABLED
  8959. ,
  8960. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8961. #endif
  8962. {
  8963. #ifdef CPPHTTPLIB_SSL_ENABLED
  8964. cli_.enable_server_certificate_verification(false);
  8965. #endif
  8966. }
  8967. virtual void SetUp() {
  8968. svr_.set_payload_max_length(8);
  8969. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8970. res.set_content("test", "text/plain");
  8971. });
  8972. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8973. svr_.wait_until_ready();
  8974. }
  8975. virtual void TearDown() {
  8976. svr_.stop();
  8977. t_.join();
  8978. }
  8979. #ifdef CPPHTTPLIB_SSL_ENABLED
  8980. SSLClient cli_;
  8981. SSLServer svr_;
  8982. #else
  8983. Client cli_;
  8984. Server svr_;
  8985. #endif
  8986. thread t_;
  8987. };
  8988. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8989. auto res = cli_.Post("/test", "123456789", "text/plain");
  8990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8991. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8992. res = cli_.Post("/test", "12345678", "text/plain");
  8993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8994. EXPECT_EQ(StatusCode::OK_200, res->status);
  8995. }
  8996. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8997. // Test chunked encoding with payload exceeding the 8-byte limit
  8998. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8999. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  9000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9001. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9002. }
  9003. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  9004. // Test chunked encoding with payload within the 8-byte limit
  9005. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  9006. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  9007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9008. EXPECT_EQ(StatusCode::OK_200, res->status);
  9009. }
  9010. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  9011. // Test using send_request to send chunked data exceeding payload limit
  9012. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  9013. "Host: " +
  9014. std::string(HOST) + ":" + std::to_string(PORT) +
  9015. "\r\n"
  9016. "Transfer-Encoding: chunked\r\n"
  9017. "Connection: close\r\n"
  9018. "\r\n"
  9019. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  9020. "0123456789\r\n"
  9021. "0\r\n" // End chunk
  9022. "\r\n";
  9023. std::string response;
  9024. bool result = send_request(1, chunked_request, &response);
  9025. if (!result) {
  9026. // If send_request fails, it might be because the server closed the
  9027. // connection due to payload limit enforcement, which is acceptable
  9028. SUCCEED()
  9029. << "Server rejected oversized chunked request (connection closed)";
  9030. } else {
  9031. // If we got a response, check if it's an error response or connection was
  9032. // closed early Short response length indicates connection was closed due to
  9033. // payload limit
  9034. if (response.length() <= 10) {
  9035. SUCCEED() << "Server closed connection for oversized chunked request";
  9036. } else {
  9037. // Check for error status codes
  9038. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9039. response.find("Payload Too Large") != std::string::npos ||
  9040. response.find("400") != std::string::npos);
  9041. }
  9042. }
  9043. }
  9044. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  9045. // Test request without Content-Length header exceeding payload limit
  9046. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9047. "Host: " +
  9048. std::string(HOST) + ":" +
  9049. std::to_string(PORT) +
  9050. "\r\n"
  9051. "Connection: close\r\n"
  9052. "\r\n";
  9053. // Add payload exceeding the 8-byte limit
  9054. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  9055. request_without_content_length += large_payload;
  9056. std::string response;
  9057. bool result = send_request(1, request_without_content_length, &response);
  9058. if (!result) {
  9059. // If send_request fails, server likely closed connection due to payload
  9060. // limit
  9061. SUCCEED() << "Server rejected oversized request without Content-Length "
  9062. "(connection closed)";
  9063. } else {
  9064. // Check if server responded with error or closed connection early
  9065. if (response.length() <= 10) {
  9066. SUCCEED() << "Server closed connection for oversized request without "
  9067. "Content-Length";
  9068. } else {
  9069. // Check for error status codes
  9070. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9071. response.find("Payload Too Large") != std::string::npos ||
  9072. response.find("400") != std::string::npos);
  9073. }
  9074. }
  9075. }
  9076. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  9077. // Test request without Content-Length header within payload limit
  9078. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9079. "Host: " +
  9080. std::string(HOST) + ":" +
  9081. std::to_string(PORT) +
  9082. "\r\n"
  9083. "Connection: close\r\n"
  9084. "\r\n";
  9085. // Add payload within the 8-byte limit
  9086. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  9087. request_without_content_length += small_payload;
  9088. std::string response;
  9089. bool result = send_request(1, request_without_content_length, &response);
  9090. // For requests without Content-Length, the server may have different behavior
  9091. // The key is that it should not reject due to payload limit for small
  9092. // payloads
  9093. if (result) {
  9094. // Check for any HTTP response (success or error, but not connection closed)
  9095. if (response.length() > 10) {
  9096. SUCCEED()
  9097. << "Server processed request without Content-Length within limit";
  9098. } else {
  9099. // Short response might indicate connection closed, which is acceptable
  9100. SUCCEED() << "Server closed connection for request without "
  9101. "Content-Length (acceptable behavior)";
  9102. }
  9103. } else {
  9104. // Connection failure might be due to protocol requirements
  9105. SUCCEED() << "Connection issue with request without Content-Length "
  9106. "(environment-specific)";
  9107. }
  9108. }
  9109. class LargePayloadMaxLengthTest : public ::testing::Test {
  9110. protected:
  9111. LargePayloadMaxLengthTest()
  9112. : cli_(HOST, PORT)
  9113. #ifdef CPPHTTPLIB_SSL_ENABLED
  9114. ,
  9115. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9116. #endif
  9117. {
  9118. #ifdef CPPHTTPLIB_SSL_ENABLED
  9119. cli_.enable_server_certificate_verification(false);
  9120. #endif
  9121. }
  9122. virtual void SetUp() {
  9123. // Set 10MB payload limit
  9124. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9125. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9126. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9127. res.set_content("Large payload test", "text/plain");
  9128. });
  9129. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9130. svr_.wait_until_ready();
  9131. }
  9132. virtual void TearDown() {
  9133. svr_.stop();
  9134. t_.join();
  9135. }
  9136. #ifdef CPPHTTPLIB_SSL_ENABLED
  9137. SSLClient cli_;
  9138. SSLServer svr_;
  9139. #else
  9140. Client cli_;
  9141. Server svr_;
  9142. #endif
  9143. thread t_;
  9144. };
  9145. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9146. // Test chunked encoding with payload within 10MB limit
  9147. std::string medium_payload(5 * 1024 * 1024,
  9148. 'A'); // 5MB payload, within 10MB limit
  9149. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9151. EXPECT_EQ(StatusCode::OK_200, res->status);
  9152. }
  9153. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9154. // Test chunked encoding with payload exceeding 10MB limit
  9155. std::string large_payload(12 * 1024 * 1024,
  9156. 'B'); // 12MB payload, exceeds 10MB limit
  9157. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9158. // Server may either return 413 or close the connection
  9159. if (res) {
  9160. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9161. } else {
  9162. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9163. }
  9164. }
  9165. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9166. // Test request without Content-Length header within 10MB limit
  9167. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9168. "Host: " +
  9169. std::string(HOST) + ":" +
  9170. std::to_string(PORT) +
  9171. "\r\n"
  9172. "Connection: close\r\n"
  9173. "\r\n";
  9174. // Add 1MB payload (within 10MB limit)
  9175. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9176. request_without_content_length += medium_payload;
  9177. std::string response;
  9178. bool result = send_request(5, request_without_content_length, &response);
  9179. if (result) {
  9180. // Should get a proper HTTP response for payloads within limit
  9181. if (response.length() > 10) {
  9182. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9183. "10MB limit";
  9184. } else {
  9185. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9186. "Content-Length)";
  9187. }
  9188. } else {
  9189. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9190. }
  9191. }
  9192. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9193. // Test request without Content-Length header exceeding 10MB limit
  9194. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9195. "Host: " +
  9196. std::string(HOST) + ":" +
  9197. std::to_string(PORT) +
  9198. "\r\n"
  9199. "Connection: close\r\n"
  9200. "\r\n";
  9201. // Add 12MB payload (exceeds 10MB limit)
  9202. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9203. request_without_content_length += large_payload;
  9204. std::string response;
  9205. bool result = send_request(10, request_without_content_length, &response);
  9206. if (!result) {
  9207. // Server should close connection due to payload limit
  9208. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9209. "(connection closed)";
  9210. } else {
  9211. // Check for error response
  9212. if (response.length() <= 10) {
  9213. SUCCEED()
  9214. << "Server closed connection for 12MB request exceeding 10MB limit";
  9215. } else {
  9216. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9217. response.find("Payload Too Large") != std::string::npos ||
  9218. response.find("400") != std::string::npos);
  9219. }
  9220. }
  9221. }
  9222. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9223. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9224. // path.
  9225. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9226. Server svr;
  9227. const size_t LIMIT = 64 * 1024; // 64KB
  9228. svr.set_payload_max_length(LIMIT);
  9229. size_t total = 0;
  9230. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9231. const ContentReader &content_reader) {
  9232. content_reader([&](const char * /*data*/, size_t len) {
  9233. total += len;
  9234. return true;
  9235. });
  9236. res.status = 200;
  9237. res.set_content("stream_ok", "text/plain");
  9238. });
  9239. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9240. auto se = detail::scope_exit([&] {
  9241. svr.stop();
  9242. thread.join();
  9243. ASSERT_FALSE(svr.is_running());
  9244. });
  9245. svr.wait_until_ready();
  9246. // Prepare 256KB raw data and gzip-compress it
  9247. std::string raw(256 * 1024, 'A');
  9248. std::string gz;
  9249. {
  9250. z_stream zs{};
  9251. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9252. Z_DEFAULT_STRATEGY);
  9253. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9254. zs.avail_in = static_cast<uInt>(raw.size());
  9255. char outbuf[4096];
  9256. int ret;
  9257. do {
  9258. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9259. zs.avail_out = sizeof(outbuf);
  9260. ret = deflate(&zs, Z_FINISH);
  9261. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9262. } while (ret != Z_STREAM_END);
  9263. deflateEnd(&zs);
  9264. }
  9265. Client cli(HOST, PORT);
  9266. cli.set_connection_timeout(std::chrono::seconds(5));
  9267. Headers headers = {{"Content-Encoding", "gzip"}};
  9268. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9269. "application/octet-stream");
  9270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9271. // Server must reject oversized decompressed payloads with 413.
  9272. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9273. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9274. EXPECT_LE(total, LIMIT);
  9275. }
  9276. #ifndef CPPHTTPLIB_SSL_ENABLED
  9277. // For a request with neither Content-Length nor Transfer-Encoding, the
  9278. // non-SSL raw-socket fallback in read_content_core() used to hand the
  9279. // compressed wire bytes straight to the ContentReader without ever routing
  9280. // them through the decompressor, so payload_max_length_ only bounded the
  9281. // compressed size on the wire, not the decompressed size.
  9282. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  9283. Server svr;
  9284. const size_t LIMIT = 64 * 1024; // 64KB
  9285. svr.set_payload_max_length(LIMIT);
  9286. size_t total = 0;
  9287. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9288. const ContentReader &content_reader) {
  9289. content_reader([&](const char * /*data*/, size_t len) {
  9290. total += len;
  9291. return true;
  9292. });
  9293. res.status = 200;
  9294. res.set_content("stream_ok", "text/plain");
  9295. });
  9296. auto port = svr.bind_to_any_port(HOST);
  9297. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9298. auto se = detail::scope_exit([&] {
  9299. svr.stop();
  9300. thread.join();
  9301. ASSERT_FALSE(svr.is_running());
  9302. });
  9303. svr.wait_until_ready();
  9304. // Prepare 256KB raw data and gzip-compress it, same payload as the
  9305. // StreamingGzipDecompression test above.
  9306. std::string raw(256 * 1024, 'A');
  9307. std::string gz;
  9308. {
  9309. httplib::detail::gzip_compressor compressor;
  9310. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  9311. [&](const char *chunk, size_t len) {
  9312. gz.append(chunk, len);
  9313. return true;
  9314. });
  9315. ASSERT_TRUE(result);
  9316. }
  9317. // Send the gzip body over raw TCP with neither Content-Length nor
  9318. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  9319. // kicks in.
  9320. std::string req = "POST /stream HTTP/1.1\r\n"
  9321. "Host: " +
  9322. std::string(HOST) + ":" + std::to_string(port) +
  9323. "\r\n"
  9324. "Content-Encoding: gzip\r\n"
  9325. "Connection: close\r\n"
  9326. "\r\n" +
  9327. gz;
  9328. std::string response;
  9329. ASSERT_TRUE(send_request(5, req, &response, port));
  9330. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9331. EXPECT_LE(total, LIMIT);
  9332. }
  9333. #endif
  9334. #endif
  9335. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9336. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9337. // the payload must be passed through untouched instead of being rejected.
  9338. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9339. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9340. Server svr;
  9341. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9342. res.set_content(body, "image/jpeg");
  9343. res.set_header("Content-Encoding", "UTF-8");
  9344. });
  9345. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9346. res.set_content(body, "image/jpeg");
  9347. res.set_header("Content-Encoding", "identity");
  9348. });
  9349. svr.Post("/echo", [](const Request &req, Response &res) {
  9350. res.set_content(req.body, "image/jpeg");
  9351. });
  9352. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9353. auto se = detail::scope_exit([&] {
  9354. svr.stop();
  9355. t.join();
  9356. ASSERT_FALSE(svr.is_running());
  9357. });
  9358. svr.wait_until_ready();
  9359. Client cli(HOST, PORT);
  9360. {
  9361. auto res = cli.Get("/image");
  9362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9363. EXPECT_EQ(StatusCode::OK_200, res->status);
  9364. EXPECT_EQ(body, res->body);
  9365. }
  9366. {
  9367. auto res = cli.Get("/identity");
  9368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9369. EXPECT_EQ(StatusCode::OK_200, res->status);
  9370. EXPECT_EQ(body, res->body);
  9371. }
  9372. {
  9373. // The same applies to a request body reaching the server.
  9374. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9375. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9377. EXPECT_EQ(StatusCode::OK_200, res->status);
  9378. EXPECT_EQ(body, res->body);
  9379. }
  9380. }
  9381. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9382. // gzip-encoded response even when the build has no zlib support.
  9383. static const char GZIPPED_HELLO_WORLD[] = {
  9384. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9385. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9386. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9387. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9388. // A content coding is a whole token, not something the field value merely
  9389. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  9390. // as "fibre" look like Brotli, and turned a multi-coding value like
  9391. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  9392. // it was never meant to see.
  9393. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  9394. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9395. Server svr;
  9396. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  9397. res.set_content(body, "image/jpeg");
  9398. res.set_header("Content-Encoding", "fibre");
  9399. });
  9400. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  9401. res.set_content(body, "image/jpeg");
  9402. res.set_header("Content-Encoding", "gzip, br");
  9403. });
  9404. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  9405. res.set_content(body, "image/jpeg");
  9406. res.set_header("Content-Encoding", "x-zstd-ish");
  9407. });
  9408. auto port = svr.bind_to_any_port(HOST);
  9409. thread t = thread([&]() { svr.listen_after_bind(); });
  9410. auto se = detail::scope_exit([&] {
  9411. svr.stop();
  9412. t.join();
  9413. ASSERT_FALSE(svr.is_running());
  9414. });
  9415. svr.wait_until_ready();
  9416. Client cli(HOST, port);
  9417. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  9418. auto res = cli.Get(path);
  9419. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9420. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9421. // Not a coding we recognize, so the payload comes back untouched
  9422. EXPECT_EQ(body, res->body) << path;
  9423. }
  9424. }
  9425. // A content coding cpp-httplib recognizes but was not built with must be
  9426. // reported as such. Handing the still-compressed payload back to the caller
  9427. // would silently corrupt it.
  9428. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9429. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9430. Server svr;
  9431. // "image/jpeg" keeps the server from applying a content coding of its own,
  9432. // so the hand-crafted Content-Encoding below survives.
  9433. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9434. res.set_content(gzipped, "image/jpeg");
  9435. res.set_header("Content-Encoding", "gzip");
  9436. });
  9437. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9438. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9439. res.set_content(gzipped, "image/jpeg");
  9440. res.set_header("Content-Encoding", "GZIP");
  9441. });
  9442. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9443. auto se = detail::scope_exit([&] {
  9444. svr.stop();
  9445. t.join();
  9446. ASSERT_FALSE(svr.is_running());
  9447. });
  9448. svr.wait_until_ready();
  9449. Client cli(HOST, PORT);
  9450. {
  9451. auto res = cli.Get("/gzipped");
  9452. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9454. EXPECT_EQ("Hello World!", res->body);
  9455. #else
  9456. ASSERT_FALSE(res);
  9457. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9458. #endif
  9459. }
  9460. {
  9461. // open_stream() must behave the same way.
  9462. auto handle = cli.open_stream("GET", "/gzipped");
  9463. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9464. ASSERT_TRUE(handle.is_valid());
  9465. std::string received;
  9466. char buf[256];
  9467. ssize_t n;
  9468. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9469. received.append(buf, static_cast<size_t>(n));
  9470. }
  9471. EXPECT_EQ("Hello World!", received);
  9472. #else
  9473. EXPECT_FALSE(handle.is_valid());
  9474. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9475. #endif
  9476. }
  9477. {
  9478. // A differently-cased coding must not be mistaken for an unknown one, or
  9479. // the body would be handed back still compressed.
  9480. auto res = cli.Get("/gzipped-uppercase");
  9481. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9483. EXPECT_EQ("Hello World!", res->body);
  9484. #else
  9485. ASSERT_FALSE(res);
  9486. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9487. #endif
  9488. }
  9489. }
  9490. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  9491. // the same message as the comma-joined one, so both have to be read the same
  9492. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  9493. // single gzip coding, and a body the sender says was encoded twice was handed
  9494. // back after one pass, still compressed but presented as decoded.
  9495. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  9496. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9497. Server svr;
  9498. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  9499. res.set_content(body, "image/jpeg");
  9500. res.headers.emplace("Content-Encoding", "gzip");
  9501. res.headers.emplace("Content-Encoding", "gzip");
  9502. });
  9503. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  9504. res.set_content(body, "image/jpeg");
  9505. res.set_header("Content-Encoding", "gzip, gzip");
  9506. });
  9507. auto port = svr.bind_to_any_port(HOST);
  9508. thread t = thread([&]() { svr.listen_after_bind(); });
  9509. auto se = detail::scope_exit([&] {
  9510. svr.stop();
  9511. t.join();
  9512. ASSERT_FALSE(svr.is_running());
  9513. });
  9514. svr.wait_until_ready();
  9515. Client cli(HOST, port);
  9516. // Two codings is not something cpp-httplib decodes, so both representations
  9517. // take the pass-through path rather than one of them being gunzipped once.
  9518. for (const char *path : {"/split", "/joined"}) {
  9519. auto res = cli.Get(path);
  9520. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9521. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9522. EXPECT_EQ(body, res->body) << path;
  9523. }
  9524. }
  9525. // Regression test for DoS vulnerability: a malicious server sending a response
  9526. // without Content-Length header must not cause unbounded memory consumption on
  9527. // the client side. The client should stop reading after a reasonable limit,
  9528. // similar to the server-side set_payload_max_length protection.
  9529. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9530. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9531. #ifndef _WIN32
  9532. signal(SIGPIPE, SIG_IGN);
  9533. #endif
  9534. auto server_thread = std::thread([] {
  9535. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9536. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9537. default_socket_options(srv);
  9538. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9539. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9540. sockaddr_in addr{};
  9541. addr.sin_family = AF_INET;
  9542. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9543. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9544. int opt = 1;
  9545. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9546. #ifdef _WIN32
  9547. reinterpret_cast<const char *>(&opt),
  9548. #else
  9549. &opt,
  9550. #endif
  9551. sizeof(opt));
  9552. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9553. ::listen(srv, 1);
  9554. sockaddr_in cli_addr{};
  9555. socklen_t cli_len = sizeof(cli_addr);
  9556. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9557. if (cli != INVALID_SOCKET) {
  9558. char buf[4096];
  9559. ::recv(cli, buf, sizeof(buf), 0);
  9560. // Malicious response: no Content-Length, no chunked encoding
  9561. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9562. "Connection: close\r\n"
  9563. "\r\n";
  9564. ::send(cli,
  9565. #ifdef _WIN32
  9566. static_cast<const char *>(response_header.c_str()),
  9567. static_cast<int>(response_header.size()),
  9568. #else
  9569. response_header.c_str(), response_header.size(),
  9570. #endif
  9571. 0);
  9572. // Send 10MB of data
  9573. std::string chunk(64 * 1024, 'A');
  9574. size_t total_sent = 0;
  9575. while (total_sent < MALICIOUS_DATA_SIZE) {
  9576. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9577. auto sent = ::send(cli,
  9578. #ifdef _WIN32
  9579. static_cast<const char *>(chunk.c_str()),
  9580. static_cast<int>(to_send),
  9581. #else
  9582. chunk.c_str(), to_send,
  9583. #endif
  9584. 0);
  9585. if (sent <= 0) break;
  9586. total_sent += static_cast<size_t>(sent);
  9587. }
  9588. detail::close_socket(cli);
  9589. }
  9590. detail::close_socket(srv);
  9591. });
  9592. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9593. size_t total_read = 0;
  9594. {
  9595. Client cli("127.0.0.1", PORT + 2);
  9596. cli.set_read_timeout(5, 0);
  9597. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9598. auto stream = cli.open_stream("GET", "/malicious");
  9599. ASSERT_TRUE(stream.is_valid());
  9600. char buffer[64 * 1024];
  9601. ssize_t n;
  9602. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9603. total_read += static_cast<size_t>(n);
  9604. }
  9605. } // StreamHandle and Client destroyed here, closing the socket
  9606. server_thread.join();
  9607. // With set_payload_max_length, the client must stop reading before consuming
  9608. // all 10MB. The read loop should be cut off at or near the configured limit.
  9609. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9610. << "Client read " << total_read << " bytes, exceeding the configured "
  9611. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9612. }
  9613. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9614. // the entire response body without truncation.
  9615. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9616. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9617. #ifndef _WIN32
  9618. signal(SIGPIPE, SIG_IGN);
  9619. #endif
  9620. auto server_thread = std::thread([] {
  9621. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9622. default_socket_options(srv);
  9623. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9624. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9625. sockaddr_in addr{};
  9626. addr.sin_family = AF_INET;
  9627. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9628. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9629. int opt = 1;
  9630. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9631. #ifdef _WIN32
  9632. reinterpret_cast<const char *>(&opt),
  9633. #else
  9634. &opt,
  9635. #endif
  9636. sizeof(opt));
  9637. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9638. ::listen(srv, 1);
  9639. sockaddr_in cli_addr{};
  9640. socklen_t cli_len = sizeof(cli_addr);
  9641. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9642. if (cli != INVALID_SOCKET) {
  9643. char buf[4096];
  9644. ::recv(cli, buf, sizeof(buf), 0);
  9645. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9646. "Connection: close\r\n"
  9647. "\r\n";
  9648. ::send(cli,
  9649. #ifdef _WIN32
  9650. static_cast<const char *>(response_header.c_str()),
  9651. static_cast<int>(response_header.size()),
  9652. #else
  9653. response_header.c_str(), response_header.size(),
  9654. #endif
  9655. 0);
  9656. std::string chunk(64 * 1024, 'A');
  9657. size_t total_sent = 0;
  9658. while (total_sent < DATA_SIZE) {
  9659. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9660. auto sent = ::send(cli,
  9661. #ifdef _WIN32
  9662. static_cast<const char *>(chunk.c_str()),
  9663. static_cast<int>(to_send),
  9664. #else
  9665. chunk.c_str(), to_send,
  9666. #endif
  9667. 0);
  9668. if (sent <= 0) break;
  9669. total_sent += static_cast<size_t>(sent);
  9670. }
  9671. #ifdef _WIN32
  9672. ::shutdown(cli, SD_SEND);
  9673. #else
  9674. ::shutdown(cli, SHUT_WR);
  9675. #endif
  9676. // Drain until the client closes its end, ensuring all data is delivered
  9677. char drain[1024];
  9678. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9679. detail::close_socket(cli);
  9680. }
  9681. detail::close_socket(srv);
  9682. });
  9683. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9684. size_t total_read = 0;
  9685. {
  9686. Client cli("127.0.0.1", PORT + 2);
  9687. cli.set_read_timeout(5, 0);
  9688. cli.set_payload_max_length(0); // 0 means no limit
  9689. auto stream = cli.open_stream("GET", "/data");
  9690. ASSERT_TRUE(stream.is_valid());
  9691. char buffer[64 * 1024];
  9692. ssize_t n;
  9693. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9694. total_read += static_cast<size_t>(n);
  9695. }
  9696. }
  9697. server_thread.join();
  9698. EXPECT_EQ(total_read, DATA_SIZE)
  9699. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9700. << " bytes without truncation, but only read " << total_read << " bytes.";
  9701. }
  9702. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9703. // enormous Content-Length must not cause the client to pre-allocate a huge
  9704. // response body buffer. The reservation is capped at payload_max_length_, and
  9705. // the read itself fails when the body exceeds the limit.
  9706. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9707. #ifndef _WIN32
  9708. signal(SIGPIPE, SIG_IGN);
  9709. #endif
  9710. auto server_thread = std::thread([] {
  9711. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9712. default_socket_options(srv);
  9713. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9714. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9715. sockaddr_in addr{};
  9716. addr.sin_family = AF_INET;
  9717. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9718. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9719. int opt = 1;
  9720. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9721. #ifdef _WIN32
  9722. reinterpret_cast<const char *>(&opt),
  9723. #else
  9724. &opt,
  9725. #endif
  9726. sizeof(opt));
  9727. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9728. ::listen(srv, 1);
  9729. sockaddr_in cli_addr{};
  9730. socklen_t cli_len = sizeof(cli_addr);
  9731. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9732. if (cli != INVALID_SOCKET) {
  9733. char buf[4096];
  9734. ::recv(cli, buf, sizeof(buf), 0);
  9735. // Malicious response: claim a 20GB body but send only a tiny payload.
  9736. std::string response = "HTTP/1.1 200 OK\r\n"
  9737. "Content-Length: 20000000000\r\n"
  9738. "\r\n"
  9739. "abc";
  9740. ::send(cli,
  9741. #ifdef _WIN32
  9742. static_cast<const char *>(response.c_str()),
  9743. static_cast<int>(response.size()),
  9744. #else
  9745. response.c_str(), response.size(),
  9746. #endif
  9747. 0);
  9748. detail::close_socket(cli);
  9749. }
  9750. detail::close_socket(srv);
  9751. });
  9752. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9753. {
  9754. Client cli("127.0.0.1", PORT + 2);
  9755. cli.set_read_timeout(5, 0);
  9756. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9757. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9758. // (server claims more bytes than payload_max_length permits), but it must
  9759. // not exhaust memory before getting there.
  9760. auto res = cli.Get("/malicious");
  9761. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9762. }
  9763. server_thread.join();
  9764. }
  9765. // Verify that content_receiver bypasses the default payload_max_length,
  9766. // allowing streaming downloads larger than 100MB without requiring an explicit
  9767. // set_payload_max_length call.
  9768. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9769. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9770. #ifndef _WIN32
  9771. signal(SIGPIPE, SIG_IGN);
  9772. #endif
  9773. auto server_thread = std::thread([] {
  9774. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9775. default_socket_options(srv);
  9776. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9777. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9778. sockaddr_in addr{};
  9779. addr.sin_family = AF_INET;
  9780. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9781. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9782. int opt = 1;
  9783. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9784. #ifdef _WIN32
  9785. reinterpret_cast<const char *>(&opt),
  9786. #else
  9787. &opt,
  9788. #endif
  9789. sizeof(opt));
  9790. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9791. ::listen(srv, 1);
  9792. sockaddr_in cli_addr{};
  9793. socklen_t cli_len = sizeof(cli_addr);
  9794. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9795. if (cli != INVALID_SOCKET) {
  9796. char buf[4096];
  9797. ::recv(cli, buf, sizeof(buf), 0);
  9798. // Response with Content-Length larger than default 100MB limit
  9799. auto content_length = std::to_string(DATA_SIZE);
  9800. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9801. "Content-Length: " +
  9802. content_length +
  9803. "\r\n"
  9804. "Connection: close\r\n"
  9805. "\r\n";
  9806. ::send(cli,
  9807. #ifdef _WIN32
  9808. static_cast<const char *>(response_header.c_str()),
  9809. static_cast<int>(response_header.size()),
  9810. #else
  9811. response_header.c_str(), response_header.size(),
  9812. #endif
  9813. 0);
  9814. std::string chunk(64 * 1024, 'A');
  9815. size_t total_sent = 0;
  9816. while (total_sent < DATA_SIZE) {
  9817. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9818. auto sent = ::send(cli,
  9819. #ifdef _WIN32
  9820. static_cast<const char *>(chunk.c_str()),
  9821. static_cast<int>(to_send),
  9822. #else
  9823. chunk.c_str(), to_send,
  9824. #endif
  9825. 0);
  9826. if (sent <= 0) break;
  9827. total_sent += static_cast<size_t>(sent);
  9828. }
  9829. detail::close_socket(cli);
  9830. }
  9831. detail::close_socket(srv);
  9832. });
  9833. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9834. size_t total_received = 0;
  9835. {
  9836. Client cli("127.0.0.1", PORT + 2);
  9837. cli.set_read_timeout(10, 0);
  9838. // Do NOT call set_payload_max_length — use the default 100MB limit
  9839. auto res =
  9840. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9841. total_received += data_length;
  9842. return true;
  9843. });
  9844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9845. EXPECT_EQ(StatusCode::OK_200, res->status);
  9846. }
  9847. server_thread.join();
  9848. EXPECT_EQ(total_received, DATA_SIZE)
  9849. << "With content_receiver, the client should read all " << DATA_SIZE
  9850. << " bytes despite the default 100MB payload_max_length, but only read "
  9851. << total_received << " bytes.";
  9852. }
  9853. // Verify that an explicit set_payload_max_length smaller than the response is
  9854. // enforced even when a content_receiver is used.
  9855. TEST(ClientVulnerabilityTest,
  9856. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9857. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9858. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9859. #ifndef _WIN32
  9860. signal(SIGPIPE, SIG_IGN);
  9861. #endif
  9862. auto server_thread = std::thread([] {
  9863. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9864. default_socket_options(srv);
  9865. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9866. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9867. sockaddr_in addr{};
  9868. addr.sin_family = AF_INET;
  9869. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9870. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9871. int opt = 1;
  9872. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9873. #ifdef _WIN32
  9874. reinterpret_cast<const char *>(&opt),
  9875. #else
  9876. &opt,
  9877. #endif
  9878. sizeof(opt));
  9879. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9880. ::listen(srv, 1);
  9881. sockaddr_in cli_addr{};
  9882. socklen_t cli_len = sizeof(cli_addr);
  9883. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9884. if (cli != INVALID_SOCKET) {
  9885. char buf[4096];
  9886. ::recv(cli, buf, sizeof(buf), 0);
  9887. auto content_length = std::to_string(DATA_SIZE);
  9888. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9889. "Content-Length: " +
  9890. content_length +
  9891. "\r\n"
  9892. "Connection: close\r\n"
  9893. "\r\n";
  9894. ::send(cli,
  9895. #ifdef _WIN32
  9896. static_cast<const char *>(response_header.c_str()),
  9897. static_cast<int>(response_header.size()),
  9898. #else
  9899. response_header.c_str(), response_header.size(),
  9900. #endif
  9901. 0);
  9902. std::string chunk(64 * 1024, 'A');
  9903. size_t total_sent = 0;
  9904. while (total_sent < DATA_SIZE) {
  9905. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9906. auto sent = ::send(cli,
  9907. #ifdef _WIN32
  9908. static_cast<const char *>(chunk.c_str()),
  9909. static_cast<int>(to_send),
  9910. #else
  9911. chunk.c_str(), to_send,
  9912. #endif
  9913. 0);
  9914. if (sent <= 0) break;
  9915. total_sent += static_cast<size_t>(sent);
  9916. }
  9917. detail::close_socket(cli);
  9918. }
  9919. detail::close_socket(srv);
  9920. });
  9921. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9922. size_t total_received = 0;
  9923. {
  9924. Client cli("127.0.0.1", PORT + 2);
  9925. cli.set_read_timeout(10, 0);
  9926. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9927. auto res =
  9928. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9929. total_received += data_length;
  9930. return true;
  9931. });
  9932. // Should fail because 200MB exceeds the explicit 150MB limit
  9933. EXPECT_FALSE(res);
  9934. }
  9935. server_thread.join();
  9936. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9937. << "Client with content_receiver should respect the explicit "
  9938. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9939. << total_received << " bytes.";
  9940. }
  9941. // Verify that an explicit set_payload_max_length larger than the response
  9942. // allows the content_receiver to read all data successfully.
  9943. TEST(ClientVulnerabilityTest,
  9944. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9945. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9946. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9947. #ifndef _WIN32
  9948. signal(SIGPIPE, SIG_IGN);
  9949. #endif
  9950. auto server_thread = std::thread([] {
  9951. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9952. default_socket_options(srv);
  9953. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9954. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9955. sockaddr_in addr{};
  9956. addr.sin_family = AF_INET;
  9957. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9958. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9959. int opt = 1;
  9960. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9961. #ifdef _WIN32
  9962. reinterpret_cast<const char *>(&opt),
  9963. #else
  9964. &opt,
  9965. #endif
  9966. sizeof(opt));
  9967. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9968. ::listen(srv, 1);
  9969. sockaddr_in cli_addr{};
  9970. socklen_t cli_len = sizeof(cli_addr);
  9971. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9972. if (cli != INVALID_SOCKET) {
  9973. char buf[4096];
  9974. ::recv(cli, buf, sizeof(buf), 0);
  9975. auto content_length = std::to_string(DATA_SIZE);
  9976. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9977. "Content-Length: " +
  9978. content_length +
  9979. "\r\n"
  9980. "Connection: close\r\n"
  9981. "\r\n";
  9982. ::send(cli,
  9983. #ifdef _WIN32
  9984. static_cast<const char *>(response_header.c_str()),
  9985. static_cast<int>(response_header.size()),
  9986. #else
  9987. response_header.c_str(), response_header.size(),
  9988. #endif
  9989. 0);
  9990. std::string chunk(64 * 1024, 'A');
  9991. size_t total_sent = 0;
  9992. while (total_sent < DATA_SIZE) {
  9993. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9994. auto sent = ::send(cli,
  9995. #ifdef _WIN32
  9996. static_cast<const char *>(chunk.c_str()),
  9997. static_cast<int>(to_send),
  9998. #else
  9999. chunk.c_str(), to_send,
  10000. #endif
  10001. 0);
  10002. if (sent <= 0) break;
  10003. total_sent += static_cast<size_t>(sent);
  10004. }
  10005. #ifdef _WIN32
  10006. ::shutdown(cli, SD_SEND);
  10007. #else
  10008. ::shutdown(cli, SHUT_WR);
  10009. #endif
  10010. char drain[1024];
  10011. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10012. detail::close_socket(cli);
  10013. }
  10014. detail::close_socket(srv);
  10015. });
  10016. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10017. size_t total_received = 0;
  10018. {
  10019. Client cli("127.0.0.1", PORT + 2);
  10020. cli.set_read_timeout(10, 0);
  10021. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  10022. auto res =
  10023. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10024. total_received += data_length;
  10025. return true;
  10026. });
  10027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10028. EXPECT_EQ(StatusCode::OK_200, res->status);
  10029. }
  10030. server_thread.join();
  10031. EXPECT_EQ(total_received, DATA_SIZE)
  10032. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  10033. << " bytes (larger than " << DATA_SIZE
  10034. << " bytes response), content_receiver should read all data, but only "
  10035. "read "
  10036. << total_received << " bytes.";
  10037. }
  10038. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  10039. // Regression test for "zip bomb" attack on the client side: a malicious server
  10040. // sends a small gzip-compressed response that decompresses to a huge payload.
  10041. // The client must enforce payload_max_length on the decompressed size.
  10042. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  10043. constexpr size_t DECOMPRESSED_SIZE =
  10044. 10 * 1024 * 1024; // 10MB after decompression
  10045. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10046. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  10047. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  10048. std::string compressed;
  10049. {
  10050. httplib::detail::gzip_compressor compressor;
  10051. bool ok =
  10052. compressor.compress(uncompressed.data(), uncompressed.size(),
  10053. /*last=*/true, [&](const char *buf, size_t len) {
  10054. compressed.append(buf, len);
  10055. return true;
  10056. });
  10057. ASSERT_TRUE(ok);
  10058. }
  10059. // Sanity: compressed data should be much smaller than the decompressed size
  10060. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  10061. #ifndef _WIN32
  10062. signal(SIGPIPE, SIG_IGN);
  10063. #endif
  10064. // Set up the listening socket in the main thread so the server is guaranteed
  10065. // to be ready before the client connects (eliminates race condition).
  10066. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10067. default_socket_options(srv);
  10068. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10069. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10070. sockaddr_in addr{};
  10071. addr.sin_family = AF_INET;
  10072. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  10073. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10074. int opt = 1;
  10075. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10076. #ifdef _WIN32
  10077. reinterpret_cast<const char *>(&opt),
  10078. #else
  10079. &opt,
  10080. #endif
  10081. sizeof(opt));
  10082. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  10083. ASSERT_EQ(0, ::listen(srv, 1));
  10084. auto server_thread = std::thread([&compressed, srv] {
  10085. sockaddr_in cli_addr{};
  10086. socklen_t cli_len = sizeof(cli_addr);
  10087. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10088. if (cli != INVALID_SOCKET) {
  10089. // Read the full HTTP request (until \r\n\r\n)
  10090. char buf[4096];
  10091. size_t total = 0;
  10092. while (total < sizeof(buf)) {
  10093. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  10094. if (n <= 0) break;
  10095. total += static_cast<size_t>(n);
  10096. // Check for end of headers
  10097. if (total >= 4) {
  10098. std::string req(buf, total);
  10099. if (req.find("\r\n\r\n") != std::string::npos) break;
  10100. }
  10101. }
  10102. // Malicious response: gzip-compressed body, no Content-Length
  10103. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10104. "Content-Encoding: gzip\r\n"
  10105. "Connection: close\r\n"
  10106. "\r\n";
  10107. ::send(cli,
  10108. #ifdef _WIN32
  10109. static_cast<const char *>(response_header.c_str()),
  10110. static_cast<int>(response_header.size()),
  10111. #else
  10112. response_header.c_str(), response_header.size(),
  10113. #endif
  10114. 0);
  10115. // Send the compressed payload (small on the wire, huge when decompressed)
  10116. size_t total_sent = 0;
  10117. while (total_sent < compressed.size()) {
  10118. auto to_send = std::min(compressed.size() - total_sent,
  10119. static_cast<size_t>(64 * 1024));
  10120. auto sent =
  10121. ::send(cli,
  10122. #ifdef _WIN32
  10123. static_cast<const char *>(compressed.c_str() + total_sent),
  10124. static_cast<int>(to_send),
  10125. #else
  10126. compressed.c_str() + total_sent, to_send,
  10127. #endif
  10128. 0);
  10129. if (sent <= 0) break;
  10130. total_sent += static_cast<size_t>(sent);
  10131. }
  10132. detail::close_socket(cli);
  10133. }
  10134. });
  10135. auto se = detail::scope_exit([&] {
  10136. detail::close_socket(srv);
  10137. server_thread.join();
  10138. });
  10139. size_t total_decompressed = 0;
  10140. {
  10141. Client cli("127.0.0.1", PORT + 3);
  10142. cli.set_read_timeout(5, 0);
  10143. cli.set_decompress(true);
  10144. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10145. auto stream = cli.open_stream("GET", "/zipbomb");
  10146. ASSERT_TRUE(stream.is_valid());
  10147. char buffer[64 * 1024];
  10148. ssize_t n;
  10149. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10150. total_decompressed += static_cast<size_t>(n);
  10151. }
  10152. }
  10153. // The decompressed size must be capped by payload_max_length. Without
  10154. // protection, the client would decompress the full 10MB from a tiny
  10155. // compressed payload, enabling a zip bomb DoS attack.
  10156. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  10157. << "Client decompressed " << total_decompressed
  10158. << " bytes from a gzip response. The decompressed size should be "
  10159. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  10160. }
  10161. #endif
  10162. TEST(HostAndPortPropertiesTest, NoSSL) {
  10163. httplib::Client cli("www.google.com", 1234);
  10164. ASSERT_EQ("www.google.com", cli.host());
  10165. ASSERT_EQ(1234, cli.port());
  10166. }
  10167. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10168. httplib::Client cli("www.google.com:1234");
  10169. ASSERT_EQ("www.google.com", cli.host());
  10170. ASSERT_EQ(1234, cli.port());
  10171. }
  10172. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10173. // Port number that overflows int — should not crash, client becomes invalid
  10174. httplib::Client cli("http://www.google.com:99999999999999999999");
  10175. ASSERT_FALSE(cli.is_valid());
  10176. }
  10177. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10178. // Port 99999 exceeds valid range (1-65535) — should not crash
  10179. httplib::Client cli("http://www.google.com:99999");
  10180. ASSERT_FALSE(cli.is_valid());
  10181. }
  10182. #ifdef CPPHTTPLIB_SSL_ENABLED
  10183. TEST(HostAndPortPropertiesTest, SSL) {
  10184. httplib::SSLClient cli("www.google.com");
  10185. ASSERT_EQ("www.google.com", cli.host());
  10186. ASSERT_EQ(443, cli.port());
  10187. }
  10188. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10189. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10190. std::string cert;
  10191. read_file(CA_CERT_FILE, cert);
  10192. httplib::SSLClient httplib_client("www.google.com");
  10193. // Load CA store first time
  10194. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10195. // Load CA store second time (update)
  10196. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10197. // Verify client is still valid and can make connections
  10198. httplib_client.enable_server_certificate_verification(true);
  10199. auto res = httplib_client.Get("/");
  10200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10201. // Google may return 200 or 301 depending on various factors
  10202. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10203. res->status == StatusCode::MovedPermanently_301);
  10204. }
  10205. TEST(SSLClientTest, ServerNameIndication_Online) {
  10206. auto host = "httpbingo.org";
  10207. auto path = std::string{"/get"};
  10208. SSLClient cli(host, 443);
  10209. auto res = cli.Get(path);
  10210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10211. ASSERT_EQ(StatusCode::OK_200, res->status);
  10212. }
  10213. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10214. // Use a site that will cause SSL verification failure due to self-signed cert
  10215. SSLClient cli("self-signed.badssl.com", 443);
  10216. cli.enable_server_certificate_verification(true);
  10217. auto res = cli.Get("/");
  10218. ASSERT_TRUE(!res);
  10219. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10220. // Verify backend error is captured for SSLServerVerification
  10221. // This occurs when certificate verification fails
  10222. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10223. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10224. EXPECT_NE(0UL, res.ssl_backend_error());
  10225. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10226. // For OpenSSL, ssl_error is 0 for verification errors
  10227. EXPECT_EQ(0, res.ssl_error());
  10228. #if !defined(_WIN32) || \
  10229. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10230. // On non-Windows or when Windows Schannel is disabled, the error comes
  10231. // from OpenSSL's verification
  10232. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10233. res.ssl_backend_error());
  10234. #endif
  10235. #endif
  10236. }
  10237. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10238. // Use a site where hostname doesn't match the certificate
  10239. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10240. SSLClient cli("wrong.host.badssl.com", 443);
  10241. cli.enable_server_certificate_verification(true);
  10242. cli.enable_server_hostname_verification(true);
  10243. auto res = cli.Get("/");
  10244. ASSERT_TRUE(!res);
  10245. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10246. // Verify backend error is captured for hostname verification failure
  10247. EXPECT_NE(0UL, res.ssl_backend_error());
  10248. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10249. // For OpenSSL, ssl_error is 0 for verification errors
  10250. EXPECT_EQ(0, res.ssl_error());
  10251. #if !defined(_WIN32) || \
  10252. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10253. // On non-Windows or when Windows Schannel is disabled, the error comes
  10254. // from OpenSSL's hostname verification
  10255. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10256. res.ssl_backend_error());
  10257. #endif
  10258. #endif
  10259. }
  10260. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10261. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10262. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10263. SSLClient cli("www.google.com", 443);
  10264. cli.enable_server_certificate_verification(true);
  10265. auto res = cli.Get("/");
  10266. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10267. }
  10268. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10269. SSLClient cli("www.google.com", 443);
  10270. cli.enable_server_certificate_verification(true);
  10271. cli.enable_windows_certificate_verification(false);
  10272. auto res = cli.Get("/");
  10273. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10274. }
  10275. #endif
  10276. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10277. Client cli("https://google.com");
  10278. auto res = cli.Get("/");
  10279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10280. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10281. }
  10282. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10283. SSLClient cli("google.com");
  10284. cli.set_ca_cert_path(CA_CERT_FILE);
  10285. auto res = cli.Get("/");
  10286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10287. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10288. }
  10289. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10290. SSLClient cli("google.com");
  10291. cli.enable_server_certificate_verification(true);
  10292. cli.set_ca_cert_path("hello");
  10293. auto res = cli.Get("/");
  10294. ASSERT_TRUE(!res);
  10295. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10296. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10297. // should be set
  10298. EXPECT_EQ(0, res.ssl_error());
  10299. // Verify backend error is captured for SSLLoadingCerts
  10300. // This error occurs when loading CA certificates fails
  10301. EXPECT_NE(0UL, res.ssl_backend_error());
  10302. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10303. // OpenSSL specific error codes:
  10304. // > openssl errstr 0x80000002
  10305. // error:80000002:system library::No such file or directory
  10306. // > openssl errstr 0xA000126
  10307. // error:0A000126:SSL routines::unexpected eof while reading
  10308. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10309. res.ssl_backend_error() == 0xA000126);
  10310. #endif
  10311. }
  10312. TEST(SSLClientTest, ServerCertificateVerification4) {
  10313. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10314. ASSERT_TRUE(svr.is_valid());
  10315. svr.Get("/test", [&](const Request &, Response &res) {
  10316. res.set_content("test", "text/plain");
  10317. svr.stop();
  10318. ASSERT_TRUE(true);
  10319. });
  10320. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10321. auto se = detail::scope_exit([&] {
  10322. t.join();
  10323. ASSERT_FALSE(svr.is_running());
  10324. });
  10325. svr.wait_until_ready();
  10326. SSLClient cli("127.0.0.1", PORT);
  10327. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10328. cli.enable_server_certificate_verification(true);
  10329. cli.set_connection_timeout(30);
  10330. auto res = cli.Get("/test");
  10331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10332. ASSERT_EQ(StatusCode::OK_200, res->status);
  10333. }
  10334. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10335. std::string cert;
  10336. read_file(CA_CERT_FILE, cert);
  10337. SSLClient cli("google.com");
  10338. cli.load_ca_cert_store(cert.data(), cert.size());
  10339. const auto res = cli.Get("/");
  10340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10341. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10342. }
  10343. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10344. // clang-format off
  10345. static constexpr char cert[] =
  10346. "GlobalSign Root CA\n"
  10347. "==================\n"
  10348. "-----BEGIN CERTIFICATE-----\n"
  10349. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10350. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10351. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10352. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10353. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10354. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10355. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10356. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10357. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10358. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10359. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10360. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10361. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10362. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10363. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10364. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10365. "-----END CERTIFICATE-----\n";
  10366. // clang-format on
  10367. SSLClient cli("google.com");
  10368. cli.load_ca_cert_store(cert, sizeof(cert));
  10369. const auto res = cli.Get("/");
  10370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10371. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10372. }
  10373. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10374. SSLClient cli("www.youtube.com");
  10375. cli.set_ca_cert_path(CA_CERT_FILE);
  10376. cli.enable_server_certificate_verification(true);
  10377. cli.set_follow_location(true);
  10378. auto res = cli.Get("/");
  10379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10380. ASSERT_EQ(StatusCode::OK_200, res->status);
  10381. }
  10382. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10383. SSLClient cli("wWw.YouTube.Com");
  10384. cli.set_ca_cert_path(CA_CERT_FILE);
  10385. cli.enable_server_certificate_verification(true);
  10386. cli.enable_server_hostname_verification(true);
  10387. cli.set_follow_location(true);
  10388. auto res = cli.Get("/");
  10389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10390. ASSERT_EQ(StatusCode::OK_200, res->status);
  10391. }
  10392. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10393. SSLClient cli("gOoGlE.COm");
  10394. cli.enable_server_certificate_verification(true);
  10395. cli.enable_server_hostname_verification(true);
  10396. cli.set_follow_location(true);
  10397. auto res = cli.Get("/");
  10398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10399. ASSERT_EQ(StatusCode::OK_200, res->status);
  10400. }
  10401. TEST(SSLClientTest, Issue2004_Online) {
  10402. Client client("https://google.com");
  10403. client.set_follow_location(true);
  10404. auto res = client.Get("/");
  10405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10406. ASSERT_EQ(StatusCode::OK_200, res->status);
  10407. auto body = res->body;
  10408. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10409. }
  10410. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10411. // Create SSLClient with invalid cert/key to make is_valid() return false
  10412. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10413. "nonexistent_key.pem");
  10414. // is_valid() should be false due to cert loading failure
  10415. ASSERT_FALSE(cli.is_valid());
  10416. auto res = cli.Get("/");
  10417. ASSERT_FALSE(res);
  10418. EXPECT_EQ(Error::SSLConnection, res.error());
  10419. }
  10420. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10421. // Test for Issue #2251: SSL error not properly reported when client cert
  10422. // and key paths are swapped or mismatched
  10423. // This simulates the scenario where user accidentally swaps the cert and key
  10424. // files
  10425. // Using client cert file as private key and vice versa (completely wrong)
  10426. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10427. // Should fail validation due to cert/key mismatch
  10428. ASSERT_FALSE(cli.is_valid());
  10429. // Attempt to make a request should fail with proper error
  10430. auto res = cli.Get("/");
  10431. ASSERT_FALSE(res);
  10432. EXPECT_EQ(Error::SSLConnection, res.error());
  10433. // SSL error should be recorded in the Result object (this is the key fix for
  10434. // Issue #2251)
  10435. auto backend_error = res.ssl_backend_error();
  10436. EXPECT_NE(0u, backend_error);
  10437. }
  10438. // Tests cert/key mismatch detection at the TLS context level
  10439. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10440. // Test that using mismatched cert/key causes connection failure.
  10441. // We verify this at the SSLClient level rather than through internal
  10442. // TLS API functions.
  10443. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10444. cli.enable_server_certificate_verification(false);
  10445. cli.set_connection_timeout(2);
  10446. // The mismatch should cause a connection or handshake error
  10447. auto res = cli.Get("/test");
  10448. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10449. // Either way, the request should fail
  10450. EXPECT_FALSE(res);
  10451. }
  10452. #endif
  10453. #if 0
  10454. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10455. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10456. ASSERT_TRUE(cli != nullptr);
  10457. cli->set_address_family(AF_INET6);
  10458. cli->set_interface("en0");
  10459. auto res = cli->Get("/get");
  10460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10461. ASSERT_EQ(StatusCode::OK_200, res->status);
  10462. }
  10463. #endif
  10464. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10465. #ifdef CPPHTTPLIB_SSL_ENABLED
  10466. void ClientCertPresent(
  10467. const std::string &client_cert_file,
  10468. const std::string &client_private_key_file,
  10469. const std::string &client_encrypted_private_key_pass = std::string()) {
  10470. using namespace httplib::tls;
  10471. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10472. CLIENT_CA_CERT_DIR);
  10473. ASSERT_TRUE(svr.is_valid());
  10474. svr.Get("/test", [&](const Request &req, Response &res) {
  10475. res.set_content("test", "text/plain");
  10476. auto cert = req.peer_cert();
  10477. ASSERT_TRUE(static_cast<bool>(cert));
  10478. std::string common_name = cert.subject_cn();
  10479. EXPECT_EQ("Common Name", common_name);
  10480. });
  10481. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10482. auto se = detail::scope_exit([&] {
  10483. svr.stop();
  10484. t.join();
  10485. ASSERT_FALSE(svr.is_running());
  10486. });
  10487. svr.wait_until_ready();
  10488. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10489. client_encrypted_private_key_pass);
  10490. cli.enable_server_certificate_verification(false);
  10491. cli.set_connection_timeout(30);
  10492. auto res = cli.Get("/test");
  10493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10494. ASSERT_EQ(StatusCode::OK_200, res->status);
  10495. }
  10496. TEST(SSLClientServerTest, ClientCertPresent) {
  10497. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10498. }
  10499. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10500. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10501. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10502. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10503. }
  10504. // PEM memory-based constructor tests (works with all TLS backends)
  10505. void PemMemoryClientCertPresent(
  10506. const std::string &client_cert_file,
  10507. const std::string &client_private_key_file,
  10508. const std::string &client_encrypted_private_key_pass = std::string()) {
  10509. // Read PEM files into memory
  10510. std::string server_cert_pem, server_key_pem;
  10511. std::string client_ca_pem;
  10512. std::string client_cert_pem, client_key_pem;
  10513. read_file(SERVER_CERT_FILE, server_cert_pem);
  10514. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10515. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10516. read_file(client_cert_file, client_cert_pem);
  10517. read_file(client_private_key_file, client_key_pem);
  10518. // Create server with PEM memory
  10519. SSLServer::PemMemory server_pem = {
  10520. server_cert_pem.c_str(),
  10521. server_cert_pem.size(),
  10522. server_key_pem.c_str(),
  10523. server_key_pem.size(),
  10524. client_ca_pem.c_str(),
  10525. client_ca_pem.size(),
  10526. nullptr // no password for server key
  10527. };
  10528. SSLServer svr(server_pem);
  10529. ASSERT_TRUE(svr.is_valid());
  10530. svr.Get("/test", [&](const Request &, Response &res) {
  10531. res.set_content("test", "text/plain");
  10532. });
  10533. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10534. auto se = detail::scope_exit([&] {
  10535. svr.stop();
  10536. t.join();
  10537. ASSERT_FALSE(svr.is_running());
  10538. });
  10539. svr.wait_until_ready();
  10540. // Create client with PEM memory
  10541. const char *password = client_encrypted_private_key_pass.empty()
  10542. ? nullptr
  10543. : client_encrypted_private_key_pass.c_str();
  10544. SSLClient::PemMemory client_pem = {
  10545. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10546. client_key_pem.size(), password};
  10547. SSLClient cli(HOST, PORT, client_pem);
  10548. cli.enable_server_certificate_verification(false);
  10549. cli.set_connection_timeout(30);
  10550. auto res = cli.Get("/test");
  10551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10552. ASSERT_EQ(StatusCode::OK_200, res->status);
  10553. }
  10554. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10555. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10556. }
  10557. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10558. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10559. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10560. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10561. }
  10562. TEST(SSLClientServerTest, ClientCertMissing) {
  10563. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10564. CLIENT_CA_CERT_DIR);
  10565. ASSERT_TRUE(svr.is_valid());
  10566. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10567. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10568. auto se = detail::scope_exit([&] {
  10569. svr.stop();
  10570. t.join();
  10571. ASSERT_FALSE(svr.is_running());
  10572. });
  10573. svr.wait_until_ready();
  10574. SSLClient cli(HOST, PORT);
  10575. cli.set_connection_timeout(30);
  10576. auto res = cli.Get("/test");
  10577. ASSERT_TRUE(!res);
  10578. // When client cert is missing and server requires it, connection fails
  10579. // Error type depends on backend implementation
  10580. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10581. res.error() == Error::SSLConnection);
  10582. // Verify backend error is captured
  10583. // Note: This test may have different error codes depending on the exact
  10584. // verification failure
  10585. EXPECT_NE(0UL, res.ssl_backend_error());
  10586. }
  10587. TEST(SSLClientServerTest, TrustDirOptional) {
  10588. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10589. ASSERT_TRUE(svr.is_valid());
  10590. svr.Get("/test", [&](const Request &, Response &res) {
  10591. res.set_content("test", "text/plain");
  10592. });
  10593. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10594. auto se = detail::scope_exit([&] {
  10595. svr.stop();
  10596. t.join();
  10597. ASSERT_FALSE(svr.is_running());
  10598. });
  10599. svr.wait_until_ready();
  10600. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10601. cli.enable_server_certificate_verification(false);
  10602. cli.set_connection_timeout(30);
  10603. auto res = cli.Get("/test");
  10604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10605. ASSERT_EQ(StatusCode::OK_200, res->status);
  10606. }
  10607. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10608. class NoListenSSLServer : public SSLServer {
  10609. public:
  10610. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10611. const char *client_ca_cert_file_path,
  10612. const char *client_ca_cert_dir_path = nullptr)
  10613. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10614. client_ca_cert_dir_path),
  10615. stop_(false) {}
  10616. std::atomic_bool stop_;
  10617. private:
  10618. bool process_and_close_socket(socket_t /*sock*/) override {
  10619. // Don't create SSL context
  10620. while (!stop_.load()) {
  10621. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10622. }
  10623. return true;
  10624. }
  10625. };
  10626. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10627. CLIENT_CA_CERT_FILE);
  10628. ASSERT_TRUE(svr.is_valid());
  10629. svr.Get("/test", [&](const Request &, Response &res) {
  10630. res.set_content("test", "text/plain");
  10631. });
  10632. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10633. auto se = detail::scope_exit([&] {
  10634. svr.stop_ = true;
  10635. svr.stop();
  10636. t.join();
  10637. ASSERT_FALSE(svr.is_running());
  10638. });
  10639. svr.wait_until_ready();
  10640. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10641. cli.enable_server_certificate_verification(false);
  10642. cli.set_connection_timeout(1);
  10643. auto res = cli.Get("/test");
  10644. ASSERT_TRUE(!res);
  10645. EXPECT_EQ(Error::SSLConnection, res.error());
  10646. // Timeout results in WantRead error code (maps to backend-specific value)
  10647. EXPECT_NE(0, res.ssl_error());
  10648. }
  10649. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10650. // Test SSLServer with client certificate verification using the standard
  10651. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10652. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10653. CLIENT_CA_CERT_DIR);
  10654. ASSERT_TRUE(svr.is_valid());
  10655. svr.Get("/test", [&](const Request &req, Response &res) {
  10656. res.set_content("test", "text/plain");
  10657. auto cert = req.peer_cert();
  10658. ASSERT_TRUE(static_cast<bool>(cert));
  10659. auto common_name = cert.subject_cn();
  10660. EXPECT_EQ("Common Name", common_name);
  10661. });
  10662. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10663. auto se = detail::scope_exit([&] {
  10664. svr.stop();
  10665. t.join();
  10666. ASSERT_FALSE(svr.is_running());
  10667. });
  10668. svr.wait_until_ready();
  10669. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10670. cli.enable_server_certificate_verification(false);
  10671. cli.set_connection_timeout(30);
  10672. auto res = cli.Get("/test");
  10673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10674. ASSERT_EQ(StatusCode::OK_200, res->status);
  10675. }
  10676. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10677. // Verifies that wildcard matching and exact matching work consistently
  10678. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10679. using namespace httplib::tls;
  10680. // We need a running server to test against
  10681. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10682. ASSERT_TRUE(svr.is_valid());
  10683. svr.Get("/test", [](const Request &, Response &res) {
  10684. res.set_content("ok", "text/plain");
  10685. });
  10686. thread t([&]() { svr.listen(HOST, PORT); });
  10687. auto se = detail::scope_exit([&] {
  10688. svr.stop();
  10689. t.join();
  10690. });
  10691. svr.wait_until_ready();
  10692. bool verify_callback_called = false;
  10693. bool verify_result_wrong = false;
  10694. SSLClient cli(HOST, PORT);
  10695. cli.enable_server_certificate_verification(true);
  10696. cli.set_ca_cert_path(CA_CERT_FILE);
  10697. cli.set_connection_timeout(5);
  10698. // Note: Test certificate has CN="Common Name", not "localhost"
  10699. bool verify_result_cn = false;
  10700. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10701. verify_callback_called = true;
  10702. if (!ctx.cert) return false;
  10703. // Test 1: "Common Name" should match (our test server cert CN)
  10704. verify_result_cn = ctx.check_hostname("Common Name");
  10705. // Test 2: wrong hostname should not match
  10706. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10707. return true; // Accept for the purpose of this test
  10708. });
  10709. auto res = cli.Get("/test");
  10710. // The request may succeed or fail depending on cert configuration
  10711. // but the callback should have been called
  10712. ASSERT_TRUE(verify_callback_called)
  10713. << "Verify callback should have been called";
  10714. // CN="Common Name" should match our test certificate
  10715. //
  10716. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10717. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10718. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10719. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10720. // <openssl/base.h>, which is included transitively when
  10721. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10722. #if defined(OPENSSL_IS_BORINGSSL)
  10723. EXPECT_FALSE(verify_result_cn)
  10724. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10725. #else
  10726. EXPECT_TRUE(verify_result_cn)
  10727. << "verify_hostname should match 'Common Name' (certificate CN)";
  10728. #endif
  10729. // Wrong hostname should not match
  10730. EXPECT_FALSE(verify_result_wrong)
  10731. << "verify_hostname should not match 'wronghost.example.com'";
  10732. }
  10733. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10734. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10735. // X509_check_ip behavior and must hold for every backend.
  10736. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10737. using namespace httplib::tls;
  10738. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10739. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10740. ASSERT_TRUE(svr.is_valid());
  10741. svr.Get("/test", [](const Request &, Response &res) {
  10742. res.set_content("ok", "text/plain");
  10743. });
  10744. thread t([&]() { svr.listen(HOST, PORT); });
  10745. auto se = detail::scope_exit([&] {
  10746. svr.stop();
  10747. t.join();
  10748. });
  10749. svr.wait_until_ready();
  10750. bool verify_callback_called = false;
  10751. bool ip_matched_via_cn = true;
  10752. SSLClient cli(HOST, PORT);
  10753. cli.enable_server_certificate_verification(true);
  10754. cli.set_ca_cert_path(CA_CERT_FILE);
  10755. cli.set_connection_timeout(5);
  10756. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10757. verify_callback_called = true;
  10758. if (!ctx.cert) return false;
  10759. // The IP appears only in the CN, so it must NOT be accepted.
  10760. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10761. return true; // Accept for the purpose of this test
  10762. });
  10763. cli.Get("/test");
  10764. ASSERT_TRUE(verify_callback_called)
  10765. << "Verify callback should have been called";
  10766. EXPECT_FALSE(ip_matched_via_cn)
  10767. << "An IP host must not be authenticated via the certificate CN";
  10768. }
  10769. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10770. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10771. using namespace httplib::tls;
  10772. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10773. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10774. ASSERT_TRUE(svr.is_valid());
  10775. svr.Get("/test", [](const Request &, Response &res) {
  10776. res.set_content("ok", "text/plain");
  10777. });
  10778. thread t([&]() { svr.listen(HOST, PORT); });
  10779. auto se = detail::scope_exit([&] {
  10780. svr.stop();
  10781. t.join();
  10782. });
  10783. svr.wait_until_ready();
  10784. bool verify_callback_called = false;
  10785. bool san_matched = false;
  10786. bool wrong_ipv6_matched = true;
  10787. bool cn_ipv6_matched = true;
  10788. SSLClient cli(HOST, PORT);
  10789. cli.enable_server_certificate_verification(true);
  10790. cli.set_ca_cert_path(CA_CERT_FILE);
  10791. cli.set_connection_timeout(5);
  10792. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10793. verify_callback_called = true;
  10794. if (!ctx.cert) return false;
  10795. // Matches the IPv6 iPAddress SAN.
  10796. san_matched = ctx.check_hostname("2001:db8::1");
  10797. // A different IPv6 address must not match.
  10798. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10799. // "::1" lives only in the CN, so it must not be accepted.
  10800. cn_ipv6_matched = ctx.check_hostname("::1");
  10801. return true; // Accept for the purpose of this test
  10802. });
  10803. cli.Get("/test");
  10804. ASSERT_TRUE(verify_callback_called)
  10805. << "Verify callback should have been called";
  10806. EXPECT_TRUE(san_matched)
  10807. << "verify_hostname should match an IPv6 iPAddress SAN";
  10808. EXPECT_FALSE(wrong_ipv6_matched)
  10809. << "verify_hostname should not match a non-matching IPv6 address";
  10810. EXPECT_FALSE(cn_ipv6_matched)
  10811. << "An IPv6 host must not be authenticated via the certificate CN";
  10812. }
  10813. #endif
  10814. // mbedTLS-specific callback constructor test
  10815. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10816. #ifdef CPPHTTPLIB_SSL_ENABLED
  10817. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10818. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10819. ASSERT_TRUE(svr.is_valid());
  10820. // Set up a handler to verify client certificate is present
  10821. bool client_cert_verified = false;
  10822. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10823. // Verify that client certificate was provided
  10824. client_cert_verified = true;
  10825. res.set_content("success", "text/plain");
  10826. });
  10827. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10828. auto se = detail::scope_exit([&] {
  10829. svr.stop();
  10830. t.join();
  10831. ASSERT_FALSE(svr.is_running());
  10832. });
  10833. svr.wait_until_ready();
  10834. // Client with certificate
  10835. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10836. cli.enable_server_certificate_verification(false);
  10837. cli.set_connection_timeout(30);
  10838. auto res = cli.Get("/test");
  10839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10840. ASSERT_EQ(StatusCode::OK_200, res->status);
  10841. ASSERT_TRUE(client_cert_verified);
  10842. EXPECT_EQ("success", res->body);
  10843. }
  10844. #endif
  10845. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10846. // backends
  10847. #ifdef CPPHTTPLIB_SSL_ENABLED
  10848. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10849. using namespace httplib::tls;
  10850. // Test that when client CA cert file is provided,
  10851. // the server properly requests and validates client certificates
  10852. // Create a server with client authentication
  10853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10854. ASSERT_TRUE(svr.is_valid());
  10855. bool handler_called = false;
  10856. svr.Get("/test", [&](const Request &req, Response &res) {
  10857. handler_called = true;
  10858. // Verify that a client certificate was provided
  10859. auto cert = req.peer_cert();
  10860. ASSERT_TRUE(static_cast<bool>(cert));
  10861. // Get the issuer name
  10862. std::string issuer_str = cert.issuer_name();
  10863. ASSERT_FALSE(issuer_str.empty());
  10864. // The client certificate should be issued by our test CA
  10865. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10866. res.set_content("authenticated", "text/plain");
  10867. });
  10868. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10869. auto se = detail::scope_exit([&] {
  10870. svr.stop();
  10871. t.join();
  10872. ASSERT_FALSE(svr.is_running());
  10873. });
  10874. svr.wait_until_ready();
  10875. // Connect with a client certificate issued by the CA
  10876. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10877. cli.enable_server_certificate_verification(false);
  10878. cli.set_connection_timeout(30);
  10879. auto res = cli.Get("/test");
  10880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10881. ASSERT_EQ(StatusCode::OK_200, res->status);
  10882. ASSERT_TRUE(handler_called);
  10883. EXPECT_EQ("authenticated", res->body);
  10884. }
  10885. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10886. using namespace httplib::tls;
  10887. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10888. ASSERT_TRUE(svr.is_valid());
  10889. svr.Get("/test", [](const Request &, Response &res) {
  10890. res.set_content("ok", "text/plain");
  10891. });
  10892. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10893. auto se = detail::scope_exit([&] {
  10894. svr.stop();
  10895. t.join();
  10896. });
  10897. svr.wait_until_ready();
  10898. SSLClient cli(HOST, PORT);
  10899. cli.enable_server_certificate_verification(false);
  10900. cli.set_connection_timeout(30);
  10901. bool cert_checked = false;
  10902. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10903. if (ctx.cert) {
  10904. auto sans = ctx.sans();
  10905. // Test certificate may or may not have SANs - just verify the API
  10906. // works If SANs exist, verify the types are valid
  10907. for (const auto &san : sans) {
  10908. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10909. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10910. san.type == SanType::OTHER);
  10911. EXPECT_FALSE(san.value.empty());
  10912. }
  10913. cert_checked = true;
  10914. }
  10915. return true;
  10916. });
  10917. auto res = cli.Get("/test");
  10918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10919. EXPECT_TRUE(cert_checked);
  10920. }
  10921. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10922. using namespace httplib::tls;
  10923. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10924. ASSERT_TRUE(svr.is_valid());
  10925. svr.Get("/test", [](const Request &, Response &res) {
  10926. res.set_content("ok", "text/plain");
  10927. });
  10928. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10929. auto se = detail::scope_exit([&] {
  10930. svr.stop();
  10931. t.join();
  10932. });
  10933. svr.wait_until_ready();
  10934. SSLClient cli(HOST, PORT);
  10935. cli.enable_server_certificate_verification(false);
  10936. cli.set_connection_timeout(30);
  10937. bool validity_checked = false;
  10938. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10939. if (ctx.cert) {
  10940. time_t not_before = 0, not_after = 0;
  10941. bool result = ctx.validity(not_before, not_after);
  10942. EXPECT_TRUE(result);
  10943. // Verify that not_before < now < not_after for a valid cert
  10944. time_t now = time(nullptr);
  10945. EXPECT_LT(not_before, now);
  10946. EXPECT_GT(not_after, now);
  10947. validity_checked = true;
  10948. }
  10949. return true;
  10950. });
  10951. auto res = cli.Get("/test");
  10952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10953. EXPECT_TRUE(validity_checked);
  10954. }
  10955. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10956. using namespace httplib::tls;
  10957. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10958. ASSERT_TRUE(svr.is_valid());
  10959. svr.Get("/test", [](const Request &, Response &res) {
  10960. res.set_content("ok", "text/plain");
  10961. });
  10962. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10963. auto se = detail::scope_exit([&] {
  10964. svr.stop();
  10965. t.join();
  10966. });
  10967. svr.wait_until_ready();
  10968. SSLClient cli(HOST, PORT);
  10969. cli.enable_server_certificate_verification(false);
  10970. cli.set_connection_timeout(30);
  10971. bool serial_checked = false;
  10972. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10973. if (ctx.cert) {
  10974. std::string serial = ctx.serial();
  10975. EXPECT_FALSE(serial.empty());
  10976. // Serial should be a hex string
  10977. for (char c : serial) {
  10978. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10979. (c >= 'a' && c <= 'f'));
  10980. }
  10981. serial_checked = true;
  10982. }
  10983. return true;
  10984. });
  10985. auto res = cli.Get("/test");
  10986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10987. EXPECT_TRUE(serial_checked);
  10988. }
  10989. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10990. // Test 1: Valid CA file - no error should be recorded
  10991. {
  10992. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10993. CLIENT_CA_CERT_FILE);
  10994. ASSERT_TRUE(svr.is_valid());
  10995. // With valid setup, last_ssl_error should be 0
  10996. EXPECT_EQ(0, svr.ssl_last_error());
  10997. }
  10998. // Test 2: Invalid CA file content
  10999. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  11000. {
  11001. // Create a temporary file with completely invalid content
  11002. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  11003. {
  11004. std::ofstream ofs(temp_invalid_ca);
  11005. ofs << "This is not a certificate file at all\n";
  11006. ofs << "Just plain text content\n";
  11007. }
  11008. // Create server with invalid CA file
  11009. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  11010. // Clean up temporary file
  11011. std::remove(temp_invalid_ca);
  11012. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  11013. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  11014. // Note: SSL_CTX_load_verify_locations typically fails first,
  11015. // but our error handling code path is still exercised
  11016. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  11017. }
  11018. }
  11019. TEST(VerifyCallbackTest, VerifyContextFields) {
  11020. using namespace httplib::tls;
  11021. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11022. ASSERT_TRUE(svr.is_valid());
  11023. svr.Get("/test", [](const Request &, Response &res) {
  11024. res.set_content("ok", "text/plain");
  11025. });
  11026. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11027. auto se = detail::scope_exit([&] {
  11028. svr.stop();
  11029. t.join();
  11030. });
  11031. svr.wait_until_ready();
  11032. SSLClient cli(HOST, PORT);
  11033. cli.enable_server_certificate_verification(false);
  11034. cli.set_connection_timeout(30);
  11035. int callback_count = 0;
  11036. bool saw_leaf_cert = false;
  11037. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11038. if (ctx.cert) {
  11039. callback_count++;
  11040. // We should see at least one certificate (the leaf)
  11041. std::string cn = ctx.subject_cn();
  11042. if (!cn.empty()) { saw_leaf_cert = true; }
  11043. // Verify context fields are populated
  11044. EXPECT_NE(ctx.session, nullptr);
  11045. EXPECT_GE(ctx.depth, 0);
  11046. }
  11047. return true;
  11048. });
  11049. auto res = cli.Get("/test");
  11050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11051. EXPECT_GT(callback_count, 0);
  11052. EXPECT_TRUE(saw_leaf_cert);
  11053. }
  11054. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  11055. using httplib::tls::TlsError;
  11056. // Test that verify_error_to_string returns empty for success
  11057. std::string success_str = TlsError::verify_error_to_string(0);
  11058. EXPECT_TRUE(success_str.empty());
  11059. // Test that verify_error_to_string returns non-empty for error codes
  11060. // Using a common error code (certificate expired)
  11061. std::string error_str =
  11062. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  11063. EXPECT_FALSE(error_str.empty());
  11064. }
  11065. TEST(SessionVerifierTest, CertificateAccepted) {
  11066. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11067. ASSERT_TRUE(svr.is_valid());
  11068. svr.Get("/test", [](const Request &, Response &res) {
  11069. res.set_content("ok", "text/plain");
  11070. });
  11071. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11072. auto se = detail::scope_exit([&] {
  11073. svr.stop();
  11074. t.join();
  11075. });
  11076. svr.wait_until_ready();
  11077. SSLClient cli(HOST, PORT);
  11078. cli.enable_server_certificate_verification(false);
  11079. cli.set_connection_timeout(30);
  11080. bool callback_called = false;
  11081. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11082. EXPECT_NE(session, nullptr);
  11083. callback_called = true;
  11084. return SSLVerifierResponse::CertificateAccepted;
  11085. });
  11086. auto res = cli.Get("/test");
  11087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11088. EXPECT_EQ(200, res->status);
  11089. EXPECT_TRUE(callback_called);
  11090. }
  11091. TEST(SessionVerifierTest, CertificateRejected) {
  11092. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11093. ASSERT_TRUE(svr.is_valid());
  11094. svr.Get("/test", [](const Request &, Response &res) {
  11095. res.set_content("ok", "text/plain");
  11096. });
  11097. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11098. auto se = detail::scope_exit([&] {
  11099. svr.stop();
  11100. t.join();
  11101. });
  11102. svr.wait_until_ready();
  11103. SSLClient cli(HOST, PORT);
  11104. cli.enable_server_certificate_verification(false);
  11105. cli.set_connection_timeout(30);
  11106. bool callback_called = false;
  11107. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11108. EXPECT_NE(session, nullptr);
  11109. callback_called = true;
  11110. return SSLVerifierResponse::CertificateRejected;
  11111. });
  11112. auto res = cli.Get("/test");
  11113. EXPECT_FALSE(res);
  11114. EXPECT_TRUE(callback_called);
  11115. }
  11116. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  11117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11118. ASSERT_TRUE(svr.is_valid());
  11119. svr.Get("/test", [](const Request &, Response &res) {
  11120. res.set_content("ok", "text/plain");
  11121. });
  11122. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11123. auto se = detail::scope_exit([&] {
  11124. svr.stop();
  11125. t.join();
  11126. });
  11127. svr.wait_until_ready();
  11128. // NoDecisionMade with verification disabled should succeed (no default check)
  11129. SSLClient cli(HOST, PORT);
  11130. cli.enable_server_certificate_verification(false);
  11131. cli.set_connection_timeout(30);
  11132. bool callback_called = false;
  11133. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11134. EXPECT_NE(session, nullptr);
  11135. callback_called = true;
  11136. return SSLVerifierResponse::NoDecisionMade;
  11137. });
  11138. auto res = cli.Get("/test");
  11139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11140. EXPECT_EQ(200, res->status);
  11141. EXPECT_TRUE(callback_called);
  11142. }
  11143. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  11144. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11145. ASSERT_TRUE(svr.is_valid());
  11146. svr.Get("/test", [](const Request &, Response &res) {
  11147. res.set_content("ok", "text/plain");
  11148. });
  11149. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11150. auto se = detail::scope_exit([&] {
  11151. svr.stop();
  11152. t.join();
  11153. });
  11154. svr.wait_until_ready();
  11155. // NoDecisionMade with verification enabled should fail (self-signed cert).
  11156. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  11157. // so we only check that the request fails, not whether the callback was
  11158. // called.
  11159. SSLClient cli(HOST, PORT);
  11160. cli.enable_server_certificate_verification(true);
  11161. cli.set_connection_timeout(30);
  11162. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11163. EXPECT_NE(session, nullptr);
  11164. return SSLVerifierResponse::NoDecisionMade;
  11165. });
  11166. auto res = cli.Get("/test");
  11167. EXPECT_FALSE(res);
  11168. }
  11169. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11170. // Test SSL server using PemMemory constructor with client CA certificates
  11171. // Read PEM files
  11172. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11173. read_file(SERVER_CERT_FILE, server_cert_pem);
  11174. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11175. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11176. // Create SSLServer with PemMemory constructor including client CA
  11177. SSLServer::PemMemory server_pem = {
  11178. server_cert_pem.c_str(),
  11179. server_cert_pem.size(),
  11180. server_key_pem.c_str(),
  11181. server_key_pem.size(),
  11182. client_ca_pem.c_str(),
  11183. client_ca_pem.size(),
  11184. nullptr // no password for server key
  11185. };
  11186. SSLServer svr(server_pem);
  11187. ASSERT_TRUE(svr.is_valid());
  11188. // No SSL error should be recorded for valid setup
  11189. EXPECT_EQ(0, svr.ssl_last_error());
  11190. // Set up server endpoints
  11191. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11192. res.set_content("ok", "text/plain");
  11193. });
  11194. // Start server in a thread
  11195. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11196. svr.wait_until_ready();
  11197. // Connect with client certificate (using constructor with paths)
  11198. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11199. cli.enable_server_certificate_verification(false);
  11200. auto res = cli.Get("/test-pem-ca");
  11201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11202. EXPECT_EQ(200, res->status);
  11203. EXPECT_EQ("ok", res->body);
  11204. svr.stop();
  11205. server_thread.join();
  11206. }
  11207. #endif
  11208. #ifdef _WIN32
  11209. TEST(CleanupTest, WSACleanup) {
  11210. int ret = WSACleanup();
  11211. ASSERT_EQ(0, ret);
  11212. }
  11213. #endif
  11214. #ifndef CPPHTTPLIB_SSL_ENABLED
  11215. TEST(NoSSLSupport, SimpleInterface) {
  11216. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11217. }
  11218. #endif
  11219. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11220. TEST(InvalidScheme, SimpleInterface) {
  11221. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11222. }
  11223. #endif
  11224. TEST(NoScheme, SimpleInterface) {
  11225. Client cli("yahoo.com:80");
  11226. ASSERT_TRUE(cli.is_valid());
  11227. }
  11228. TEST(SendAPI, SimpleInterface_Online) {
  11229. Client cli("http://yahoo.com");
  11230. Request req;
  11231. req.method = "GET";
  11232. req.path = "/";
  11233. auto res = cli.send(req);
  11234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11235. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11236. }
  11237. TEST(SendAPI, WithParamsInRequest) {
  11238. Server svr;
  11239. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11240. EXPECT_TRUE(req.has_param("test"));
  11241. EXPECT_EQ("test_value", req.get_param_value("test"));
  11242. });
  11243. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11244. auto se = detail::scope_exit([&] {
  11245. svr.stop();
  11246. t.join();
  11247. ASSERT_FALSE(svr.is_running());
  11248. });
  11249. svr.wait_until_ready();
  11250. Client cli(HOST, PORT);
  11251. {
  11252. Request req;
  11253. req.method = "GET";
  11254. req.path = "/";
  11255. req.params.emplace("test", "test_value");
  11256. auto res = cli.send(req);
  11257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11258. }
  11259. {
  11260. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11262. }
  11263. }
  11264. TEST(ClientImplMethods, GetSocketTest) {
  11265. httplib::Server svr;
  11266. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11267. res.status = StatusCode::OK_200;
  11268. });
  11269. auto port = svr.bind_to_any_port("127.0.0.1");
  11270. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11271. auto se = detail::scope_exit([&] {
  11272. svr.stop();
  11273. thread.join();
  11274. ASSERT_FALSE(svr.is_running());
  11275. });
  11276. svr.wait_until_ready();
  11277. {
  11278. httplib::Client cli("127.0.0.1", port);
  11279. cli.set_keep_alive(true);
  11280. // Use the behavior of cpp-httplib of opening the connection
  11281. // only when the first request happens. If that changes,
  11282. // this test would be obsolete.
  11283. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11284. // This also implicitly tests the server. But other tests would fail much
  11285. // earlier than this one to be considered.
  11286. auto res = cli.Get("/");
  11287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11288. EXPECT_EQ(StatusCode::OK_200, res->status);
  11289. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11290. }
  11291. }
  11292. #ifdef CPPHTTPLIB_SSL_ENABLED
  11293. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11294. Client cli("http://yahoo.com");
  11295. auto res = cli.Get("/");
  11296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11297. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11298. cli.set_follow_location(true);
  11299. res = cli.Get("/");
  11300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11301. EXPECT_EQ(StatusCode::OK_200, res->status);
  11302. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11303. }
  11304. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11305. Client cli("https://yahoo.com");
  11306. auto res = cli.Get("/");
  11307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  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(StatusCode::OK_200, res->status);
  11313. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11314. }
  11315. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11316. Client cli("https://yahoo.com");
  11317. auto res = cli.Get("/");
  11318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11319. ASSERT_FALSE(!res);
  11320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11321. ASSERT_FALSE(res == nullptr);
  11322. ASSERT_TRUE(res != nullptr);
  11323. EXPECT_EQ(Error::Success, res.error());
  11324. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11325. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11326. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11327. cli.set_follow_location(true);
  11328. res = cli.Get("/");
  11329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11330. EXPECT_EQ(Error::Success, res.error());
  11331. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11332. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11333. EXPECT_EQ(StatusCode::OK_200, res->status);
  11334. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11335. }
  11336. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11337. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11338. Client cli("https://cdnjs.cloudflare.com");
  11339. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11340. Headers{{"Accept-Encoding", "br"}});
  11341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11342. EXPECT_EQ(StatusCode::OK_200, res->status);
  11343. EXPECT_EQ(287630U, res->body.size());
  11344. EXPECT_EQ("application/javascript; charset=utf-8",
  11345. res->get_header_value("Content-Type"));
  11346. }
  11347. #endif
  11348. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11349. #undef REDIR_HOST // Silence compiler warning
  11350. #define REDIR_HOST "https://httpbingo.org"
  11351. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11352. Client cli(REDIR_HOST);
  11353. cli.set_follow_location(true);
  11354. auto res =
  11355. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11357. EXPECT_EQ(StatusCode::OK_200, res->status);
  11358. }
  11359. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11360. Client cli(REDIR_HOST);
  11361. cli.set_follow_location(true);
  11362. Params params;
  11363. params.emplace("url", "http://example.com");
  11364. params.emplace("status_code", "302");
  11365. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11367. EXPECT_EQ(StatusCode::OK_200, res->status);
  11368. }
  11369. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11370. Client cli(REDIR_HOST);
  11371. cli.set_follow_location(true);
  11372. Params params;
  11373. params.emplace("url", "http://example.com");
  11374. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11376. EXPECT_EQ(StatusCode::OK_200, res->status);
  11377. }
  11378. TEST(HttpToHttpsRedirectTest, CertFile) {
  11379. auto ssl_port = PORT + 1;
  11380. Server svr;
  11381. ASSERT_TRUE(svr.is_valid());
  11382. svr.Get("/index", [&](const Request &, Response &res) {
  11383. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11384. "/index");
  11385. svr.stop();
  11386. });
  11387. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11388. ASSERT_TRUE(ssl_svr.is_valid());
  11389. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11390. res.set_content("test", "text/plain");
  11391. ssl_svr.stop();
  11392. });
  11393. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11394. thread t2 =
  11395. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11396. auto se = detail::scope_exit([&] {
  11397. t2.join();
  11398. t.join();
  11399. ASSERT_FALSE(svr.is_running());
  11400. });
  11401. svr.wait_until_ready();
  11402. ssl_svr.wait_until_ready();
  11403. Client cli("127.0.0.1", PORT);
  11404. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11405. cli.enable_server_certificate_verification(true);
  11406. cli.set_follow_location(true);
  11407. cli.set_connection_timeout(30);
  11408. auto res = cli.Get("/index");
  11409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11410. ASSERT_EQ(StatusCode::OK_200, res->status);
  11411. }
  11412. TEST(SSLClientRedirectTest, CertFile) {
  11413. auto ssl_port = PORT + 1;
  11414. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11415. ASSERT_TRUE(ssl_svr1.is_valid());
  11416. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11417. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11418. "/index");
  11419. ssl_svr1.stop();
  11420. });
  11421. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11422. ASSERT_TRUE(ssl_svr2.is_valid());
  11423. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11424. res.set_content("test", "text/plain");
  11425. ssl_svr2.stop();
  11426. });
  11427. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11428. thread t2 =
  11429. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11430. auto se = detail::scope_exit([&] {
  11431. t2.join();
  11432. t.join();
  11433. ASSERT_FALSE(ssl_svr1.is_running());
  11434. });
  11435. ssl_svr1.wait_until_ready();
  11436. ssl_svr2.wait_until_ready();
  11437. SSLClient cli("127.0.0.1", PORT);
  11438. std::string cert;
  11439. read_file(SERVER_CERT2_FILE, cert);
  11440. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11441. cli.enable_server_certificate_verification(true);
  11442. cli.set_follow_location(true);
  11443. cli.set_connection_timeout(30);
  11444. auto res = cli.Get("/index");
  11445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11446. ASSERT_EQ(StatusCode::OK_200, res->status);
  11447. }
  11448. #endif
  11449. #ifdef CPPHTTPLIB_SSL_ENABLED
  11450. // Test that set_ca_cert_store() skips system certs (consistent with
  11451. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11452. // should be trusted - system certs should NOT be loaded.
  11453. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11454. // Load a specific cert that is NOT a system CA cert
  11455. std::string cert;
  11456. read_file(SERVER_CERT2_FILE, cert);
  11457. SSLClient cli("google.com");
  11458. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11459. cli.enable_server_certificate_verification(true);
  11460. // This should FAIL because:
  11461. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11462. // 2. System certs should NOT be loaded when custom store is set
  11463. // If system certs WERE loaded, this would succeed
  11464. auto res = cli.Get("/");
  11465. ASSERT_FALSE(res);
  11466. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11467. }
  11468. // Same as above, but through the native store handle path. Regression test:
  11469. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11470. // merged system certs into the user-provided store.
  11471. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11472. std::string cert;
  11473. read_file(SERVER_CERT2_FILE, cert);
  11474. SSLClient cli("google.com");
  11475. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11476. cli.enable_server_certificate_verification(true);
  11477. auto res = cli.Get("/");
  11478. ASSERT_FALSE(res);
  11479. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11480. }
  11481. // A custom store set via the native handle must still verify a server whose
  11482. // cert it does contain.
  11483. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11484. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11485. ASSERT_TRUE(svr.is_valid());
  11486. svr.Get("/test", [&](const Request &, Response &res) {
  11487. res.set_content("test", "text/plain");
  11488. });
  11489. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11490. auto se = detail::scope_exit([&] {
  11491. svr.stop();
  11492. t.join();
  11493. ASSERT_FALSE(svr.is_running());
  11494. });
  11495. svr.wait_until_ready();
  11496. SSLClient cli("127.0.0.1", PORT);
  11497. std::string cert;
  11498. read_file(SERVER_CERT2_FILE, cert);
  11499. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11500. cli.enable_server_certificate_verification(true);
  11501. cli.set_connection_timeout(30);
  11502. auto res = cli.Get("/test");
  11503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11504. ASSERT_EQ(StatusCode::OK_200, res->status);
  11505. }
  11506. // CA certs loaded through the universal Client must be transferred to the
  11507. // client created internally for following an HTTPS redirect. Regression test:
  11508. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11509. // the CA data for redirect transfer.
  11510. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11511. auto ssl_port = PORT + 1;
  11512. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11513. ASSERT_TRUE(ssl_svr1.is_valid());
  11514. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11515. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11516. "/index");
  11517. });
  11518. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11519. ASSERT_TRUE(ssl_svr2.is_valid());
  11520. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11521. res.set_content("test", "text/plain");
  11522. });
  11523. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11524. thread t2 =
  11525. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11526. auto se = detail::scope_exit([&] {
  11527. ssl_svr2.stop();
  11528. ssl_svr1.stop();
  11529. t2.join();
  11530. t.join();
  11531. ASSERT_FALSE(ssl_svr1.is_running());
  11532. });
  11533. ssl_svr1.wait_until_ready();
  11534. ssl_svr2.wait_until_ready();
  11535. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11536. std::string cert;
  11537. read_file(SERVER_CERT2_FILE, cert);
  11538. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11539. cli.enable_server_certificate_verification(true);
  11540. cli.set_follow_location(true);
  11541. cli.set_connection_timeout(30);
  11542. auto res = cli.Get("/index");
  11543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11544. ASSERT_EQ(StatusCode::OK_200, res->status);
  11545. }
  11546. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11547. // so a host signed by a system CA verifies even though a custom CA is set
  11548. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11549. std::string cert;
  11550. read_file(SERVER_CERT2_FILE, cert);
  11551. SSLClient cli("google.com");
  11552. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11553. cli.enable_system_ca(true);
  11554. cli.enable_server_certificate_verification(true);
  11555. auto res = cli.Get("/");
  11556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11557. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11558. }
  11559. // The custom CA remains effective when combined with the system CA
  11560. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11561. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11562. ASSERT_TRUE(svr.is_valid());
  11563. svr.Get("/test", [&](const Request &, Response &res) {
  11564. res.set_content("test", "text/plain");
  11565. });
  11566. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11567. auto se = detail::scope_exit([&] {
  11568. svr.stop();
  11569. t.join();
  11570. ASSERT_FALSE(svr.is_running());
  11571. });
  11572. svr.wait_until_ready();
  11573. SSLClient cli("127.0.0.1", PORT);
  11574. std::string cert;
  11575. read_file(SERVER_CERT2_FILE, cert);
  11576. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11577. cli.enable_system_ca(true);
  11578. cli.enable_server_certificate_verification(true);
  11579. cli.set_connection_timeout(30);
  11580. auto res = cli.Get("/test");
  11581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11582. ASSERT_EQ(StatusCode::OK_200, res->status);
  11583. }
  11584. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11585. // skip chain verification entirely (only the certificate identity was
  11586. // checked), so a server presenting an untrusted certificate with a matching
  11587. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11588. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11589. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11590. ASSERT_TRUE(svr.is_valid());
  11591. svr.Get("/test", [&](const Request &, Response &res) {
  11592. res.set_content("test", "text/plain");
  11593. });
  11594. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11595. auto se = detail::scope_exit([&] {
  11596. svr.stop();
  11597. t.join();
  11598. ASSERT_FALSE(svr.is_running());
  11599. });
  11600. svr.wait_until_ready();
  11601. SSLClient cli("127.0.0.1", PORT);
  11602. std::string cert;
  11603. // A trusted CA that did not sign the server certificate. The server cert
  11604. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11605. // this connection.
  11606. read_file(CLIENT_CA_CERT_FILE, cert);
  11607. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11608. cli.enable_server_certificate_verification(true);
  11609. cli.set_connection_timeout(30);
  11610. auto res = cli.Get("/test");
  11611. ASSERT_FALSE(res);
  11612. }
  11613. // enable_system_ca(false) prevents system CA loading entirely
  11614. TEST(SSLClientTest, DisableSystemCa_Online) {
  11615. SSLClient cli("google.com");
  11616. cli.enable_system_ca(false);
  11617. cli.enable_server_certificate_verification(true);
  11618. auto res = cli.Get("/");
  11619. ASSERT_FALSE(res);
  11620. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11621. // itself when the CA chain is empty
  11622. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11623. res.error() == Error::SSLConnection);
  11624. }
  11625. // The universal Client forwards enable_system_ca()
  11626. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11627. std::string cert;
  11628. read_file(SERVER_CERT2_FILE, cert);
  11629. Client cli("https://google.com");
  11630. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11631. cli.enable_system_ca(true);
  11632. cli.enable_server_certificate_verification(true);
  11633. auto res = cli.Get("/");
  11634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11635. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11636. }
  11637. // The system CA policy must carry over to the client created internally for
  11638. // following a cross-host HTTPS redirect
  11639. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11640. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11641. ASSERT_TRUE(svr.is_valid());
  11642. svr.Get("/index", [&](const Request &, Response &res) {
  11643. res.set_redirect("https://www.google.com/");
  11644. });
  11645. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11646. auto se = detail::scope_exit([&] {
  11647. svr.stop();
  11648. t.join();
  11649. ASSERT_FALSE(svr.is_running());
  11650. });
  11651. svr.wait_until_ready();
  11652. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11653. std::string cert;
  11654. read_file(SERVER_CERT2_FILE, cert);
  11655. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11656. cli.enable_system_ca(true);
  11657. cli.enable_server_certificate_verification(true);
  11658. cli.set_follow_location(true);
  11659. cli.set_connection_timeout(30);
  11660. // Receiving any response proves the redirect client completed the TLS
  11661. // handshake with a system-CA-signed host
  11662. auto res = cli.Get("/index");
  11663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11664. }
  11665. TEST(MultipartFormDataTest, LargeData) {
  11666. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11667. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11668. const ContentReader &content_reader) {
  11669. if (req.is_multipart_form_data()) {
  11670. std::vector<FormData> items;
  11671. content_reader(
  11672. [&](const FormData &file) {
  11673. items.push_back(file);
  11674. return true;
  11675. },
  11676. [&](const char *data, size_t data_length) {
  11677. items.back().content.append(data, data_length);
  11678. return true;
  11679. });
  11680. EXPECT_TRUE(std::string(items[0].name) == "document");
  11681. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11682. EXPECT_TRUE(items[0].filename == "2MB_data");
  11683. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11684. EXPECT_TRUE(items[1].name == "hello");
  11685. EXPECT_TRUE(items[1].content == "world");
  11686. EXPECT_TRUE(items[1].filename == "");
  11687. EXPECT_TRUE(items[1].content_type == "");
  11688. } else {
  11689. std::string body;
  11690. content_reader([&](const char *data, size_t data_length) {
  11691. body.append(data, data_length);
  11692. return true;
  11693. });
  11694. }
  11695. });
  11696. auto port = svr.bind_to_any_port(HOST);
  11697. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11698. auto se = detail::scope_exit([&] {
  11699. svr.stop();
  11700. t.join();
  11701. ASSERT_FALSE(svr.is_running());
  11702. });
  11703. svr.wait_until_ready();
  11704. {
  11705. std::string data(1024 * 1024 * 2, '.');
  11706. std::stringstream buffer;
  11707. buffer << data;
  11708. SSLClient cli(HOST, port);
  11709. cli.enable_server_certificate_verification(false);
  11710. UploadFormDataItems items{
  11711. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11712. {"hello", "world", "", ""},
  11713. };
  11714. auto res = cli.Post("/post", items);
  11715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11716. ASSERT_EQ(StatusCode::OK_200, res->status);
  11717. }
  11718. }
  11719. TEST(MultipartFormDataTest, DataProviderItems) {
  11720. std::random_device seed_gen;
  11721. std::mt19937 random(seed_gen());
  11722. std::string rand1;
  11723. rand1.resize(1000);
  11724. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11725. std::string rand2;
  11726. rand2.resize(3000);
  11727. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11728. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11729. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11730. const ContentReader &content_reader) {
  11731. ASSERT_FALSE(req.is_multipart_form_data());
  11732. std::string body;
  11733. content_reader([&](const char *data, size_t data_length) {
  11734. body.append(data, data_length);
  11735. return true;
  11736. });
  11737. EXPECT_EQ(body, "");
  11738. });
  11739. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11740. const ContentReader &content_reader) {
  11741. ASSERT_TRUE(req.is_multipart_form_data());
  11742. std::vector<FormData> items;
  11743. content_reader(
  11744. [&](const FormData &file) {
  11745. items.push_back(file);
  11746. return true;
  11747. },
  11748. [&](const char *data, size_t data_length) {
  11749. items.back().content.append(data, data_length);
  11750. return true;
  11751. });
  11752. ASSERT_TRUE(items.size() == 2);
  11753. EXPECT_EQ(std::string(items[0].name), "name1");
  11754. EXPECT_EQ(items[0].content, "Testing123");
  11755. EXPECT_EQ(items[0].filename, "filename1");
  11756. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11757. EXPECT_EQ(items[1].name, "name2");
  11758. EXPECT_EQ(items[1].content, "Testing456");
  11759. EXPECT_EQ(items[1].filename, "");
  11760. EXPECT_EQ(items[1].content_type, "");
  11761. });
  11762. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11763. const ContentReader &content_reader) {
  11764. ASSERT_TRUE(req.is_multipart_form_data());
  11765. std::vector<FormData> items;
  11766. content_reader(
  11767. [&](const FormData &file) {
  11768. items.push_back(file);
  11769. return true;
  11770. },
  11771. [&](const char *data, size_t data_length) {
  11772. items.back().content.append(data, data_length);
  11773. return true;
  11774. });
  11775. ASSERT_TRUE(items.size() == 2);
  11776. EXPECT_EQ(items[0].name, "name3");
  11777. EXPECT_EQ(items[0].content, rand1);
  11778. EXPECT_EQ(items[0].filename, "filename3");
  11779. EXPECT_EQ(items[0].content_type, "");
  11780. EXPECT_EQ(items[1].name, "name4");
  11781. EXPECT_EQ(items[1].content, rand2);
  11782. EXPECT_EQ(items[1].filename, "filename4");
  11783. EXPECT_EQ(items[1].content_type, "");
  11784. });
  11785. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11786. const ContentReader &content_reader) {
  11787. ASSERT_TRUE(req.is_multipart_form_data());
  11788. std::vector<FormData> items;
  11789. content_reader(
  11790. [&](const FormData &file) {
  11791. items.push_back(file);
  11792. return true;
  11793. },
  11794. [&](const char *data, size_t data_length) {
  11795. items.back().content.append(data, data_length);
  11796. return true;
  11797. });
  11798. ASSERT_TRUE(items.size() == 4);
  11799. EXPECT_EQ(std::string(items[0].name), "name1");
  11800. EXPECT_EQ(items[0].content, "Testing123");
  11801. EXPECT_EQ(items[0].filename, "filename1");
  11802. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11803. EXPECT_EQ(items[1].name, "name2");
  11804. EXPECT_EQ(items[1].content, "Testing456");
  11805. EXPECT_EQ(items[1].filename, "");
  11806. EXPECT_EQ(items[1].content_type, "");
  11807. EXPECT_EQ(items[2].name, "name3");
  11808. EXPECT_EQ(items[2].content, rand1);
  11809. EXPECT_EQ(items[2].filename, "filename3");
  11810. EXPECT_EQ(items[2].content_type, "");
  11811. EXPECT_EQ(items[3].name, "name4");
  11812. EXPECT_EQ(items[3].content, rand2);
  11813. EXPECT_EQ(items[3].filename, "filename4");
  11814. EXPECT_EQ(items[3].content_type, "");
  11815. });
  11816. auto port = svr.bind_to_any_port("localhost");
  11817. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11818. auto se = detail::scope_exit([&] {
  11819. svr.stop();
  11820. t.join();
  11821. ASSERT_FALSE(svr.is_running());
  11822. });
  11823. svr.wait_until_ready();
  11824. {
  11825. SSLClient cli("localhost", port);
  11826. cli.enable_server_certificate_verification(false);
  11827. UploadFormDataItems items{
  11828. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11829. {"name2", "Testing456", "", ""}, // not a file
  11830. };
  11831. {
  11832. auto res = cli.Post("/post-none", {}, {}, {});
  11833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11834. ASSERT_EQ(StatusCode::OK_200, res->status);
  11835. }
  11836. FormDataProviderItems providers;
  11837. {
  11838. auto res =
  11839. cli.Post("/post-items", {}, items, providers); // empty providers
  11840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11841. ASSERT_EQ(StatusCode::OK_200, res->status);
  11842. }
  11843. providers.push_back({"name3",
  11844. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11845. // test the offset is given correctly at each step
  11846. if (!offset)
  11847. sink.os.write(rand1.data(), 30);
  11848. else if (offset == 30)
  11849. sink.os.write(rand1.data() + 30, 300);
  11850. else if (offset == 330)
  11851. sink.os.write(rand1.data() + 330, 670);
  11852. else if (offset == rand1.size())
  11853. sink.done();
  11854. return true;
  11855. },
  11856. "filename3",
  11857. {}});
  11858. providers.push_back({"name4",
  11859. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11860. // test the offset is given correctly at each step
  11861. if (!offset)
  11862. sink.os.write(rand2.data(), 2000);
  11863. else if (offset == 2000)
  11864. sink.os.write(rand2.data() + 2000, 1);
  11865. else if (offset == 2001)
  11866. sink.os.write(rand2.data() + 2001, 999);
  11867. else if (offset == rand2.size())
  11868. sink.done();
  11869. return true;
  11870. },
  11871. "filename4",
  11872. {}});
  11873. {
  11874. auto res = cli.Post("/post-providers", {}, {}, providers);
  11875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11876. ASSERT_EQ(StatusCode::OK_200, res->status);
  11877. }
  11878. {
  11879. auto res = cli.Post("/post-both", {}, items, providers);
  11880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11881. ASSERT_EQ(StatusCode::OK_200, res->status);
  11882. }
  11883. }
  11884. }
  11885. TEST(MultipartFormDataTest, BadHeader) {
  11886. Server svr;
  11887. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11888. res.set_content("ok", "text/plain");
  11889. });
  11890. thread t = thread([&] { svr.listen(HOST, PORT); });
  11891. auto se = detail::scope_exit([&] {
  11892. svr.stop();
  11893. t.join();
  11894. ASSERT_FALSE(svr.is_running());
  11895. });
  11896. svr.wait_until_ready();
  11897. const std::string body =
  11898. "This is the preamble. It is to be ignored, though it\r\n"
  11899. "is a handy place for composition agents to include an\r\n"
  11900. "explanatory note to non-MIME conformant readers.\r\n"
  11901. "\r\n"
  11902. "\r\n"
  11903. "--simple boundary\r\n"
  11904. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11905. ": BAD...\r\n"
  11906. "\r\n"
  11907. "value1\r\n"
  11908. "--simple boundary\r\n"
  11909. "Content-Disposition: form-data; name=\"field2\"; "
  11910. "filename=\"example.txt\"\r\n"
  11911. "\r\n"
  11912. "value2\r\n"
  11913. "--simple boundary--\r\n"
  11914. "This is the epilogue. It is also to be ignored.\r\n";
  11915. std::string content_type =
  11916. R"(multipart/form-data; boundary="simple boundary")";
  11917. Client cli(HOST, PORT);
  11918. auto res = cli.Post("/post", body, content_type.c_str());
  11919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11920. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11921. }
  11922. TEST(MultipartFormDataTest, WithPreamble) {
  11923. Server svr;
  11924. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11925. res.set_content("ok", "text/plain");
  11926. });
  11927. thread t = thread([&] { svr.listen(HOST, PORT); });
  11928. auto se = detail::scope_exit([&] {
  11929. svr.stop();
  11930. t.join();
  11931. ASSERT_FALSE(svr.is_running());
  11932. });
  11933. svr.wait_until_ready();
  11934. const std::string body =
  11935. "This is the preamble. It is to be ignored, though it\r\n"
  11936. "is a handy place for composition agents to include an\r\n"
  11937. "explanatory note to non-MIME conformant readers.\r\n"
  11938. "\r\n"
  11939. "\r\n"
  11940. "--simple boundary\r\n"
  11941. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11942. "\r\n"
  11943. "value1\r\n"
  11944. "--simple boundary\r\n"
  11945. "Content-Disposition: form-data; name=\"field2\"; "
  11946. "filename=\"example.txt\"\r\n"
  11947. "\r\n"
  11948. "value2\r\n"
  11949. "--simple boundary--\r\n"
  11950. "This is the epilogue. It is also to be ignored.\r\n";
  11951. std::string content_type =
  11952. R"(multipart/form-data; boundary="simple boundary")";
  11953. Client cli(HOST, PORT);
  11954. auto res = cli.Post("/post", body, content_type.c_str());
  11955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11956. EXPECT_EQ(StatusCode::OK_200, res->status);
  11957. }
  11958. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11959. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11960. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11961. const ContentReader &content_reader) {
  11962. if (req.is_multipart_form_data()) {
  11963. std::vector<FormData> items;
  11964. content_reader(
  11965. [&](const FormData &file) {
  11966. items.push_back(file);
  11967. return true;
  11968. },
  11969. [&](const char *data, size_t data_length) {
  11970. items.back().content.append(data, data_length);
  11971. return true;
  11972. });
  11973. EXPECT_TRUE(std::string(items[0].name) == "document");
  11974. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11975. EXPECT_TRUE(items[0].filename == "2MB_data");
  11976. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11977. EXPECT_TRUE(items[1].name == "hello");
  11978. EXPECT_TRUE(items[1].content == "world");
  11979. EXPECT_TRUE(items[1].filename == "");
  11980. EXPECT_TRUE(items[1].content_type == "");
  11981. } else {
  11982. std::string body;
  11983. content_reader([&](const char *data, size_t data_length) {
  11984. body.append(data, data_length);
  11985. return true;
  11986. });
  11987. }
  11988. });
  11989. auto port = svr.bind_to_any_port("localhost");
  11990. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11991. auto se = detail::scope_exit([&] {
  11992. svr.stop();
  11993. t.join();
  11994. ASSERT_FALSE(svr.is_running());
  11995. });
  11996. svr.wait_until_ready();
  11997. {
  11998. std::string data(1024 * 1024 * 2, '.');
  11999. std::stringstream buffer;
  12000. buffer << data;
  12001. SSLClient cli("localhost", port);
  12002. cli.enable_server_certificate_verification(false);
  12003. UploadFormDataItems items{
  12004. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12005. {"hello", "world", "", ""},
  12006. };
  12007. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  12008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12009. ASSERT_EQ(StatusCode::OK_200, res->status);
  12010. }
  12011. }
  12012. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  12013. std::string data(1024 * 1024 * 2, '&');
  12014. std::stringstream buffer;
  12015. buffer << data;
  12016. Client cli("https://localhost:8080");
  12017. UploadFormDataItems items{
  12018. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12019. {"hello", "world", "", ""},
  12020. };
  12021. for (const char &c : " \t\r\n") {
  12022. auto res =
  12023. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  12024. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12025. ASSERT_FALSE(res);
  12026. }
  12027. }
  12028. TEST(MultipartFormDataTest, PutFormData) {
  12029. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12030. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  12031. const ContentReader &content_reader) {
  12032. if (req.is_multipart_form_data()) {
  12033. std::vector<FormData> items;
  12034. content_reader(
  12035. [&](const FormData &file) {
  12036. items.push_back(file);
  12037. return true;
  12038. },
  12039. [&](const char *data, size_t data_length) {
  12040. items.back().content.append(data, data_length);
  12041. return true;
  12042. });
  12043. EXPECT_TRUE(std::string(items[0].name) == "document");
  12044. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12045. EXPECT_TRUE(items[0].filename == "2MB_data");
  12046. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12047. EXPECT_TRUE(items[1].name == "hello");
  12048. EXPECT_TRUE(items[1].content == "world");
  12049. EXPECT_TRUE(items[1].filename == "");
  12050. EXPECT_TRUE(items[1].content_type == "");
  12051. } else {
  12052. std::string body;
  12053. content_reader([&](const char *data, size_t data_length) {
  12054. body.append(data, data_length);
  12055. return true;
  12056. });
  12057. }
  12058. });
  12059. auto port = svr.bind_to_any_port("localhost");
  12060. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12061. auto se = detail::scope_exit([&] {
  12062. svr.stop();
  12063. t.join();
  12064. ASSERT_FALSE(svr.is_running());
  12065. });
  12066. svr.wait_until_ready();
  12067. {
  12068. std::string data(1024 * 1024 * 2, '&');
  12069. std::stringstream buffer;
  12070. buffer << data;
  12071. SSLClient cli("localhost", port);
  12072. cli.enable_server_certificate_verification(false);
  12073. UploadFormDataItems items{
  12074. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12075. {"hello", "world", "", ""},
  12076. };
  12077. auto res = cli.Put("/put", items);
  12078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12079. ASSERT_EQ(StatusCode::OK_200, res->status);
  12080. }
  12081. }
  12082. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  12083. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12084. svr.Put("/put_customboundary",
  12085. [&](const Request &req, const Response & /*res*/,
  12086. const ContentReader &content_reader) {
  12087. if (req.is_multipart_form_data()) {
  12088. std::vector<FormData> items;
  12089. content_reader(
  12090. [&](const FormData &file) {
  12091. items.push_back(file);
  12092. return true;
  12093. },
  12094. [&](const char *data, size_t data_length) {
  12095. items.back().content.append(data, data_length);
  12096. return true;
  12097. });
  12098. EXPECT_TRUE(std::string(items[0].name) == "document");
  12099. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12100. EXPECT_TRUE(items[0].filename == "2MB_data");
  12101. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12102. EXPECT_TRUE(items[1].name == "hello");
  12103. EXPECT_TRUE(items[1].content == "world");
  12104. EXPECT_TRUE(items[1].filename == "");
  12105. EXPECT_TRUE(items[1].content_type == "");
  12106. } else {
  12107. std::string body;
  12108. content_reader([&](const char *data, size_t data_length) {
  12109. body.append(data, data_length);
  12110. return true;
  12111. });
  12112. }
  12113. });
  12114. auto port = svr.bind_to_any_port("localhost");
  12115. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12116. auto se = detail::scope_exit([&] {
  12117. svr.stop();
  12118. t.join();
  12119. ASSERT_FALSE(svr.is_running());
  12120. });
  12121. svr.wait_until_ready();
  12122. {
  12123. std::string data(1024 * 1024 * 2, '&');
  12124. std::stringstream buffer;
  12125. buffer << data;
  12126. SSLClient cli("localhost", port);
  12127. cli.enable_server_certificate_verification(false);
  12128. UploadFormDataItems items{
  12129. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12130. {"hello", "world", "", ""},
  12131. };
  12132. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  12133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12134. ASSERT_EQ(StatusCode::OK_200, res->status);
  12135. }
  12136. }
  12137. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  12138. std::string data(1024 * 1024 * 2, '&');
  12139. std::stringstream buffer;
  12140. buffer << data;
  12141. Client cli("https://localhost:8080");
  12142. cli.enable_server_certificate_verification(false);
  12143. UploadFormDataItems items{
  12144. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12145. {"hello", "world", "", ""},
  12146. };
  12147. for (const char &c : " \t\r\n") {
  12148. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  12149. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12150. ASSERT_FALSE(res);
  12151. }
  12152. }
  12153. TEST(MultipartFormDataTest, AlternateFilename) {
  12154. auto handled = false;
  12155. Server svr;
  12156. svr.Post("/test", [&](const Request &req, Response &res) {
  12157. ASSERT_EQ(2u, req.form.files.size());
  12158. ASSERT_EQ(1u, req.form.fields.size());
  12159. // Test files
  12160. const auto &file1 = req.form.get_file("file1");
  12161. ASSERT_EQ("file1", file1.name);
  12162. ASSERT_EQ("A.txt", file1.filename);
  12163. ASSERT_EQ("text/plain", file1.content_type);
  12164. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  12165. const auto &file2 = req.form.get_file("file2");
  12166. ASSERT_EQ("file2", file2.name);
  12167. ASSERT_EQ("a.html", file2.filename);
  12168. ASSERT_EQ("text/html", file2.content_type);
  12169. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12170. file2.content);
  12171. // Test text field
  12172. const auto &text = req.form.get_field("text");
  12173. ASSERT_EQ("text default", text);
  12174. res.set_content("ok", "text/plain");
  12175. handled = true;
  12176. });
  12177. thread t = thread([&] { svr.listen(HOST, PORT); });
  12178. auto se = detail::scope_exit([&] {
  12179. svr.stop();
  12180. t.join();
  12181. ASSERT_FALSE(svr.is_running());
  12182. ASSERT_TRUE(handled);
  12183. });
  12184. svr.wait_until_ready();
  12185. auto req = "POST /test HTTP/1.1\r\n"
  12186. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12187. "Content-Length: 399\r\n"
  12188. "\r\n"
  12189. "----------\r\n"
  12190. "Content-Disposition: form-data; name=\"text\"\r\n"
  12191. "\r\n"
  12192. "text default\r\n"
  12193. "----------\r\n"
  12194. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12195. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12196. "Content-Type: text/plain\r\n"
  12197. "\r\n"
  12198. "Content of a.txt.\r\n"
  12199. "\r\n"
  12200. "----------\r\n"
  12201. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12202. "\"a.html\"\r\n"
  12203. "Content-Type: text/html\r\n"
  12204. "\r\n"
  12205. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12206. "\r\n"
  12207. "------------\r\n";
  12208. ASSERT_TRUE(send_request(1, req));
  12209. }
  12210. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12211. auto handled = false;
  12212. Server svr;
  12213. svr.Post("/test", [&](const Request &req, Response &res) {
  12214. // Case-insensitive "utf-8''" prefix with a long value
  12215. const auto &file = req.form.get_file("file1");
  12216. ASSERT_EQ("file1", file.name);
  12217. // 8000 chars exercises both the Content-Disposition parser and the
  12218. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12219. // Prior to the fix, std::regex_match on this header would cause O(N)
  12220. // stack recursion in libstdc++, leading to SIGSEGV.
  12221. std::string expected_filename(8000, 'A');
  12222. ASSERT_EQ(expected_filename, file.filename);
  12223. res.set_content("ok", "text/plain");
  12224. handled = true;
  12225. });
  12226. thread t = thread([&] { svr.listen(HOST, PORT); });
  12227. auto se = detail::scope_exit([&] {
  12228. svr.stop();
  12229. t.join();
  12230. ASSERT_FALSE(svr.is_running());
  12231. ASSERT_TRUE(handled);
  12232. });
  12233. svr.wait_until_ready();
  12234. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12235. // Regression test for GHSA-qq6v-r583-3h69
  12236. std::string long_filename(8000, 'A');
  12237. std::string body = "----------\r\n"
  12238. "Content-Disposition: form-data; name=\"file1\"; "
  12239. "filename*=\"Utf-8''" +
  12240. long_filename +
  12241. "\"\r\n"
  12242. "\r\n"
  12243. "hello\r\n"
  12244. "------------\r\n";
  12245. auto req = "POST /test HTTP/1.1\r\n"
  12246. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12247. "Content-Length: " +
  12248. std::to_string(body.size()) + "\r\n\r\n" + body;
  12249. ASSERT_TRUE(send_request(1, req));
  12250. }
  12251. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12252. auto handled = false;
  12253. Server svr;
  12254. svr.Post("/test", [&](const Request &req, Response &) {
  12255. ASSERT_EQ(2u, req.form.fields.size());
  12256. const auto &text1 = req.form.get_field("text1");
  12257. ASSERT_EQ("text1", text1);
  12258. const auto &text2 = req.form.get_field("text2");
  12259. ASSERT_EQ("text2", text2);
  12260. handled = true;
  12261. });
  12262. thread t = thread([&] { svr.listen(HOST, PORT); });
  12263. auto se = detail::scope_exit([&] {
  12264. svr.stop();
  12265. t.join();
  12266. ASSERT_FALSE(svr.is_running());
  12267. ASSERT_TRUE(handled);
  12268. });
  12269. svr.wait_until_ready();
  12270. auto req = "POST /test HTTP/1.1\r\n"
  12271. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12272. "Content-Length: 146\r\n"
  12273. "\r\n----------\r\n"
  12274. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12275. "\r\n"
  12276. "text1"
  12277. "\r\n----------\r\n"
  12278. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12279. "\r\n"
  12280. "text2"
  12281. "\r\n------------";
  12282. std::string response;
  12283. ASSERT_TRUE(send_request(1, req, &response));
  12284. ASSERT_EQ("200", response.substr(9, 3));
  12285. }
  12286. TEST(MultipartFormDataTest, ContentLength) {
  12287. auto handled = false;
  12288. Server svr;
  12289. svr.Post("/test", [&](const Request &req, Response &) {
  12290. ASSERT_EQ(2u, req.form.fields.size());
  12291. const auto &text1 = req.form.get_field("text1");
  12292. ASSERT_EQ("text1", text1);
  12293. const auto &text2 = req.form.get_field("text2");
  12294. ASSERT_EQ("text2", text2);
  12295. handled = true;
  12296. });
  12297. thread t = thread([&] { svr.listen(HOST, PORT); });
  12298. auto se = detail::scope_exit([&] {
  12299. svr.stop();
  12300. t.join();
  12301. ASSERT_FALSE(svr.is_running());
  12302. ASSERT_TRUE(handled);
  12303. });
  12304. svr.wait_until_ready();
  12305. auto req = "POST /test HTTP/1.1\r\n"
  12306. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12307. "Content-Length: 167\r\n"
  12308. "\r\n----------\r\n"
  12309. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12310. "Content-Length: 5\r\n"
  12311. "\r\n"
  12312. "text1"
  12313. "\r\n----------\r\n"
  12314. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12315. "\r\n"
  12316. "text2"
  12317. "\r\n------------\r\n";
  12318. std::string response;
  12319. ASSERT_TRUE(send_request(1, req, &response));
  12320. ASSERT_EQ("200", response.substr(9, 3));
  12321. }
  12322. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12323. auto handled = false;
  12324. Server svr;
  12325. svr.Post("/test", [&](const Request &req, Response &) {
  12326. ASSERT_EQ(2u, req.form.fields.size());
  12327. const auto &text1 = req.form.get_field("text1");
  12328. ASSERT_EQ("text1", text1);
  12329. // TODO: Add header access for text fields if needed
  12330. const auto &text2 = req.form.get_field("text2");
  12331. ASSERT_EQ("text2", text2);
  12332. // TODO: Header access for text fields needs to be implemented
  12333. // auto &headers = it->second.headers;
  12334. // ASSERT_EQ(3U, headers.size());
  12335. // auto custom_header = headers.find("x-whatever");
  12336. // ASSERT_TRUE(custom_header != headers.end());
  12337. // ASSERT_NE("customvalue", custom_header->second);
  12338. // ASSERT_EQ("CustomValue", custom_header->second);
  12339. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12340. handled = true;
  12341. });
  12342. thread t = thread([&] { svr.listen(HOST, PORT); });
  12343. auto se = detail::scope_exit([&] {
  12344. svr.stop();
  12345. t.join();
  12346. ASSERT_FALSE(svr.is_running());
  12347. ASSERT_TRUE(handled);
  12348. });
  12349. svr.wait_until_ready();
  12350. auto req = "POST /test HTTP/1.1\r\n"
  12351. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12352. "Content-Length: 232\r\n"
  12353. "\r\n----------\r\n"
  12354. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12355. "Content-Length: 5\r\n"
  12356. "X-Test: 1\r\n"
  12357. "\r\n"
  12358. "text1"
  12359. "\r\n----------\r\n"
  12360. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12361. "Content-Type: text/plain\r\n"
  12362. "X-Whatever: CustomValue\r\n"
  12363. "\r\n"
  12364. "text2"
  12365. "\r\n------------\r\n"
  12366. "That should be disregarded. Not even read";
  12367. std::string response;
  12368. ASSERT_TRUE(send_request(1, req, &response));
  12369. ASSERT_EQ("200", response.substr(9, 3));
  12370. }
  12371. TEST(MultipartFormDataTest, LargeHeader) {
  12372. auto handled = false;
  12373. Server svr;
  12374. svr.Post("/test", [&](const Request &req, Response &) {
  12375. ASSERT_EQ(1u, req.form.fields.size());
  12376. const auto &text = req.form.get_field("name1");
  12377. ASSERT_EQ("text1", text);
  12378. handled = true;
  12379. });
  12380. thread t = thread([&] { svr.listen(HOST, PORT); });
  12381. auto se = detail::scope_exit([&] {
  12382. svr.stop();
  12383. t.join();
  12384. ASSERT_FALSE(svr.is_running());
  12385. ASSERT_TRUE(handled);
  12386. });
  12387. svr.wait_until_ready();
  12388. auto boundary = std::string("cpp-httplib-multipart-data");
  12389. std::string content = "--" + boundary +
  12390. "\r\n"
  12391. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12392. "\r\n"
  12393. "text1\r\n"
  12394. "--" +
  12395. boundary + "--\r\n";
  12396. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12397. "Content-Type: multipart/form-data;boundary=" +
  12398. boundary +
  12399. "\r\n"
  12400. "Content-Length: " +
  12401. std::to_string(content.size()) +
  12402. "\r\n"
  12403. "Dummy-Header: ";
  12404. std::string header_suffix = "\r\n"
  12405. "\r\n";
  12406. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12407. size_t header_dummy_size =
  12408. read_buff_size -
  12409. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12410. auto header_dummy = std::string(header_dummy_size, '@');
  12411. auto req = header_prefix + header_dummy + header_suffix + content;
  12412. std::string response;
  12413. ASSERT_TRUE(send_request(1, req, &response));
  12414. ASSERT_EQ("200", response.substr(9, 3));
  12415. }
  12416. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12417. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12418. // (not chunked Transfer-Encoding) after the streaming refactor.
  12419. auto handled = false;
  12420. Server svr;
  12421. svr.Post("/upload", [&](const Request &req, Response &res) {
  12422. auto cl_it = req.headers.find("Content-Length");
  12423. EXPECT_TRUE(cl_it != req.headers.end());
  12424. auto te_it = req.headers.find("Transfer-Encoding");
  12425. EXPECT_TRUE(te_it == req.headers.end());
  12426. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12427. res.set_content("ok", "text/plain");
  12428. handled = true;
  12429. });
  12430. auto port = svr.bind_to_any_port(HOST);
  12431. auto t = thread([&] { svr.listen_after_bind(); });
  12432. auto se = detail::scope_exit([&] {
  12433. svr.stop();
  12434. t.join();
  12435. ASSERT_FALSE(svr.is_running());
  12436. ASSERT_TRUE(handled);
  12437. });
  12438. svr.wait_until_ready();
  12439. UploadFormDataItems items = {
  12440. {"field1", "hello", "", "text/plain"},
  12441. {"file1", "world", "test.txt", "application/octet-stream"},
  12442. };
  12443. Client cli(HOST, port);
  12444. auto res = cli.Post("/upload", {}, items);
  12445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12446. EXPECT_EQ(StatusCode::OK_200, res->status);
  12447. }
  12448. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12449. // Verify that make_multipart_content_provider coalesces many small segments
  12450. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12451. constexpr size_t kItemCount = 1000;
  12452. UploadFormDataItems items;
  12453. items.reserve(kItemCount);
  12454. for (size_t i = 0; i < kItemCount; i++) {
  12455. items.push_back(
  12456. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12457. }
  12458. const std::string boundary = "----test-boundary";
  12459. auto content_length = detail::get_multipart_content_length(items, boundary);
  12460. auto provider = detail::make_multipart_content_provider(items, boundary);
  12461. // Drive the provider the same way write_content_with_progress does
  12462. size_t write_count = 0;
  12463. size_t total_bytes = 0;
  12464. DataSink sink;
  12465. size_t offset = 0;
  12466. sink.write = [&](const char *d, size_t l) -> bool {
  12467. (void)d;
  12468. write_count++;
  12469. total_bytes += l;
  12470. offset += l;
  12471. return true;
  12472. };
  12473. sink.is_writable = []() -> bool { return true; };
  12474. while (offset < content_length) {
  12475. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12476. }
  12477. EXPECT_EQ(content_length, total_bytes);
  12478. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12479. // With buffering into 64KB blocks, write_count should be much smaller.
  12480. auto segment_count = 3 * kItemCount + 1;
  12481. EXPECT_LT(write_count, segment_count / 10);
  12482. }
  12483. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12484. // Integration test: send many UploadFormDataItems and verify the server
  12485. // receives all of them correctly (#2410).
  12486. constexpr size_t kItemCount = 500;
  12487. auto handled = false;
  12488. Server svr;
  12489. svr.Post("/upload", [&](const Request &req, Response &res) {
  12490. EXPECT_EQ(kItemCount, req.form.fields.size());
  12491. for (size_t i = 0; i < kItemCount; i++) {
  12492. auto key = "field" + std::to_string(i);
  12493. auto val = "value" + std::to_string(i);
  12494. auto it = req.form.fields.find(key);
  12495. if (it != req.form.fields.end()) {
  12496. EXPECT_EQ(val, it->second.content);
  12497. } else {
  12498. ADD_FAILURE() << "Missing field: " << key;
  12499. }
  12500. }
  12501. res.set_content("ok", "text/plain");
  12502. handled = true;
  12503. });
  12504. auto port = svr.bind_to_any_port(HOST);
  12505. auto t = thread([&] { svr.listen_after_bind(); });
  12506. auto se = detail::scope_exit([&] {
  12507. svr.stop();
  12508. t.join();
  12509. ASSERT_FALSE(svr.is_running());
  12510. ASSERT_TRUE(handled);
  12511. });
  12512. svr.wait_until_ready();
  12513. UploadFormDataItems items;
  12514. items.reserve(kItemCount);
  12515. for (size_t i = 0; i < kItemCount; i++) {
  12516. items.push_back(
  12517. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12518. }
  12519. Client cli(HOST, port);
  12520. auto res = cli.Post("/upload", items);
  12521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12522. EXPECT_EQ(StatusCode::OK_200, res->status);
  12523. }
  12524. TEST(MultipartFormDataTest, MakeFileProvider) {
  12525. // Verify make_file_provider sends a file's contents correctly.
  12526. const std::string file_content(4096, 'Z');
  12527. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12528. {
  12529. std::ofstream ofs(tmp_path, std::ios::binary);
  12530. ofs.write(file_content.data(),
  12531. static_cast<std::streamsize>(file_content.size()));
  12532. }
  12533. auto handled = false;
  12534. Server svr;
  12535. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12536. const ContentReader &content_reader) {
  12537. ASSERT_TRUE(req.is_multipart_form_data());
  12538. std::vector<FormData> items;
  12539. content_reader(
  12540. [&](const FormData &file) {
  12541. items.push_back(file);
  12542. return true;
  12543. },
  12544. [&](const char *data, size_t data_length) {
  12545. items.back().content.append(data, data_length);
  12546. return true;
  12547. });
  12548. ASSERT_EQ(1u, items.size());
  12549. EXPECT_EQ("myfile", items[0].name);
  12550. EXPECT_EQ("data.bin", items[0].filename);
  12551. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12552. EXPECT_EQ(file_content, items[0].content);
  12553. handled = true;
  12554. });
  12555. auto port = svr.bind_to_any_port(HOST);
  12556. auto t = thread([&] { svr.listen_after_bind(); });
  12557. auto se = detail::scope_exit([&] {
  12558. svr.stop();
  12559. t.join();
  12560. ASSERT_FALSE(svr.is_running());
  12561. ASSERT_TRUE(handled);
  12562. std::remove(tmp_path.c_str());
  12563. });
  12564. svr.wait_until_ready();
  12565. FormDataProviderItems providers;
  12566. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12567. "application/octet-stream"));
  12568. Client cli(HOST, port);
  12569. auto res = cli.Post("/upload", {}, {}, providers);
  12570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12571. EXPECT_EQ(StatusCode::OK_200, res->status);
  12572. }
  12573. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12574. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12575. // (100) headers is rejected with a 400 Bad Request response.
  12576. Server svr;
  12577. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12578. res.set_content("ok", "text/plain");
  12579. });
  12580. thread t = thread([&] { svr.listen(HOST, PORT); });
  12581. auto se = detail::scope_exit([&] {
  12582. svr.stop();
  12583. t.join();
  12584. ASSERT_FALSE(svr.is_running());
  12585. });
  12586. svr.wait_until_ready();
  12587. // Build a multipart part with 101 custom headers (exceeding
  12588. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12589. std::stringstream body;
  12590. body << "--simpleboundary\r\n"
  12591. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12592. for (int i = 0; i < 101; i++) {
  12593. body << "X-Custom-Header-" << i << ": value\r\n";
  12594. }
  12595. body << "\r\n"
  12596. << "value1\r\n"
  12597. << "--simpleboundary--\r\n";
  12598. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12599. Client cli(HOST, PORT);
  12600. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12602. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12603. }
  12604. TEST(MakeFileBodyTest, Basic) {
  12605. const std::string file_content(4096, 'Z');
  12606. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12607. {
  12608. std::ofstream ofs(tmp_path, std::ios::binary);
  12609. ofs.write(file_content.data(),
  12610. static_cast<std::streamsize>(file_content.size()));
  12611. }
  12612. auto handled = false;
  12613. Server svr;
  12614. svr.Post("/upload", [&](const Request &req, Response &res) {
  12615. EXPECT_EQ(file_content, req.body);
  12616. handled = true;
  12617. res.status = StatusCode::OK_200;
  12618. });
  12619. auto port = svr.bind_to_any_port(HOST);
  12620. auto t = thread([&] { svr.listen_after_bind(); });
  12621. auto se = detail::scope_exit([&] {
  12622. svr.stop();
  12623. t.join();
  12624. ASSERT_FALSE(svr.is_running());
  12625. ASSERT_TRUE(handled);
  12626. std::remove(tmp_path.c_str());
  12627. });
  12628. svr.wait_until_ready();
  12629. auto fb = make_file_body(tmp_path);
  12630. ASSERT_GT(fb.first, 0u);
  12631. Client cli(HOST, port);
  12632. auto res =
  12633. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12635. EXPECT_EQ(StatusCode::OK_200, res->status);
  12636. }
  12637. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12638. static constexpr unsigned int number_of_tasks{1000000};
  12639. std::atomic_uint count{0};
  12640. std::unique_ptr<TaskQueue> task_queue{
  12641. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12642. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12643. auto queued = task_queue->enqueue(
  12644. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12645. EXPECT_TRUE(queued);
  12646. }
  12647. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12648. task_queue->shutdown();
  12649. #else
  12650. EXPECT_NO_THROW(task_queue->shutdown());
  12651. #endif
  12652. EXPECT_EQ(number_of_tasks, count.load());
  12653. }
  12654. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12655. static constexpr unsigned int number_of_tasks{1000000};
  12656. static constexpr unsigned int qlimit{2};
  12657. unsigned int queued_count{0};
  12658. std::atomic_uint count{0};
  12659. std::unique_ptr<TaskQueue> task_queue{
  12660. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12661. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12662. if (task_queue->enqueue(
  12663. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12664. queued_count++;
  12665. }
  12666. }
  12667. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12668. task_queue->shutdown();
  12669. #else
  12670. EXPECT_NO_THROW(task_queue->shutdown());
  12671. #endif
  12672. EXPECT_EQ(queued_count, count.load());
  12673. EXPECT_TRUE(queued_count <= number_of_tasks);
  12674. EXPECT_TRUE(queued_count >= qlimit);
  12675. }
  12676. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12677. // Use a short idle timeout so a dynamic thread spawns, times out and
  12678. // exits during the test, and the pool keeps working afterwards.
  12679. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12680. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12681. /*idle_timeout_sec=*/1}};
  12682. std::atomic_uint count{0};
  12683. std::condition_variable cv;
  12684. std::mutex mtx;
  12685. bool release = false;
  12686. // Block the base thread so the second task spawns a dynamic thread.
  12687. EXPECT_TRUE(task_queue->enqueue([&] {
  12688. std::unique_lock<std::mutex> lock(mtx);
  12689. while (!release) {
  12690. cv.wait(lock);
  12691. }
  12692. count++;
  12693. }));
  12694. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12695. // Let the dynamic thread finish its task and exceed the idle timeout.
  12696. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12697. {
  12698. std::unique_lock<std::mutex> lock(mtx);
  12699. release = true;
  12700. }
  12701. cv.notify_all();
  12702. // The pool must still accept and run tasks after the dynamic thread exited.
  12703. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12704. task_queue->shutdown();
  12705. EXPECT_EQ(3u, count.load());
  12706. }
  12707. TEST(TaskQueueTest, MaxQueuedRequests) {
  12708. static constexpr unsigned int qlimit{3};
  12709. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12710. std::condition_variable sem_cv;
  12711. std::mutex sem_mtx;
  12712. int credits = 0;
  12713. bool queued;
  12714. /* Fill up the queue with tasks that will block until we give them credits to
  12715. * complete. */
  12716. for (unsigned int n = 0; n <= qlimit;) {
  12717. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12718. std::unique_lock<std::mutex> lock(sem_mtx);
  12719. while (credits <= 0) {
  12720. sem_cv.wait(lock);
  12721. }
  12722. /* Consume the credit and signal the test code if they are all gone. */
  12723. if (--credits == 0) { sem_cv.notify_one(); }
  12724. });
  12725. if (n < qlimit) {
  12726. /* The first qlimit enqueues must succeed. */
  12727. EXPECT_TRUE(queued);
  12728. } else {
  12729. /* The last one will succeed only when the worker thread
  12730. * starts and dequeues the first blocking task. Although
  12731. * not necessary for the correctness of this test, we sleep for
  12732. * a short while to avoid busy waiting. */
  12733. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12734. }
  12735. if (queued) { n++; }
  12736. }
  12737. /* Further enqueues must fail since the queue is full. */
  12738. for (auto i = 0; i < 4; i++) {
  12739. queued = task_queue->enqueue([] {});
  12740. EXPECT_FALSE(queued);
  12741. }
  12742. /* Give the credits to allow the previous tasks to complete. */
  12743. {
  12744. std::unique_lock<std::mutex> lock(sem_mtx);
  12745. credits += qlimit + 1;
  12746. }
  12747. sem_cv.notify_all();
  12748. /* Wait for all the credits to be consumed. */
  12749. {
  12750. std::unique_lock<std::mutex> lock(sem_mtx);
  12751. while (credits > 0) {
  12752. sem_cv.wait(lock);
  12753. }
  12754. }
  12755. /* Check that we are able again to enqueue at least qlimit tasks. */
  12756. for (unsigned int i = 0; i < qlimit; i++) {
  12757. queued = task_queue->enqueue([] {});
  12758. EXPECT_TRUE(queued);
  12759. }
  12760. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12761. task_queue->shutdown();
  12762. #else
  12763. EXPECT_NO_THROW(task_queue->shutdown());
  12764. #endif
  12765. }
  12766. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12767. Server svr;
  12768. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12769. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12770. });
  12771. svr.Get("/hello", [](const Request &req, Response &res) {
  12772. res.set_content(req.get_param_value("key"), "text/plain");
  12773. });
  12774. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12775. auto se = detail::scope_exit([&] {
  12776. svr.stop();
  12777. thread.join();
  12778. ASSERT_FALSE(svr.is_running());
  12779. });
  12780. svr.wait_until_ready();
  12781. {
  12782. Client cli(HOST, PORT);
  12783. cli.set_follow_location(true);
  12784. auto res = cli.Get("/");
  12785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12786. EXPECT_EQ(StatusCode::OK_200, res->status);
  12787. EXPECT_EQ("val&key2=val2", res->body);
  12788. }
  12789. }
  12790. #endif
  12791. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12792. Server svr;
  12793. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12794. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12795. });
  12796. svr.Get("/hello", [](const Request &req, Response &res) {
  12797. res.set_content(req.get_param_value("key"), "text/plain");
  12798. });
  12799. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12800. auto se = detail::scope_exit([&] {
  12801. svr.stop();
  12802. thread.join();
  12803. ASSERT_FALSE(svr.is_running());
  12804. });
  12805. svr.wait_until_ready();
  12806. {
  12807. Client cli(HOST, PORT);
  12808. cli.set_follow_location(true);
  12809. auto res = cli.Get("/");
  12810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12811. EXPECT_EQ(StatusCode::OK_200, res->status);
  12812. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12813. }
  12814. }
  12815. TEST(RedirectTest, RedirectWithPlusInPath) {
  12816. Server svr;
  12817. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12818. res.set_redirect("/a+b");
  12819. });
  12820. // Route pattern uses regex; escape + as \\+
  12821. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12822. res.set_content(req.path, "text/plain");
  12823. });
  12824. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12825. auto se = detail::scope_exit([&] {
  12826. svr.stop();
  12827. thread.join();
  12828. ASSERT_FALSE(svr.is_running());
  12829. });
  12830. svr.wait_until_ready();
  12831. {
  12832. Client cli(HOST, PORT);
  12833. cli.set_follow_location(true);
  12834. auto res = cli.Get("/");
  12835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12836. EXPECT_EQ(StatusCode::OK_200, res->status);
  12837. EXPECT_EQ("/a+b", res->body);
  12838. }
  12839. }
  12840. #ifdef CPPHTTPLIB_SSL_ENABLED
  12841. TEST(RedirectTest, Issue2185_Online) {
  12842. SSLClient client("github.com");
  12843. client.set_follow_location(true);
  12844. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12845. "Coollab-Windows.zip");
  12846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12847. EXPECT_EQ(StatusCode::OK_200, res->status);
  12848. EXPECT_EQ(9920427U, res->body.size());
  12849. }
  12850. #endif
  12851. TEST(VulnerabilityTest, CRLFInjection) {
  12852. Server svr;
  12853. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12854. res.set_content("Hello 1", "text/plain");
  12855. });
  12856. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12857. res.set_content("Hello 2", "text/plain");
  12858. });
  12859. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12860. res.set_content("Hello 3", "text/plain");
  12861. });
  12862. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12863. res.set_content("Hello 4", "text/plain");
  12864. });
  12865. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12866. for (const auto &x : req.headers) {
  12867. auto key = x.first;
  12868. EXPECT_STRNE("evil", key.c_str());
  12869. }
  12870. });
  12871. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12872. auto se = detail::scope_exit([&] {
  12873. svr.stop();
  12874. thread.join();
  12875. ASSERT_FALSE(svr.is_running());
  12876. });
  12877. svr.wait_until_ready();
  12878. {
  12879. Client cli(HOST, PORT);
  12880. cli.Post("/test1", "A=B",
  12881. "application/x-www-form-urlencoded\r\nevil: hello1");
  12882. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12883. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12884. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12885. }
  12886. }
  12887. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12888. auto server_thread = std::thread([] {
  12889. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12890. default_socket_options(srv);
  12891. sockaddr_in addr{};
  12892. addr.sin_family = AF_INET;
  12893. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12894. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12895. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12896. ::listen(srv, 1);
  12897. sockaddr_in cli_addr{};
  12898. socklen_t cli_len = sizeof(cli_addr);
  12899. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12900. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12901. std::string buf_all;
  12902. char buf[2048];
  12903. ssize_t n;
  12904. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12905. buf_all.append(buf, static_cast<size_t>(n));
  12906. size_t pos;
  12907. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12908. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12909. auto e = request_block.find("\r\n");
  12910. if (e != std::string::npos) {
  12911. auto request_line = request_block.substr(0, e);
  12912. std::string msg =
  12913. "CRLF injection detected in request line: '" + request_line + "'";
  12914. EXPECT_FALSE(true) << msg;
  12915. }
  12916. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12917. ::send(cli,
  12918. #ifdef _WIN32
  12919. static_cast<const char *>(resp.c_str()),
  12920. static_cast<int>(resp.size()),
  12921. #else
  12922. resp.c_str(), resp.size(),
  12923. #endif
  12924. 0);
  12925. buf_all.erase(0, pos + 4);
  12926. }
  12927. }
  12928. detail::close_socket(cli);
  12929. detail::close_socket(srv);
  12930. });
  12931. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12932. auto cli = Client("127.0.0.1", PORT + 1);
  12933. auto headers = Headers{
  12934. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12935. {"Connection", "keep-alive"}};
  12936. auto res = cli.Get("/hi", headers);
  12937. EXPECT_FALSE(res);
  12938. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12939. server_thread.join();
  12940. }
  12941. TEST(PathParamsTest, StaticMatch) {
  12942. const auto pattern = "/users/all";
  12943. detail::PathParamsMatcher matcher(pattern);
  12944. Request request;
  12945. request.path = "/users/all";
  12946. ASSERT_TRUE(matcher.match(request));
  12947. std::unordered_map<std::string, std::string> expected_params = {};
  12948. EXPECT_EQ(request.path_params, expected_params);
  12949. }
  12950. TEST(PathParamsTest, StaticMismatch) {
  12951. const auto pattern = "/users/all";
  12952. detail::PathParamsMatcher matcher(pattern);
  12953. Request request;
  12954. request.path = "/users/1";
  12955. ASSERT_FALSE(matcher.match(request));
  12956. }
  12957. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12958. const auto pattern = "/users/:id/subscriptions";
  12959. detail::PathParamsMatcher matcher(pattern);
  12960. Request request;
  12961. request.path = "/users/42/subscriptions";
  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, SingleParamInTheEnd) {
  12967. const auto pattern = "/users/:id";
  12968. detail::PathParamsMatcher matcher(pattern);
  12969. Request request;
  12970. request.path = "/users/24";
  12971. ASSERT_TRUE(matcher.match(request));
  12972. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12973. EXPECT_EQ(request.path_params, expected_params);
  12974. }
  12975. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12976. const auto pattern = "/users/:id/";
  12977. detail::PathParamsMatcher matcher(pattern);
  12978. Request request;
  12979. request.path = "/users/42/";
  12980. ASSERT_TRUE(matcher.match(request));
  12981. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12982. EXPECT_EQ(request.path_params, expected_params);
  12983. }
  12984. TEST(PathParamsTest, EmptyParam) {
  12985. const auto pattern = "/users/:id/";
  12986. detail::PathParamsMatcher matcher(pattern);
  12987. Request request;
  12988. request.path = "/users//";
  12989. ASSERT_TRUE(matcher.match(request));
  12990. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12991. EXPECT_EQ(request.path_params, expected_params);
  12992. }
  12993. TEST(PathParamsTest, FragmentMismatch) {
  12994. const auto pattern = "/users/:id/";
  12995. detail::PathParamsMatcher matcher(pattern);
  12996. Request request;
  12997. request.path = "/admins/24/";
  12998. ASSERT_FALSE(matcher.match(request));
  12999. }
  13000. TEST(PathParamsTest, ExtraFragments) {
  13001. const auto pattern = "/users/:id";
  13002. detail::PathParamsMatcher matcher(pattern);
  13003. Request request;
  13004. request.path = "/users/42/subscriptions";
  13005. ASSERT_FALSE(matcher.match(request));
  13006. }
  13007. TEST(PathParamsTest, MissingTrailingParam) {
  13008. const auto pattern = "/users/:id";
  13009. detail::PathParamsMatcher matcher(pattern);
  13010. Request request;
  13011. request.path = "/users";
  13012. ASSERT_FALSE(matcher.match(request));
  13013. }
  13014. TEST(PathParamsTest, MissingParamInTheMiddle) {
  13015. const auto pattern = "/users/:id/subscriptions";
  13016. detail::PathParamsMatcher matcher(pattern);
  13017. Request request;
  13018. request.path = "/users/subscriptions";
  13019. ASSERT_FALSE(matcher.match(request));
  13020. }
  13021. TEST(PathParamsTest, MultipleParams) {
  13022. const auto pattern = "/users/:userid/subscriptions/:subid";
  13023. detail::PathParamsMatcher matcher(pattern);
  13024. Request request;
  13025. request.path = "/users/42/subscriptions/2";
  13026. ASSERT_TRUE(matcher.match(request));
  13027. std::unordered_map<std::string, std::string> expected_params = {
  13028. {"userid", "42"}, {"subid", "2"}};
  13029. EXPECT_EQ(request.path_params, expected_params);
  13030. }
  13031. TEST(PathParamsTest, SequenceOfParams) {
  13032. const auto pattern = "/values/:x/:y/:z";
  13033. detail::PathParamsMatcher matcher(pattern);
  13034. Request request;
  13035. request.path = "/values/1/2/3";
  13036. ASSERT_TRUE(matcher.match(request));
  13037. std::unordered_map<std::string, std::string> expected_params = {
  13038. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  13039. EXPECT_EQ(request.path_params, expected_params);
  13040. }
  13041. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  13042. const auto pattern = "/prefix:suffix";
  13043. detail::PathParamsMatcher matcher(pattern);
  13044. Request request;
  13045. request.path = "/prefix:suffix";
  13046. ASSERT_TRUE(matcher.match(request));
  13047. const std::unordered_map<std::string, std::string> expected_params = {};
  13048. EXPECT_EQ(request.path_params, expected_params);
  13049. }
  13050. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  13051. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  13052. // calling thread's stack on a long enough path for a quantified pattern;
  13053. // RegexMatcher must refuse to run regex matching on paths beyond
  13054. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  13055. detail::RegexMatcher matcher("/files/(.*)");
  13056. Request within_limit;
  13057. within_limit.path = "/files/" + std::string(10, 'A');
  13058. EXPECT_TRUE(matcher.match(within_limit));
  13059. Request over_limit;
  13060. over_limit.path =
  13061. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  13062. EXPECT_FALSE(matcher.match(over_limit));
  13063. }
  13064. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  13065. Server svr;
  13066. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  13067. res.set_content("ok", "text/plain");
  13068. });
  13069. auto port = svr.bind_to_any_port(HOST);
  13070. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13071. auto se = detail::scope_exit([&] {
  13072. svr.stop();
  13073. thread.join();
  13074. ASSERT_FALSE(svr.is_running());
  13075. });
  13076. svr.wait_until_ready();
  13077. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  13078. // request URI limit; this used to be able to crash the process.
  13079. std::string path =
  13080. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  13081. std::string req = "GET " + path +
  13082. " HTTP/1.1\r\n"
  13083. "Host: " +
  13084. std::string(HOST) + ":" + std::to_string(port) +
  13085. "\r\n"
  13086. "Connection: close\r\n"
  13087. "\r\n";
  13088. std::string response;
  13089. ASSERT_TRUE(send_request(5, req, &response, port));
  13090. EXPECT_NE(std::string::npos, response.find("404"));
  13091. }
  13092. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  13093. Server svr;
  13094. auto handler = [](const Request & /*req*/, Response &res) {
  13095. res.set_content("hit", "text/plain");
  13096. };
  13097. // No regex metacharacter, so this one is compared literally
  13098. svr.Get("/literal/route", handler);
  13099. // '.' is a regex metacharacter, so this one must keep regex semantics
  13100. svr.Get("/a.c", handler);
  13101. auto port = svr.bind_to_any_port(HOST);
  13102. std::thread t([&]() { svr.listen_after_bind(); });
  13103. auto se = detail::scope_exit([&] {
  13104. svr.stop();
  13105. t.join();
  13106. ASSERT_FALSE(svr.is_running());
  13107. });
  13108. svr.wait_until_ready();
  13109. Client cli(HOST, port);
  13110. struct {
  13111. const char *path;
  13112. int status;
  13113. } cases[] = {
  13114. {"/literal/route", StatusCode::OK_200},
  13115. {"/literal/routes", StatusCode::NotFound_404},
  13116. {"/literal/rout", StatusCode::NotFound_404},
  13117. {"/abc", StatusCode::OK_200},
  13118. {"/a.c", StatusCode::OK_200},
  13119. };
  13120. for (const auto &x : cases) {
  13121. auto res = cli.Get(x.path);
  13122. ASSERT_TRUE(res) << x.path;
  13123. EXPECT_EQ(x.status, res->status) << x.path;
  13124. }
  13125. }
  13126. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  13127. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  13128. // from exhausting the stack, so it must only constrain routes that actually
  13129. // run a regular expression. A literal route is matched by comparison and
  13130. // stays usable at any length.
  13131. Server svr;
  13132. const std::string pattern =
  13133. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  13134. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  13135. res.set_content("hit", "text/plain");
  13136. });
  13137. auto port = svr.bind_to_any_port(HOST);
  13138. std::thread t([&]() { svr.listen_after_bind(); });
  13139. auto se = detail::scope_exit([&] {
  13140. svr.stop();
  13141. t.join();
  13142. ASSERT_FALSE(svr.is_running());
  13143. });
  13144. svr.wait_until_ready();
  13145. Client cli(HOST, port);
  13146. auto res = cli.Get(pattern);
  13147. ASSERT_TRUE(res);
  13148. EXPECT_EQ(StatusCode::OK_200, res->status);
  13149. }
  13150. TEST(ParseUrlTest, VariousPatterns) {
  13151. {
  13152. detail::UrlComponents uc;
  13153. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  13154. EXPECT_EQ("http", uc.scheme);
  13155. EXPECT_EQ("example.com", uc.host);
  13156. EXPECT_EQ("8080", uc.port);
  13157. EXPECT_EQ("/path", uc.path);
  13158. EXPECT_EQ("?q=1", uc.query);
  13159. }
  13160. {
  13161. detail::UrlComponents uc;
  13162. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  13163. EXPECT_EQ("https", uc.scheme);
  13164. EXPECT_EQ("example.com", uc.host);
  13165. EXPECT_TRUE(uc.port.empty());
  13166. EXPECT_EQ("/path", uc.path);
  13167. }
  13168. {
  13169. detail::UrlComponents uc;
  13170. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  13171. EXPECT_EQ("::1", uc.host);
  13172. EXPECT_EQ("8080", uc.port);
  13173. EXPECT_EQ("/path", uc.path);
  13174. }
  13175. {
  13176. detail::UrlComponents uc;
  13177. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  13178. }
  13179. {
  13180. // Bytes after the IPv6 literal must be a delimiter, not folded into
  13181. // the path while the connection still targets the bracketed host.
  13182. detail::UrlComponents uc;
  13183. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  13184. }
  13185. {
  13186. detail::UrlComponents uc;
  13187. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  13188. }
  13189. {
  13190. detail::UrlComponents uc;
  13191. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  13192. EXPECT_EQ("::1", uc.host);
  13193. EXPECT_TRUE(uc.port.empty());
  13194. EXPECT_EQ("/path", uc.path);
  13195. }
  13196. {
  13197. detail::UrlComponents uc;
  13198. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  13199. EXPECT_TRUE(uc.scheme.empty());
  13200. EXPECT_EQ("example.com", uc.host);
  13201. EXPECT_EQ("/path", uc.path);
  13202. EXPECT_EQ("?q=1", uc.query);
  13203. }
  13204. {
  13205. detail::UrlComponents uc;
  13206. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  13207. EXPECT_TRUE(uc.host.empty());
  13208. EXPECT_EQ("/path", uc.path);
  13209. EXPECT_EQ("?q=1", uc.query);
  13210. }
  13211. {
  13212. detail::UrlComponents uc;
  13213. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  13214. EXPECT_EQ("example.com", uc.host);
  13215. EXPECT_EQ("8080", uc.port);
  13216. }
  13217. {
  13218. // Unix socket path — must not be parsed as host
  13219. detail::UrlComponents uc;
  13220. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  13221. EXPECT_TRUE(uc.host.empty());
  13222. }
  13223. {
  13224. detail::UrlComponents uc;
  13225. ASSERT_TRUE(detail::parse_url("", uc));
  13226. EXPECT_TRUE(uc.host.empty());
  13227. EXPECT_TRUE(uc.path.empty());
  13228. }
  13229. {
  13230. detail::UrlComponents uc;
  13231. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  13232. }
  13233. {
  13234. detail::UrlComponents uc;
  13235. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  13236. }
  13237. {
  13238. // Accepted by parse_url; callers restrict to http/https
  13239. detail::UrlComponents uc;
  13240. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  13241. EXPECT_EQ("ftp", uc.scheme);
  13242. }
  13243. {
  13244. detail::UrlComponents uc;
  13245. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  13246. }
  13247. {
  13248. detail::UrlComponents uc;
  13249. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  13250. }
  13251. }
  13252. TEST(ParseUrlTest, FragmentHandling) {
  13253. {
  13254. detail::UrlComponents uc;
  13255. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  13256. EXPECT_EQ("/path", uc.path);
  13257. EXPECT_TRUE(uc.query.empty());
  13258. }
  13259. {
  13260. detail::UrlComponents uc;
  13261. ASSERT_TRUE(detail::parse_url("#frag", uc));
  13262. EXPECT_TRUE(uc.path.empty());
  13263. EXPECT_TRUE(uc.query.empty());
  13264. }
  13265. }
  13266. TEST(ParseUrlTest, UserinfoHandling) {
  13267. // Userinfo with @ but no colon — host includes @
  13268. detail::UrlComponents uc;
  13269. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  13270. EXPECT_EQ("user@host.com", uc.host);
  13271. EXPECT_EQ("/path", uc.path);
  13272. }
  13273. TEST(ParseUrlTest, IPv6EdgeCases) {
  13274. {
  13275. detail::UrlComponents uc;
  13276. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  13277. EXPECT_TRUE(uc.scheme.empty());
  13278. EXPECT_EQ("::1", uc.host);
  13279. EXPECT_EQ("8080", uc.port);
  13280. }
  13281. {
  13282. // Zone ID '%25' is not in [a-fA-F0-9:]
  13283. detail::UrlComponents uc;
  13284. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  13285. }
  13286. }
  13287. TEST(ParseUrlTest, SchemeEdgeCases) {
  13288. {
  13289. detail::UrlComponents uc;
  13290. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  13291. }
  13292. {
  13293. detail::UrlComponents uc;
  13294. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  13295. }
  13296. {
  13297. detail::UrlComponents uc;
  13298. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  13299. }
  13300. }
  13301. TEST(ParseUrlTest, PortEdgeCases) {
  13302. {
  13303. detail::UrlComponents uc;
  13304. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  13305. EXPECT_TRUE(uc.port.empty());
  13306. EXPECT_EQ("/path", uc.path);
  13307. }
  13308. {
  13309. // parse_url accepts any port string; validation is done by parse_port
  13310. detail::UrlComponents uc;
  13311. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  13312. EXPECT_EQ("abc", uc.port);
  13313. }
  13314. }
  13315. TEST(ParseUrlTest, WebSocketPatterns) {
  13316. {
  13317. detail::UrlComponents uc;
  13318. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  13319. EXPECT_EQ("ws", uc.scheme);
  13320. EXPECT_EQ("echo.example.com", uc.host);
  13321. EXPECT_EQ("8080", uc.port);
  13322. EXPECT_EQ("/ws", uc.path);
  13323. }
  13324. {
  13325. detail::UrlComponents uc;
  13326. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  13327. EXPECT_EQ("wss", uc.scheme);
  13328. EXPECT_EQ("echo.example.com", uc.host);
  13329. EXPECT_TRUE(uc.port.empty());
  13330. EXPECT_EQ("/ws", uc.path);
  13331. }
  13332. }
  13333. TEST(ParseUrlTest, QueryOnly) {
  13334. detail::UrlComponents uc;
  13335. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  13336. EXPECT_TRUE(uc.host.empty());
  13337. EXPECT_TRUE(uc.path.empty());
  13338. EXPECT_EQ("?q=1&r=2", uc.query);
  13339. }
  13340. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13341. detail::UrlComponents uc;
  13342. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13343. EXPECT_TRUE(uc.scheme.empty());
  13344. EXPECT_EQ("example.com", uc.host);
  13345. EXPECT_EQ("443", uc.port);
  13346. EXPECT_EQ("/path", uc.path);
  13347. }
  13348. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13349. // If ipv6 regex working, regex match codepath is taken.
  13350. // else port will default to 80 in Client impl
  13351. int clientImplMagicPort = 80;
  13352. int port = 4321;
  13353. // above ports must be different to avoid false negative
  13354. EXPECT_NE(clientImplMagicPort, port);
  13355. std::string ipV6TestURL = "http://[ff06::c3]";
  13356. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13357. CLIENT_PRIVATE_KEY_FILE);
  13358. EXPECT_EQ(cli.port(), port);
  13359. }
  13360. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13361. auto file_path = "./www/dir/index.html";
  13362. auto dir_path = "./www/dir";
  13363. detail::FileStat stat_file(file_path);
  13364. EXPECT_TRUE(stat_file.is_file());
  13365. EXPECT_FALSE(stat_file.is_dir());
  13366. detail::FileStat stat_dir(dir_path);
  13367. EXPECT_FALSE(stat_dir.is_file());
  13368. EXPECT_TRUE(stat_dir.is_dir());
  13369. }
  13370. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13371. // IPv4 with default HTTP port (80)
  13372. EXPECT_EQ("example.com",
  13373. detail::make_host_and_port_string("example.com", 80, false));
  13374. // IPv4 with default HTTPS port (443)
  13375. EXPECT_EQ("example.com",
  13376. detail::make_host_and_port_string("example.com", 443, true));
  13377. // IPv4 with non-default HTTP port
  13378. EXPECT_EQ("example.com:8080",
  13379. detail::make_host_and_port_string("example.com", 8080, false));
  13380. // IPv4 with non-default HTTPS port
  13381. EXPECT_EQ("example.com:8443",
  13382. detail::make_host_and_port_string("example.com", 8443, true));
  13383. // IPv6 with default HTTP port (80)
  13384. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13385. // IPv6 with default HTTPS port (443)
  13386. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13387. // IPv6 with non-default HTTP port
  13388. EXPECT_EQ("[::1]:8080",
  13389. detail::make_host_and_port_string("::1", 8080, false));
  13390. // IPv6 with non-default HTTPS port
  13391. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13392. // IPv6 full address with default port
  13393. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13394. detail::make_host_and_port_string(
  13395. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13396. // IPv6 full address with non-default port
  13397. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13398. detail::make_host_and_port_string(
  13399. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13400. // IPv6 localhost with non-default port
  13401. EXPECT_EQ("[::1]:3000",
  13402. detail::make_host_and_port_string("::1", 3000, false));
  13403. // IPv6 with zone ID (link-local address) with default port
  13404. EXPECT_EQ("[fe80::1%eth0]",
  13405. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13406. // IPv6 with zone ID (link-local address) with non-default port
  13407. EXPECT_EQ("[fe80::1%eth0]:8080",
  13408. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13409. // Edge case: Port 443 with is_ssl=false (should add port)
  13410. EXPECT_EQ("example.com:443",
  13411. detail::make_host_and_port_string("example.com", 443, false));
  13412. // Edge case: Port 80 with is_ssl=true (should add port)
  13413. EXPECT_EQ("example.com:80",
  13414. detail::make_host_and_port_string("example.com", 80, true));
  13415. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13416. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13417. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13418. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13419. // Security fix: Already bracketed IPv6 should not get double brackets
  13420. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13421. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13422. EXPECT_EQ("[::1]:8080",
  13423. detail::make_host_and_port_string("[::1]", 8080, false));
  13424. EXPECT_EQ("[2001:db8::1]:8080",
  13425. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13426. EXPECT_EQ("[fe80::1%eth0]",
  13427. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13428. EXPECT_EQ("[fe80::1%eth0]:8080",
  13429. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13430. // Edge case: Empty host (should return as-is)
  13431. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13432. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13433. // This is a known limitation but shouldn't crash
  13434. EXPECT_EQ("[host:name]",
  13435. detail::make_host_and_port_string("host:name", 80, false));
  13436. // Port number edge cases (no validation, but should not crash)
  13437. EXPECT_EQ("example.com:0",
  13438. detail::make_host_and_port_string("example.com", 0, false));
  13439. EXPECT_EQ("example.com:-1",
  13440. detail::make_host_and_port_string("example.com", -1, false));
  13441. EXPECT_EQ("example.com:65535",
  13442. detail::make_host_and_port_string("example.com", 65535, false));
  13443. EXPECT_EQ("example.com:65536",
  13444. detail::make_host_and_port_string("example.com", 65536, false));
  13445. }
  13446. #ifdef CPPHTTPLIB_SSL_ENABLED
  13447. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13448. httplib::SSLClient cli("roblox.com", 443);
  13449. cli.set_follow_location(true);
  13450. auto res = cli.Get("/");
  13451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13452. EXPECT_EQ(StatusCode::OK_200, res->status);
  13453. }
  13454. #endif
  13455. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13456. Server svr;
  13457. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13458. EXPECT_EQ(res.status, 400);
  13459. });
  13460. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13461. auto se = detail::scope_exit([&] {
  13462. svr.stop();
  13463. thread.join();
  13464. ASSERT_FALSE(svr.is_running());
  13465. });
  13466. svr.wait_until_ready();
  13467. Client cli(HOST, PORT);
  13468. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13469. }
  13470. TEST(InvalidHeaderCharsTest, is_field_name) {
  13471. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13472. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13473. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13474. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13475. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13476. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13477. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13478. EXPECT_FALSE(detail::fields::is_field_name(""));
  13479. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13480. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13481. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13482. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13483. }
  13484. TEST(InvalidHeaderCharsTest, is_field_value) {
  13485. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13486. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13487. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13488. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13489. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13490. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13491. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13492. EXPECT_TRUE(detail::fields::is_field_value(""));
  13493. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13494. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13495. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13496. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13497. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13498. }
  13499. TEST(InvalidHeaderCharsTest, OnServer) {
  13500. Server svr;
  13501. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13502. std::string header = "Not Set";
  13503. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13504. res.set_header(header, "value");
  13505. res.set_content("Page Content Page Content", "text/plain");
  13506. });
  13507. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13508. std::string header = "Not Set";
  13509. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13510. res.set_header("X-Test", header);
  13511. res.set_content("Page Content Page Content", "text/plain");
  13512. });
  13513. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13514. auto se = detail::scope_exit([&] {
  13515. svr.stop();
  13516. thread.join();
  13517. ASSERT_FALSE(svr.is_running());
  13518. });
  13519. svr.wait_until_ready();
  13520. Client cli(HOST, PORT);
  13521. {
  13522. auto res = cli.Get(
  13523. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13525. EXPECT_EQ("Page Content Page Content", res->body);
  13526. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13527. }
  13528. {
  13529. auto res = cli.Get(
  13530. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13532. EXPECT_EQ("Page Content Page Content", res->body);
  13533. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13534. }
  13535. }
  13536. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13537. auto handled = false;
  13538. Server svr;
  13539. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13540. thread t = thread([&] { svr.listen(HOST, PORT); });
  13541. auto se = detail::scope_exit([&] {
  13542. svr.stop();
  13543. t.join();
  13544. ASSERT_FALSE(svr.is_running());
  13545. ASSERT_FALSE(handled);
  13546. });
  13547. svr.wait_until_ready();
  13548. auto req = "POST /test HTTP/1.1\r\n"
  13549. "Content-Length: x\r\n"
  13550. "\r\n";
  13551. std::string response;
  13552. ASSERT_TRUE(send_request(1, req, &response));
  13553. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13554. response.substr(0, response.find("\r\n")));
  13555. }
  13556. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  13557. // case-insensitive, and a server that receives a 100-continue expectation in
  13558. // an HTTP/1.0 request MUST ignore it.
  13559. static void probe_expect(int port, const std::string &req, bool *got_100) {
  13560. std::string response;
  13561. ASSERT_TRUE(send_request(1, req, &response, port));
  13562. *got_100 = response.find("100 Continue") != std::string::npos;
  13563. }
  13564. class ExpectTokenTest : public ::testing::Test {
  13565. protected:
  13566. void SetUp() override {
  13567. svr_.Post("/p", [](const Request &, Response &res) {
  13568. res.set_content("ok", "text/plain");
  13569. });
  13570. port_ = svr_.bind_to_any_port(HOST);
  13571. thread_ = thread([&]() { svr_.listen_after_bind(); });
  13572. svr_.wait_until_ready();
  13573. }
  13574. void TearDown() override {
  13575. svr_.stop();
  13576. if (thread_.joinable()) { thread_.join(); }
  13577. }
  13578. std::string request(const char *version, const char *expect_value) const {
  13579. return std::string("POST /p ") + version +
  13580. "\r\n"
  13581. "Host: localhost\r\n"
  13582. "Content-Length: 2\r\n"
  13583. "Connection: close\r\n"
  13584. "Expect: " +
  13585. expect_value +
  13586. "\r\n"
  13587. "\r\n"
  13588. "hi";
  13589. }
  13590. Server svr_;
  13591. int port_ = 0;
  13592. thread thread_;
  13593. };
  13594. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  13595. bool got_100 = false;
  13596. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  13597. EXPECT_TRUE(got_100);
  13598. }
  13599. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  13600. bool got_100 = true;
  13601. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  13602. EXPECT_FALSE(got_100);
  13603. }
  13604. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  13605. bool got_100 = false;
  13606. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  13607. EXPECT_TRUE(got_100);
  13608. }
  13609. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  13610. bool got_100 = false;
  13611. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  13612. EXPECT_TRUE(got_100);
  13613. }
  13614. #ifndef _WIN32
  13615. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13616. static constexpr char reject[] = "Unauthorized";
  13617. static constexpr char accept[] = "Upload accepted";
  13618. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  13619. Server svr;
  13620. svr.set_expect_100_continue_handler(
  13621. [](const Request & /*req*/, Response &res) {
  13622. res.status = StatusCode::Unauthorized_401;
  13623. res.set_content(reject, "text/plain");
  13624. return res.status;
  13625. });
  13626. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13627. res.set_content(accept, "text/plain");
  13628. });
  13629. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13630. auto se = detail::scope_exit([&] {
  13631. svr.stop();
  13632. thread.join();
  13633. ASSERT_FALSE(svr.is_running());
  13634. });
  13635. svr.wait_until_ready();
  13636. {
  13637. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13638. curl_easy_init(), &curl_easy_cleanup};
  13639. ASSERT_NE(curl, nullptr);
  13640. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13641. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13642. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13643. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13644. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13645. &curl_slist_free_all};
  13646. ASSERT_NE(list, nullptr);
  13647. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13648. struct read_data {
  13649. size_t read_size;
  13650. size_t total_size;
  13651. } data = {0, total_size};
  13652. using read_callback_t =
  13653. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13654. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13655. void *userdata) -> size_t {
  13656. read_data *d = (read_data *)userdata;
  13657. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13658. std::fill_n(ptr, size * nmemb, 'A');
  13659. d->read_size += size * nmemb;
  13660. return size * nmemb;
  13661. };
  13662. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13663. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13664. std::vector<char> buffer;
  13665. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13666. using write_callback_t =
  13667. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13668. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13669. void *userdata) -> size_t {
  13670. std::vector<char> *buf = (std::vector<char> *)userdata;
  13671. buf->reserve(buf->size() + size * nmemb + 1);
  13672. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13673. return size * nmemb;
  13674. };
  13675. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13676. {
  13677. const auto res = curl_easy_perform(curl.get());
  13678. ASSERT_EQ(res, CURLE_OK);
  13679. }
  13680. {
  13681. auto response_code = long{};
  13682. const auto res =
  13683. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13684. ASSERT_EQ(res, CURLE_OK);
  13685. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13686. }
  13687. {
  13688. auto dl = curl_off_t{};
  13689. const auto res =
  13690. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13691. ASSERT_EQ(res, CURLE_OK);
  13692. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13693. }
  13694. {
  13695. buffer.push_back('\0');
  13696. ASSERT_STRCASEEQ(buffer.data(), reject);
  13697. }
  13698. }
  13699. }
  13700. #endif
  13701. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13702. // Regression test for #2458.
  13703. //
  13704. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13705. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13706. // ticket can make the client socket spuriously readable during the
  13707. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13708. // the client withholds the body and then blocks reading a response that never
  13709. // comes, failing with `Failed to read connection`.
  13710. //
  13711. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13712. // within the timeout. This raw OpenSSL server deliberately never sends
  13713. // `100 Continue`; the client must still deliver the body and receive 200.
  13714. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13715. signal(SIGPIPE, SIG_IGN);
  13716. const auto port = PORT + 4;
  13717. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13718. ASSERT_NE(srv, INVALID_SOCKET);
  13719. int opt = 1;
  13720. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13721. sockaddr_in addr{};
  13722. addr.sin_family = AF_INET;
  13723. addr.sin_port = htons(static_cast<uint16_t>(port));
  13724. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13725. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13726. ASSERT_EQ(0, ::listen(srv, 1));
  13727. std::atomic<size_t> server_body_bytes{0};
  13728. auto server_thread = std::thread([&] {
  13729. sockaddr_in cli_addr{};
  13730. socklen_t cli_len = sizeof(cli_addr);
  13731. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13732. if (cli == INVALID_SOCKET) { return; }
  13733. // Bound the lifetime of the server side so a buggy client (which never
  13734. // sends the body) cannot make this thread block forever on join.
  13735. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13736. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13737. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13738. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13739. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13740. SSL *ssl = SSL_new(ctx);
  13741. SSL_set_fd(ssl, static_cast<int>(cli));
  13742. if (SSL_accept(ssl) > 0) {
  13743. // Read the request headers. Reading here also flushes the TLS 1.3
  13744. // session tickets to the client. Deliberately do NOT send
  13745. // `100 Continue`.
  13746. std::string buf;
  13747. char tmp[1024];
  13748. while (buf.find("\r\n\r\n") == std::string::npos) {
  13749. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13750. if (n <= 0) { break; }
  13751. buf.append(tmp, static_cast<size_t>(n));
  13752. }
  13753. // A correct client sends the body now; count what arrives.
  13754. auto pos = buf.find("\r\n\r\n");
  13755. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13756. while (body < 4096) {
  13757. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13758. if (n <= 0) { break; }
  13759. body += static_cast<size_t>(n);
  13760. }
  13761. server_body_bytes = body;
  13762. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13763. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13764. SSL_shutdown(ssl);
  13765. }
  13766. SSL_free(ssl);
  13767. detail::close_socket(cli);
  13768. SSL_CTX_free(ctx);
  13769. });
  13770. auto se = detail::scope_exit([&] {
  13771. server_thread.join();
  13772. detail::close_socket(srv);
  13773. });
  13774. SSLClient cli("127.0.0.1", port);
  13775. cli.enable_server_certificate_verification(false);
  13776. cli.set_connection_timeout(5, 0);
  13777. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13778. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13779. std::string body(4096, 'A');
  13780. auto res = cli.Put("/api/test", body, "application/json");
  13781. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13782. EXPECT_EQ(StatusCode::OK_200, res->status);
  13783. EXPECT_EQ(body.size(), server_body_bytes.load());
  13784. }
  13785. #endif
  13786. template <typename S, typename C>
  13787. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13788. svr.Get("/stream", [&](const Request &, Response &res) {
  13789. auto data = new std::string("01234567890123456789");
  13790. res.set_content_provider(
  13791. data->size(), "text/plain",
  13792. [&, data](size_t offset, size_t length, DataSink &sink) {
  13793. const size_t DATA_CHUNK_SIZE = 4;
  13794. const auto &d = *data;
  13795. std::this_thread::sleep_for(std::chrono::seconds(1));
  13796. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13797. return true;
  13798. },
  13799. [data](bool success) {
  13800. EXPECT_FALSE(success);
  13801. delete data;
  13802. });
  13803. });
  13804. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13805. auto i = new size_t(0);
  13806. res.set_content_provider(
  13807. "text/plain",
  13808. [i](size_t, DataSink &sink) {
  13809. if (*i < 5) {
  13810. std::this_thread::sleep_for(std::chrono::seconds(1));
  13811. sink.write("abcd", 4);
  13812. (*i)++;
  13813. } else {
  13814. sink.done();
  13815. }
  13816. return true;
  13817. },
  13818. [i](bool success) {
  13819. EXPECT_FALSE(success);
  13820. delete i;
  13821. });
  13822. });
  13823. svr.Get("/chunked", [&](const Request &, Response &res) {
  13824. auto i = new size_t(0);
  13825. res.set_chunked_content_provider(
  13826. "text/plain",
  13827. [i](size_t, DataSink &sink) {
  13828. if (*i < 5) {
  13829. std::this_thread::sleep_for(std::chrono::seconds(1));
  13830. sink.os << "abcd";
  13831. (*i)++;
  13832. } else {
  13833. sink.done();
  13834. }
  13835. return true;
  13836. },
  13837. [i](bool success) {
  13838. EXPECT_FALSE(success);
  13839. delete i;
  13840. });
  13841. });
  13842. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13843. auto se = detail::scope_exit([&] {
  13844. svr.stop();
  13845. listen_thread.join();
  13846. ASSERT_FALSE(svr.is_running());
  13847. });
  13848. svr.wait_until_ready();
  13849. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13850. {
  13851. auto start = std::chrono::steady_clock::now();
  13852. auto res = cli.Get("/stream");
  13853. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13854. std::chrono::steady_clock::now() - start)
  13855. .count();
  13856. ASSERT_FALSE(res);
  13857. EXPECT_EQ(Error::Read, res.error());
  13858. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13859. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13860. }
  13861. {
  13862. auto start = std::chrono::steady_clock::now();
  13863. auto res = cli.Get("/stream_without_length");
  13864. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13865. std::chrono::steady_clock::now() - start)
  13866. .count();
  13867. ASSERT_FALSE(res);
  13868. EXPECT_EQ(Error::Read, res.error());
  13869. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13870. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13871. }
  13872. {
  13873. auto start = std::chrono::steady_clock::now();
  13874. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13875. EXPECT_EQ("abcd", string(data, data_length));
  13876. return true;
  13877. });
  13878. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13879. std::chrono::steady_clock::now() - start)
  13880. .count();
  13881. ASSERT_FALSE(res);
  13882. EXPECT_EQ(Error::Read, res.error());
  13883. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13884. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13885. }
  13886. }
  13887. TEST(MaxTimeoutTest, ContentStream) {
  13888. time_t timeout = 2000;
  13889. time_t threshold = 200;
  13890. Server svr;
  13891. Client cli("localhost", PORT);
  13892. max_timeout_test(svr, cli, timeout, threshold);
  13893. }
  13894. #ifdef CPPHTTPLIB_SSL_ENABLED
  13895. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13896. time_t timeout = 2000;
  13897. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13899. SSLClient cli("localhost", PORT);
  13900. cli.enable_server_certificate_verification(false);
  13901. max_timeout_test(svr, cli, timeout, threshold);
  13902. }
  13903. #endif
  13904. class EventDispatcher {
  13905. public:
  13906. EventDispatcher() {}
  13907. bool wait_event(DataSink *sink) {
  13908. unique_lock<mutex> lk(m_);
  13909. int id = id_;
  13910. // Wait with timeout to prevent hanging if client disconnects
  13911. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13912. [&] { return cid_ == id; })) {
  13913. return false; // Timeout occurred
  13914. }
  13915. sink->write(message_.data(), message_.size());
  13916. return true;
  13917. }
  13918. void send_event(const string &message) {
  13919. lock_guard<mutex> lk(m_);
  13920. cid_ = id_++;
  13921. message_ = message;
  13922. cv_.notify_all();
  13923. }
  13924. private:
  13925. mutex m_;
  13926. condition_variable cv_;
  13927. atomic_int id_{0};
  13928. atomic_int cid_{-1};
  13929. string message_;
  13930. };
  13931. TEST(ClientInThreadTest, Issue2068) {
  13932. EventDispatcher ed;
  13933. Server svr;
  13934. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13935. res.set_chunked_content_provider("text/event-stream",
  13936. [&](size_t /*offset*/, DataSink &sink) {
  13937. return ed.wait_event(&sink);
  13938. });
  13939. });
  13940. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13941. svr.wait_until_ready();
  13942. thread event_thread([&] {
  13943. int id = 0;
  13944. while (svr.is_running()) {
  13945. this_thread::sleep_for(chrono::milliseconds(500));
  13946. std::stringstream ss;
  13947. ss << "data: " << id << "\n\n";
  13948. ed.send_event(ss.str());
  13949. id++;
  13950. }
  13951. });
  13952. auto se = detail::scope_exit([&] {
  13953. svr.stop();
  13954. listen_thread.join();
  13955. event_thread.join();
  13956. ASSERT_FALSE(svr.is_running());
  13957. });
  13958. {
  13959. auto client = detail::make_unique<Client>(HOST, PORT);
  13960. client->set_read_timeout(std::chrono::minutes(10));
  13961. std::atomic<bool> stop{false};
  13962. std::thread t([&] {
  13963. client->Get("/event1",
  13964. [&](const char *, size_t) -> bool { return !stop; });
  13965. });
  13966. std::this_thread::sleep_for(std::chrono::seconds(2));
  13967. stop = true;
  13968. client->stop();
  13969. t.join();
  13970. // Reset client after thread has finished
  13971. client.reset();
  13972. }
  13973. }
  13974. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13975. auto handled = false;
  13976. Server svr;
  13977. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13978. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13979. auto se = detail::scope_exit([&] {
  13980. svr.stop();
  13981. t.join();
  13982. ASSERT_FALSE(svr.is_running());
  13983. ASSERT_FALSE(handled);
  13984. });
  13985. svr.wait_until_ready();
  13986. // Two Content-Length headers with different values — must be rejected
  13987. auto req = "POST /test HTTP/1.1\r\n"
  13988. "Content-Length: 5\r\n"
  13989. "Content-Length: 10\r\n"
  13990. "\r\n"
  13991. "hello";
  13992. std::string response;
  13993. ASSERT_TRUE(send_request(1, req, &response));
  13994. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13995. response.substr(0, response.find("\r\n")));
  13996. }
  13997. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13998. auto handled = false;
  13999. Server svr;
  14000. svr.Post("/test", [&](const Request &, Response &res) {
  14001. handled = true;
  14002. res.set_content("ok", "text/plain");
  14003. });
  14004. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14005. auto se = detail::scope_exit([&] {
  14006. svr.stop();
  14007. t.join();
  14008. ASSERT_FALSE(svr.is_running());
  14009. ASSERT_TRUE(handled);
  14010. });
  14011. svr.wait_until_ready();
  14012. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  14013. auto req = "POST /test HTTP/1.1\r\n"
  14014. "Content-Length: 5\r\n"
  14015. "Content-Length: 5\r\n"
  14016. "\r\n"
  14017. "hello";
  14018. std::string response;
  14019. ASSERT_TRUE(send_request(1, req, &response));
  14020. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  14021. }
  14022. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  14023. Server svr;
  14024. svr.Get("/", [](const Request &req, Response &res) {
  14025. EXPECT_EQ(2U, req.trailers.size());
  14026. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  14027. // Denied
  14028. EXPECT_FALSE(req.has_trailer("Content-Length"));
  14029. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  14030. // Accepted
  14031. EXPECT_TRUE(req.has_trailer("X-Hello"));
  14032. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  14033. EXPECT_TRUE(req.has_trailer("X-World"));
  14034. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  14035. res.set_content("ok", "text/plain");
  14036. });
  14037. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14038. auto se = detail::scope_exit([&] {
  14039. svr.stop();
  14040. t.join();
  14041. ASSERT_FALSE(svr.is_running());
  14042. });
  14043. svr.wait_until_ready();
  14044. const std::string req = "GET / HTTP/1.1\r\n"
  14045. "Transfer-Encoding: chunked\r\n"
  14046. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  14047. "\r\n"
  14048. "0\r\n"
  14049. "Content-Length: 10\r\n"
  14050. "Host: internal.local\r\n"
  14051. "Content-Type: malicious/content\r\n"
  14052. "Cookie: any\r\n"
  14053. "Set-Cookie: any\r\n"
  14054. "X-Forwarded-For: attacker.com\r\n"
  14055. "X-Real-Ip: 1.1.1.1\r\n"
  14056. "X-Hello: hello\r\n"
  14057. "X-World: world\r\n"
  14058. "\r\n";
  14059. std::string res;
  14060. ASSERT_TRUE(send_request(1, req, &res));
  14061. }
  14062. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  14063. // several field lines, and the combined value is what has to be parsed. A
  14064. // Trailer field split across lines therefore declares every name it lists;
  14065. // reading only the first line silently drops the trailers the later lines
  14066. // declare. The prohibited-trailer filter still applies to every line.
  14067. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  14068. Server svr;
  14069. size_t observed_trailer_count = 0;
  14070. std::string observed_hello;
  14071. std::string observed_world;
  14072. bool observed_content_length = true;
  14073. svr.Get("/", [&](const Request &req, Response &res) {
  14074. observed_trailer_count = req.trailers.size();
  14075. observed_hello = req.get_trailer_value("X-Hello");
  14076. observed_world = req.get_trailer_value("X-World");
  14077. observed_content_length = req.has_trailer("Content-Length");
  14078. res.set_content("ok", "text/plain");
  14079. });
  14080. auto port = svr.bind_to_any_port(HOST);
  14081. thread t = thread([&]() { svr.listen_after_bind(); });
  14082. auto se = detail::scope_exit([&] {
  14083. svr.stop();
  14084. t.join();
  14085. ASSERT_FALSE(svr.is_running());
  14086. });
  14087. svr.wait_until_ready();
  14088. const std::string req = "GET / HTTP/1.1\r\n"
  14089. "Transfer-Encoding: chunked\r\n"
  14090. "Trailer: X-Hello\r\n"
  14091. "Trailer: X-World, Content-Length\r\n"
  14092. "\r\n"
  14093. "0\r\n"
  14094. "X-Hello: hello\r\n"
  14095. "X-World: world\r\n"
  14096. "Content-Length: 10\r\n"
  14097. "\r\n";
  14098. std::string res;
  14099. ASSERT_TRUE(send_request(1, req, &res, port));
  14100. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  14101. // Accepted: both field lines contribute to the declared set
  14102. EXPECT_EQ(2U, observed_trailer_count);
  14103. EXPECT_EQ(observed_hello, "hello");
  14104. EXPECT_EQ(observed_world, "world");
  14105. // Denied: a prohibited name stays prohibited on a later field line
  14106. EXPECT_FALSE(observed_content_length);
  14107. }
  14108. // A direct client that is not listed in trusted_proxies must not be able to
  14109. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  14110. // the peer address on the actual TCP connection determines whether the
  14111. // header is honored.
  14112. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  14113. Server svr;
  14114. // Deliberately does NOT include the loopback address the test client
  14115. // actually connects from, so the direct connection is not a trusted proxy.
  14116. svr.set_trusted_proxies({"203.0.113.66"});
  14117. std::string observed_remote_addr;
  14118. svr.Get("/ip", [&](const Request &req, Response &res) {
  14119. observed_remote_addr = req.remote_addr;
  14120. res.set_content("ok", "text/plain");
  14121. });
  14122. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14123. auto se = detail::scope_exit([&] {
  14124. svr.stop();
  14125. t.join();
  14126. ASSERT_FALSE(svr.is_running());
  14127. });
  14128. svr.wait_until_ready();
  14129. Client cli(HOST, PORT);
  14130. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  14131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14132. EXPECT_EQ(StatusCode::OK_200, res->status);
  14133. // The connecting peer is not a trusted proxy, so the spoofed header must be
  14134. // ignored entirely and the real connection-level address retained.
  14135. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14136. observed_remote_addr == "127.0.0.1");
  14137. }
  14138. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  14139. Server svr;
  14140. std::string observed_remote_addr;
  14141. std::string observed_xff;
  14142. svr.Get("/ip", [&](const Request &req, Response &res) {
  14143. observed_remote_addr = req.remote_addr;
  14144. observed_xff = req.get_header_value("X-Forwarded-For");
  14145. res.set_content("ok", "text/plain");
  14146. });
  14147. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14148. auto se = detail::scope_exit([&] {
  14149. svr.stop();
  14150. t.join();
  14151. ASSERT_FALSE(svr.is_running());
  14152. });
  14153. svr.wait_until_ready();
  14154. Client cli(HOST, PORT);
  14155. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  14156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14157. EXPECT_EQ(StatusCode::OK_200, res->status);
  14158. EXPECT_EQ(observed_xff, "203.0.113.66");
  14159. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14160. observed_remote_addr == "127.0.0.1");
  14161. }
  14162. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  14163. Server svr;
  14164. svr.set_trusted_proxies({"203.0.113.66"});
  14165. std::string observed_remote_addr;
  14166. std::string observed_xff;
  14167. svr.Get("/ip", [&](const Request &req, Response &res) {
  14168. observed_remote_addr = req.remote_addr;
  14169. observed_xff = req.get_header_value("X-Forwarded-For");
  14170. res.set_content("ok", "text/plain");
  14171. });
  14172. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14173. auto se = detail::scope_exit([&] {
  14174. svr.stop();
  14175. t.join();
  14176. ASSERT_FALSE(svr.is_running());
  14177. });
  14178. svr.wait_until_ready();
  14179. Client cli(HOST, PORT);
  14180. auto res = cli.Get("/ip");
  14181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14182. EXPECT_EQ(StatusCode::OK_200, res->status);
  14183. EXPECT_EQ(observed_xff, "");
  14184. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14185. observed_remote_addr == "127.0.0.1");
  14186. }
  14187. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  14188. Server svr;
  14189. // Include the loopback address the test client actually connects from, so
  14190. // the direct connection itself is recognized as the trusted proxy hop.
  14191. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  14192. std::string observed_remote_addr;
  14193. std::string observed_xff;
  14194. svr.Get("/ip", [&](const Request &req, Response &res) {
  14195. observed_remote_addr = req.remote_addr;
  14196. observed_xff = req.get_header_value("X-Forwarded-For");
  14197. res.set_content("ok", "text/plain");
  14198. });
  14199. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14200. auto se = detail::scope_exit([&] {
  14201. svr.stop();
  14202. t.join();
  14203. ASSERT_FALSE(svr.is_running());
  14204. });
  14205. svr.wait_until_ready();
  14206. Client cli(HOST, PORT);
  14207. auto res = cli.Get(
  14208. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  14209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14210. EXPECT_EQ(StatusCode::OK_200, res->status);
  14211. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  14212. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14213. }
  14214. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  14215. Server svr;
  14216. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  14217. std::string observed_remote_addr;
  14218. std::string observed_xff;
  14219. svr.Get("/ip", [&](const Request &req, Response &res) {
  14220. observed_remote_addr = req.remote_addr;
  14221. observed_xff = req.get_header_value("X-Forwarded-For");
  14222. res.set_content("ok", "text/plain");
  14223. });
  14224. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14225. auto se = detail::scope_exit([&] {
  14226. svr.stop();
  14227. t.join();
  14228. ASSERT_FALSE(svr.is_running());
  14229. });
  14230. svr.wait_until_ready();
  14231. Client cli(HOST, PORT);
  14232. auto res = cli.Get(
  14233. "/ip",
  14234. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14236. EXPECT_EQ(StatusCode::OK_200, res->status);
  14237. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14238. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14239. }
  14240. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  14241. Server svr;
  14242. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14243. std::string observed_remote_addr;
  14244. std::string observed_xff;
  14245. svr.Get("/ip", [&](const Request &req, Response &res) {
  14246. observed_remote_addr = req.remote_addr;
  14247. observed_xff = req.get_header_value("X-Forwarded-For");
  14248. res.set_content("ok", "text/plain");
  14249. });
  14250. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14251. auto se = detail::scope_exit([&] {
  14252. svr.stop();
  14253. t.join();
  14254. ASSERT_FALSE(svr.is_running());
  14255. });
  14256. svr.wait_until_ready();
  14257. Client cli(HOST, PORT);
  14258. auto res = cli.Get(
  14259. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  14260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14261. EXPECT_EQ(StatusCode::OK_200, res->status);
  14262. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  14263. // by the closest hop) is used. The leftmost entry is fully client-controlled
  14264. // and must not be selected.
  14265. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  14266. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  14267. }
  14268. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  14269. Server svr;
  14270. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  14271. std::string observed_remote_addr;
  14272. svr.Get("/ip", [&](const Request &req, Response &res) {
  14273. observed_remote_addr = req.remote_addr;
  14274. res.set_content("ok", "text/plain");
  14275. });
  14276. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14277. auto se = detail::scope_exit([&] {
  14278. svr.stop();
  14279. t.join();
  14280. ASSERT_FALSE(svr.is_running());
  14281. });
  14282. svr.wait_until_ready();
  14283. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  14284. // a forged address and the trusted proxy's own address; the forged value must
  14285. // not win over the address the trusted proxy actually recorded.
  14286. Client cli(HOST, PORT);
  14287. auto res = cli.Get(
  14288. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  14289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14290. EXPECT_EQ(StatusCode::OK_200, res->status);
  14291. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  14292. }
  14293. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  14294. Server svr;
  14295. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14296. std::string observed_remote_addr;
  14297. std::string observed_xff;
  14298. svr.Get("/ip", [&](const Request &req, Response &res) {
  14299. observed_remote_addr = req.remote_addr;
  14300. observed_xff = req.get_header_value("X-Forwarded-For");
  14301. res.set_content("ok", "text/plain");
  14302. });
  14303. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14304. auto se = detail::scope_exit([&] {
  14305. svr.stop();
  14306. t.join();
  14307. ASSERT_FALSE(svr.is_running());
  14308. });
  14309. svr.wait_until_ready();
  14310. Client cli(HOST, PORT);
  14311. auto res = cli.Get(
  14312. "/ip",
  14313. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14315. EXPECT_EQ(StatusCode::OK_200, res->status);
  14316. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14317. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14318. }
  14319. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  14320. Server svr;
  14321. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14322. std::string observed_remote_addr;
  14323. std::string observed_xff;
  14324. svr.Get("/ip", [&](const Request &req, Response &res) {
  14325. observed_remote_addr = req.remote_addr;
  14326. observed_xff = req.get_header_value("X-Forwarded-For");
  14327. res.set_content("ok", "text/plain");
  14328. });
  14329. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14330. auto se = detail::scope_exit([&] {
  14331. svr.stop();
  14332. t.join();
  14333. ASSERT_FALSE(svr.is_running());
  14334. });
  14335. svr.wait_until_ready();
  14336. std::string raw_req =
  14337. "GET /ip HTTP/1.1\r\n"
  14338. "Host: localhost\r\n"
  14339. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  14340. "Connection: close\r\n"
  14341. "\r\n";
  14342. std::string out;
  14343. ASSERT_TRUE(send_request(5, raw_req, &out));
  14344. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14345. // Header parser trims surrounding whitespace of the header value
  14346. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  14347. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14348. }
  14349. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  14350. // one comma-joined value, in the order received. Proxies such as HAProxy append
  14351. // their own X-Forwarded-For as a separate field line rather than extending the
  14352. // one the client sent, so every occurrence has to be taken into account.
  14353. // Reading only the first one hands back the address the client chose.
  14354. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  14355. Server svr;
  14356. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14357. std::string observed_remote_addr;
  14358. size_t observed_xff_count = 0;
  14359. svr.Get("/ip", [&](const Request &req, Response &res) {
  14360. observed_remote_addr = req.remote_addr;
  14361. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  14362. res.set_content("ok", "text/plain");
  14363. });
  14364. auto port = svr.bind_to_any_port(HOST);
  14365. thread t = thread([&]() { svr.listen_after_bind(); });
  14366. auto se = detail::scope_exit([&] {
  14367. svr.stop();
  14368. t.join();
  14369. ASSERT_FALSE(svr.is_running());
  14370. });
  14371. svr.wait_until_ready();
  14372. // The client supplies the first field line; the trusted proxy appends the
  14373. // address it observed as a second one.
  14374. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  14375. "Host: localhost\r\n"
  14376. "X-Forwarded-For: 1.2.3.4\r\n"
  14377. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  14378. "Connection: close\r\n"
  14379. "\r\n";
  14380. std::string out;
  14381. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14382. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14383. EXPECT_EQ(observed_xff_count, 2U);
  14384. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14385. // The same chain spread over one field line per hop derives the same client
  14386. // address, i.e. the split and the comma-joined representations agree.
  14387. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  14388. "Host: localhost\r\n"
  14389. "X-Forwarded-For: 1.2.3.4\r\n"
  14390. "X-Forwarded-For: 198.51.100.23\r\n"
  14391. "X-Forwarded-For: 192.0.2.45\r\n"
  14392. "Connection: close\r\n"
  14393. "\r\n";
  14394. out.clear();
  14395. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  14396. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14397. EXPECT_EQ(observed_xff_count, 3U);
  14398. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14399. }
  14400. // An X-Forwarded-For header whose value parses to zero IP segments must not
  14401. // crash the server (it used to call front() on an empty vector inside
  14402. // get_client_ip). The connection-level remote address must be retained instead.
  14403. static void run_malformed_xff_test(const std::string &xff_value) {
  14404. Server svr;
  14405. svr.set_trusted_proxies({"192.0.2.45"});
  14406. std::string observed_remote_addr;
  14407. svr.Get("/ip", [&](const Request &req, Response &res) {
  14408. observed_remote_addr = req.remote_addr;
  14409. res.set_content("ok", "text/plain");
  14410. });
  14411. int port = 0;
  14412. thread t = thread([&]() {
  14413. port = svr.bind_to_any_port(HOST);
  14414. svr.listen_after_bind();
  14415. });
  14416. auto se = detail::scope_exit([&] {
  14417. svr.stop();
  14418. t.join();
  14419. ASSERT_FALSE(svr.is_running());
  14420. });
  14421. svr.wait_until_ready();
  14422. Client cli(HOST, port);
  14423. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  14424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14425. EXPECT_EQ(StatusCode::OK_200, res->status);
  14426. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14427. observed_remote_addr == "127.0.0.1");
  14428. }
  14429. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  14430. run_malformed_xff_test("");
  14431. }
  14432. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  14433. run_malformed_xff_test(",");
  14434. }
  14435. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  14436. run_malformed_xff_test(", , ,");
  14437. }
  14438. // The same rule applies to Accept: a request whose acceptable types are spread
  14439. // over several field lines must be negotiated against all of them.
  14440. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  14441. // case-insensitive connection options. Comparing the whole field value against
  14442. // one option misses a client that sends several of them, and misses every
  14443. // casing but the one written in the comparison.
  14444. //
  14445. // Sends req, reads the response, then reuses the same socket for a second
  14446. // request to find out whether the server kept the connection.
  14447. static void probe_connection_reuse(int port, const std::string &req,
  14448. bool *announced_close, bool *reusable) {
  14449. auto error = Error::Success;
  14450. auto sock = detail::create_client_socket(
  14451. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  14452. /*connection_timeout_sec=*/5, 0,
  14453. /*read_timeout_sec=*/1, 0,
  14454. /*write_timeout_sec=*/5, 0, std::string(), error);
  14455. ASSERT_NE(sock, INVALID_SOCKET);
  14456. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  14457. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  14458. "Host: localhost\r\n"
  14459. "Connection: close\r\n"
  14460. "\r\n";
  14461. std::string first_response;
  14462. std::string second_response;
  14463. detail::process_client_socket(
  14464. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  14465. [&](Stream &strm) {
  14466. if (strm.write(req.data(), req.size()) !=
  14467. static_cast<ssize_t>(req.size())) {
  14468. return false;
  14469. }
  14470. char buf[512];
  14471. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  14472. // Headers plus the two-byte body of the handler below
  14473. while (reader.getline()) {
  14474. first_response += reader.ptr();
  14475. if (first_response.find("ok") != std::string::npos) { break; }
  14476. }
  14477. if (strm.write(second.data(), second.size()) !=
  14478. static_cast<ssize_t>(second.size())) {
  14479. return true;
  14480. }
  14481. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  14482. while (reader2.getline()) {
  14483. second_response += reader2.ptr();
  14484. if (second_response.find("ok") != std::string::npos) { break; }
  14485. }
  14486. return true;
  14487. });
  14488. *announced_close =
  14489. first_response.find("Connection: close") != std::string::npos;
  14490. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  14491. }
  14492. class ConnectionTokenTest : public ::testing::Test {
  14493. protected:
  14494. void SetUp() override {
  14495. svr_.Get("/keepalive", [](const Request &, Response &res) {
  14496. res.set_content("ok", "text/plain");
  14497. });
  14498. port_ = svr_.bind_to_any_port(HOST);
  14499. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14500. svr_.wait_until_ready();
  14501. }
  14502. void TearDown() override {
  14503. svr_.stop();
  14504. if (thread_.joinable()) { thread_.join(); }
  14505. }
  14506. Server svr_;
  14507. int port_ = 0;
  14508. thread thread_;
  14509. };
  14510. // "close" alongside another option still closes the connection, and the
  14511. // response says so rather than leaving the peer to discover it.
  14512. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  14513. bool announced_close = false;
  14514. bool reusable = true;
  14515. probe_connection_reuse(port_,
  14516. "GET /keepalive HTTP/1.1\r\n"
  14517. "Host: localhost\r\n"
  14518. "Connection: keep-alive, close\r\n"
  14519. "\r\n",
  14520. &announced_close, &reusable);
  14521. EXPECT_TRUE(announced_close);
  14522. EXPECT_FALSE(reusable);
  14523. }
  14524. // "close" split over two field lines is the same list, so it is honored too.
  14525. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  14526. bool announced_close = false;
  14527. bool reusable = true;
  14528. probe_connection_reuse(port_,
  14529. "GET /keepalive HTTP/1.1\r\n"
  14530. "Host: localhost\r\n"
  14531. "Connection: keep-alive\r\n"
  14532. "Connection: close\r\n"
  14533. "\r\n",
  14534. &announced_close, &reusable);
  14535. EXPECT_TRUE(announced_close);
  14536. EXPECT_FALSE(reusable);
  14537. }
  14538. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  14539. // keep-alive in the spelling everyone actually sends keeps its connection.
  14540. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  14541. bool announced_close = false;
  14542. bool reusable = false;
  14543. probe_connection_reuse(port_,
  14544. "GET /keepalive HTTP/1.0\r\n"
  14545. "Host: localhost\r\n"
  14546. "Connection: keep-alive\r\n"
  14547. "\r\n",
  14548. &announced_close, &reusable);
  14549. EXPECT_FALSE(announced_close);
  14550. EXPECT_TRUE(reusable);
  14551. }
  14552. // A token the value merely contains is not the token itself.
  14553. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  14554. bool announced_close = false;
  14555. bool reusable = false;
  14556. probe_connection_reuse(port_,
  14557. "GET /keepalive HTTP/1.1\r\n"
  14558. "Host: localhost\r\n"
  14559. "Connection: notclose\r\n"
  14560. "\r\n",
  14561. &announced_close, &reusable);
  14562. EXPECT_FALSE(announced_close);
  14563. EXPECT_TRUE(reusable);
  14564. }
  14565. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  14566. Server svr;
  14567. std::vector<std::string> observed_types;
  14568. svr.Get("/", [&](const Request &req, Response &res) {
  14569. observed_types = req.accept_content_types;
  14570. res.set_content("ok", "text/plain");
  14571. });
  14572. auto port = svr.bind_to_any_port(HOST);
  14573. thread t = thread([&]() { svr.listen_after_bind(); });
  14574. auto se = detail::scope_exit([&] {
  14575. svr.stop();
  14576. t.join();
  14577. ASSERT_FALSE(svr.is_running());
  14578. });
  14579. svr.wait_until_ready();
  14580. Client cli(HOST, port);
  14581. Headers headers;
  14582. headers.emplace("Accept", "text/plain;q=0.5");
  14583. headers.emplace("Accept", "application/json");
  14584. auto res = cli.Get("/", headers);
  14585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14586. EXPECT_EQ(StatusCode::OK_200, res->status);
  14587. // Sorted by q-value, so the second field line's type comes first
  14588. ASSERT_EQ(2U, observed_types.size());
  14589. EXPECT_EQ("application/json", observed_types[0]);
  14590. EXPECT_EQ("text/plain", observed_types[1]);
  14591. }
  14592. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  14593. // empty field line must not contribute a bare comma to the combined value.
  14594. // parse_accept_header() rejects a leading comma outright, so a stray one would
  14595. // turn a legal request into 400 Bad Request.
  14596. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  14597. Server svr;
  14598. std::vector<std::string> observed_types;
  14599. svr.Get("/", [&](const Request &req, Response &res) {
  14600. observed_types = req.accept_content_types;
  14601. res.set_content("ok", "text/plain");
  14602. });
  14603. auto port = svr.bind_to_any_port(HOST);
  14604. thread t = thread([&]() { svr.listen_after_bind(); });
  14605. auto se = detail::scope_exit([&] {
  14606. svr.stop();
  14607. t.join();
  14608. ASSERT_FALSE(svr.is_running());
  14609. });
  14610. svr.wait_until_ready();
  14611. // Empty first field line, then a real one
  14612. std::string raw_req = "GET / HTTP/1.1\r\n"
  14613. "Host: localhost\r\n"
  14614. "Accept:\r\n"
  14615. "Accept: application/json\r\n"
  14616. "Connection: close\r\n"
  14617. "\r\n";
  14618. std::string out;
  14619. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14620. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14621. ASSERT_EQ(1U, observed_types.size());
  14622. EXPECT_EQ("application/json", observed_types[0]);
  14623. }
  14624. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14625. // An encoding offered on a later Accept-Encoding field line is still offered.
  14626. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  14627. Server svr;
  14628. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14629. res.set_content(std::string(1024, 'x'), "text/plain");
  14630. });
  14631. auto port = svr.bind_to_any_port(HOST);
  14632. thread t = thread([&]() { svr.listen_after_bind(); });
  14633. auto se = detail::scope_exit([&] {
  14634. svr.stop();
  14635. t.join();
  14636. ASSERT_FALSE(svr.is_running());
  14637. });
  14638. svr.wait_until_ready();
  14639. Client cli(HOST, port);
  14640. cli.set_decompress(false);
  14641. Headers headers;
  14642. headers.emplace("Accept-Encoding", "identity");
  14643. headers.emplace("Accept-Encoding", "gzip");
  14644. auto res = cli.Get("/", headers);
  14645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14646. EXPECT_EQ(StatusCode::OK_200, res->status);
  14647. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  14648. }
  14649. #endif
  14650. #ifndef _WIN32
  14651. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  14652. Server svr;
  14653. svr.Post("/post", [&](const Request &req, Response &res) {
  14654. res.set_content(req.body, "text/plain");
  14655. });
  14656. svr.Put("/put", [&](const Request &req, Response &res) {
  14657. res.set_content(req.body, "text/plain");
  14658. });
  14659. svr.Patch("/patch", [&](const Request &req, Response &res) {
  14660. res.set_content(req.body, "text/plain");
  14661. });
  14662. svr.Delete("/delete", [&](const Request &req, Response &res) {
  14663. res.set_content(req.body, "text/plain");
  14664. });
  14665. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14666. auto se = detail::scope_exit([&] {
  14667. svr.stop();
  14668. t.join();
  14669. ASSERT_FALSE(svr.is_running());
  14670. });
  14671. svr.wait_until_ready();
  14672. std::string resp;
  14673. // POST without Content-Length
  14674. ASSERT_TRUE(send_request(5,
  14675. "POST /post 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. // PUT without Content-Length
  14682. resp.clear();
  14683. ASSERT_TRUE(send_request(5,
  14684. "PUT /put 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. // PATCH without Content-Length
  14691. resp.clear();
  14692. ASSERT_TRUE(send_request(5,
  14693. "PATCH /patch HTTP/1.1\r\n"
  14694. "Host: localhost\r\n"
  14695. "Connection: close\r\n"
  14696. "\r\n",
  14697. &resp));
  14698. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14699. // DELETE without Content-Length
  14700. resp.clear();
  14701. ASSERT_TRUE(send_request(5,
  14702. "DELETE /delete HTTP/1.1\r\n"
  14703. "Host: localhost\r\n"
  14704. "Connection: close\r\n"
  14705. "\r\n",
  14706. &resp));
  14707. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14708. }
  14709. #endif
  14710. //==============================================================================
  14711. // open_stream() Tests
  14712. //==============================================================================
  14713. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  14714. std::string result;
  14715. char buf[8192];
  14716. ssize_t n;
  14717. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14718. result.append(buf, static_cast<size_t>(n));
  14719. }
  14720. return result;
  14721. }
  14722. // Mock stream for unit tests
  14723. class MockStream : public Stream {
  14724. public:
  14725. std::string data;
  14726. size_t pos = 0;
  14727. ssize_t error_after = -1; // -1 = no error
  14728. explicit MockStream(const std::string &d, ssize_t err = -1)
  14729. : data(d), error_after(err) {}
  14730. bool is_readable() const override { return true; }
  14731. bool wait_readable() const override { return true; }
  14732. bool wait_writable() const override { return true; }
  14733. ssize_t read(char *ptr, size_t size) override {
  14734. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  14735. if (pos >= data.size()) return 0;
  14736. size_t limit =
  14737. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  14738. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  14739. std::memcpy(ptr, data.data() + pos, to_read);
  14740. pos += to_read;
  14741. return static_cast<ssize_t>(to_read);
  14742. }
  14743. ssize_t write(const char *, size_t) override { return -1; }
  14744. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  14745. ip = "127.0.0.1";
  14746. port = 0;
  14747. }
  14748. void get_local_ip_and_port(std::string &ip, int &port) const override {
  14749. ip = "127.0.0.1";
  14750. port = 0;
  14751. }
  14752. socket_t socket() const override { return INVALID_SOCKET; }
  14753. time_t duration() const override { return 0; }
  14754. };
  14755. TEST(StreamHandleTest, Basic) {
  14756. ClientImpl::StreamHandle handle;
  14757. EXPECT_FALSE(handle.is_valid());
  14758. handle.response = detail::make_unique<Response>();
  14759. handle.error = Error::Connection;
  14760. EXPECT_FALSE(handle.is_valid());
  14761. handle.error = Error::Success;
  14762. EXPECT_TRUE(handle.is_valid());
  14763. }
  14764. TEST(BodyReaderTest, Basic) {
  14765. MockStream stream("Hello, World!");
  14766. detail::BodyReader reader;
  14767. reader.stream = &stream;
  14768. reader.content_length = 13;
  14769. char buf[32];
  14770. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  14771. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  14772. EXPECT_TRUE(reader.eof);
  14773. }
  14774. TEST(BodyReaderTest, NoStream) {
  14775. detail::BodyReader reader;
  14776. char buf[32];
  14777. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14778. EXPECT_EQ(Error::Connection, reader.last_error);
  14779. }
  14780. TEST(BodyReaderTest, Error) {
  14781. MockStream stream("Hello, World!", 5);
  14782. detail::BodyReader reader;
  14783. reader.stream = &stream;
  14784. reader.content_length = 13;
  14785. char buf[32];
  14786. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  14787. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14788. EXPECT_EQ(Error::Read, reader.last_error);
  14789. }
  14790. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  14791. // Mock-based StreamHandle tests relying on private internals are removed.
  14792. class OpenStreamTest : public ::testing::Test {
  14793. protected:
  14794. void SetUp() override {
  14795. svr_.Get("/hello", [](const Request &, Response &res) {
  14796. res.set_content("Hello World!", "text/plain");
  14797. });
  14798. svr_.Get("/large", [](const Request &, Response &res) {
  14799. res.set_content(std::string(10000, 'X'), "text/plain");
  14800. });
  14801. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  14802. res.set_content("Hello World!", "image/jpeg");
  14803. res.set_header("Content-Encoding", "UTF-8");
  14804. });
  14805. svr_.Get("/chunked", [](const Request &, Response &res) {
  14806. res.set_chunked_content_provider("text/plain",
  14807. [](size_t offset, DataSink &sink) {
  14808. if (offset < 15) {
  14809. sink.write("chunk", 5);
  14810. return true;
  14811. }
  14812. sink.done();
  14813. return true;
  14814. });
  14815. });
  14816. svr_.Get("/compressible", [](const Request &, Response &res) {
  14817. res.set_chunked_content_provider("text/plain", [](size_t offset,
  14818. DataSink &sink) {
  14819. if (offset < 100 * 1024) {
  14820. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  14821. sink.write(chunk.data(), chunk.size());
  14822. return true;
  14823. }
  14824. sink.done();
  14825. return true;
  14826. });
  14827. });
  14828. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  14829. [](const Request & /*req*/, Response &res) {
  14830. auto i = new int(0);
  14831. res.set_header("Trailer", "Content-Length, X-Allowed");
  14832. res.set_chunked_content_provider(
  14833. "text/plain",
  14834. [i](size_t /*offset*/, DataSink &sink) {
  14835. switch (*i) {
  14836. case 0: sink.os << "123"; break;
  14837. case 1: sink.os << "456"; break;
  14838. case 2: sink.os << "789"; break;
  14839. case 3: {
  14840. sink.done_with_trailer(
  14841. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  14842. } break;
  14843. }
  14844. (*i)++;
  14845. return true;
  14846. },
  14847. [i](bool success) {
  14848. EXPECT_TRUE(success);
  14849. delete i;
  14850. });
  14851. });
  14852. // Echo headers endpoint for header-related tests
  14853. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  14854. std::string body;
  14855. for (const auto &h : req.headers) {
  14856. body.append(h.first);
  14857. body.push_back(':');
  14858. body.append(h.second);
  14859. body.push_back('\n');
  14860. }
  14861. res.set_content(body, "text/plain");
  14862. });
  14863. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  14864. std::string body;
  14865. for (const auto &h : req.headers) {
  14866. body.append(h.first);
  14867. body.push_back(':');
  14868. body.append(h.second);
  14869. body.push_back('\n');
  14870. }
  14871. res.set_content(body, "text/plain");
  14872. });
  14873. port_ = svr_.bind_to_any_port("127.0.0.1");
  14874. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14875. svr_.wait_until_ready();
  14876. }
  14877. void TearDown() override {
  14878. svr_.stop();
  14879. if (thread_.joinable()) thread_.join();
  14880. }
  14881. Server svr_;
  14882. std::thread thread_;
  14883. int port_ = 0;
  14884. };
  14885. TEST_F(OpenStreamTest, Basic) {
  14886. Client cli("127.0.0.1", port_);
  14887. auto handle = cli.open_stream("GET", "/hello");
  14888. EXPECT_TRUE(handle.is_valid());
  14889. EXPECT_EQ("Hello World!", read_all(handle));
  14890. }
  14891. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  14892. Client cli("127.0.0.1", port_);
  14893. auto handle = cli.open_stream("GET", "/unknown-encoding");
  14894. ASSERT_TRUE(handle.is_valid());
  14895. EXPECT_EQ("Hello World!", read_all(handle));
  14896. }
  14897. TEST_F(OpenStreamTest, SmallBuffer) {
  14898. Client cli("127.0.0.1", port_);
  14899. auto handle = cli.open_stream("GET", "/hello");
  14900. std::string result;
  14901. char buf[4];
  14902. ssize_t n;
  14903. while ((n = handle.read(buf, sizeof(buf))) > 0)
  14904. result.append(buf, static_cast<size_t>(n));
  14905. EXPECT_EQ("Hello World!", result);
  14906. }
  14907. TEST_F(OpenStreamTest, DefaultHeaders) {
  14908. Client cli("127.0.0.1", port_);
  14909. // open_stream GET should include Host, User-Agent and Accept-Encoding
  14910. {
  14911. auto handle = cli.open_stream("GET", "/echo-headers");
  14912. ASSERT_TRUE(handle.is_valid());
  14913. auto body = read_all(handle);
  14914. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  14915. std::string::npos);
  14916. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  14917. std::string::npos);
  14918. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  14919. }
  14920. // open_stream POST with body and no explicit content_type should NOT add
  14921. // text/plain Content-Type (behavior differs from non-streaming path), but
  14922. // should include Content-Length
  14923. {
  14924. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  14925. ASSERT_TRUE(handle.is_valid());
  14926. auto body = read_all(handle);
  14927. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  14928. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  14929. }
  14930. // open_stream POST with explicit Content-Type should preserve it
  14931. {
  14932. auto handle = cli.open_stream("POST", "/echo-headers", {},
  14933. {{"Content-Type", "application/custom"}},
  14934. "{}", "application/custom");
  14935. ASSERT_TRUE(handle.is_valid());
  14936. auto body = read_all(handle);
  14937. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  14938. }
  14939. // User-specified User-Agent must not be overwritten for stream API
  14940. {
  14941. auto handle = cli.open_stream("GET", "/echo-headers", {},
  14942. {{"User-Agent", "MyAgent/1.2"}});
  14943. ASSERT_TRUE(handle.is_valid());
  14944. auto body = read_all(handle);
  14945. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  14946. }
  14947. }
  14948. TEST_F(OpenStreamTest, Large) {
  14949. Client cli("127.0.0.1", port_);
  14950. auto handle = cli.open_stream("GET", "/large");
  14951. EXPECT_EQ(10000u, read_all(handle).size());
  14952. }
  14953. TEST_F(OpenStreamTest, ConnectionError) {
  14954. Client cli("127.0.0.1", 9999);
  14955. auto handle = cli.open_stream("GET", "/hello");
  14956. EXPECT_FALSE(handle.is_valid());
  14957. }
  14958. TEST_F(OpenStreamTest, Chunked) {
  14959. Client cli("127.0.0.1", port_);
  14960. auto handle = cli.open_stream("GET", "/chunked");
  14961. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14962. "Transfer-Encoding") == "chunked");
  14963. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  14964. }
  14965. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  14966. Client cli("127.0.0.1", port_);
  14967. auto handle =
  14968. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  14969. ASSERT_TRUE(handle.is_valid());
  14970. // Consume body to allow trailers to be received/parsed
  14971. auto body = read_all(handle);
  14972. // Explicitly parse trailers (ensure trailers are available for assertion)
  14973. handle.parse_trailers_if_needed();
  14974. EXPECT_EQ(std::string("123456789"), body);
  14975. // The response should include a Trailer header declaring both names
  14976. ASSERT_TRUE(handle.response);
  14977. EXPECT_TRUE(handle.response->has_header("Trailer"));
  14978. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  14979. handle.response->get_header_value("Trailer"));
  14980. // Prohibited trailer must not be present
  14981. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  14982. // Allowed trailer should be present
  14983. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  14984. EXPECT_EQ(std::string("yes"),
  14985. handle.response->get_trailer_value("X-Allowed"));
  14986. // Verify trailers are NOT present as regular headers
  14987. EXPECT_EQ(std::string(""),
  14988. handle.response->get_header_value("Content-Length"));
  14989. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  14990. }
  14991. static std::thread serve_single_response(std::promise<int> &port_promise,
  14992. const std::string &response) {
  14993. return std::thread([&port_promise, response] {
  14994. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14995. default_socket_options(srv);
  14996. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14997. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14998. sockaddr_in addr{};
  14999. addr.sin_family = AF_INET;
  15000. addr.sin_port = htons(0); // Let OS assign a free port
  15001. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15002. int opt = 1;
  15003. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  15004. #ifdef _WIN32
  15005. reinterpret_cast<const char *>(&opt),
  15006. #else
  15007. &opt,
  15008. #endif
  15009. sizeof(opt));
  15010. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  15011. ::listen(srv, 1) != 0) {
  15012. port_promise.set_value(-1);
  15013. detail::close_socket(srv);
  15014. return;
  15015. }
  15016. socklen_t addr_len = sizeof(addr);
  15017. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  15018. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  15019. sockaddr_in cli_addr{};
  15020. socklen_t cli_len = sizeof(cli_addr);
  15021. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15022. if (cli != INVALID_SOCKET) {
  15023. // Read the complete HTTP request (until the blank line that terminates
  15024. // headers) before sending the response. If the server closes the socket
  15025. // while the client's request data is still unread in the kernel receive
  15026. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  15027. // connection on both sides: it discards the client's receive buffer
  15028. // (which already holds our response) and causes any in-progress write on
  15029. // the client to fail with ECONNRESET. Reading all request data first
  15030. // ensures close() emits a graceful FIN.
  15031. {
  15032. char rbuf[256];
  15033. std::string req;
  15034. while (req.find("\r\n\r\n") == std::string::npos) {
  15035. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  15036. if (n <= 0) { break; }
  15037. req.append(rbuf, static_cast<size_t>(n));
  15038. }
  15039. }
  15040. ::send(cli,
  15041. #ifdef _WIN32
  15042. static_cast<const char *>(response.c_str()),
  15043. static_cast<int>(response.size()),
  15044. #else
  15045. response.c_str(), response.size(),
  15046. #endif
  15047. 0);
  15048. detail::close_socket(cli);
  15049. }
  15050. detail::close_socket(srv);
  15051. });
  15052. }
  15053. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  15054. #ifndef _WIN32
  15055. signal(SIGPIPE, SIG_IGN);
  15056. #endif
  15057. std::promise<int> port_promise;
  15058. auto port_future = port_promise.get_future();
  15059. auto server_thread =
  15060. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  15061. "Content-Type: text/plain\r\n"
  15062. "Content-Length: not-a-number\r\n"
  15063. "Connection: close\r\n"
  15064. "\r\n"
  15065. "hello");
  15066. auto port = port_future.get();
  15067. ASSERT_GT(port, 0);
  15068. Client cli("127.0.0.1", port);
  15069. auto handle = cli.open_stream("GET", "/");
  15070. EXPECT_FALSE(handle.is_valid());
  15071. server_thread.join();
  15072. }
  15073. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  15074. #ifndef _WIN32
  15075. signal(SIGPIPE, SIG_IGN);
  15076. #endif
  15077. std::promise<int> port_promise;
  15078. auto port_future = port_promise.get_future();
  15079. auto server_thread = serve_single_response(
  15080. port_promise, "HTTP/1.1 200 OK\r\n"
  15081. "Content-Type: text/plain\r\n"
  15082. "Content-Length: 99999999999999999999999999\r\n"
  15083. "Connection: close\r\n"
  15084. "\r\n"
  15085. "hello");
  15086. auto port = port_future.get();
  15087. ASSERT_GT(port, 0);
  15088. // Historically std::stoull would throw std::out_of_range here and crash
  15089. // the process, then parsing silently clamped to a bogus framing length and
  15090. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  15091. // so the stream fails to open, matching the not-a-number case above. The
  15092. // process still must NOT terminate.
  15093. Client cli("127.0.0.1", port);
  15094. auto handle = cli.open_stream("GET", "/");
  15095. EXPECT_FALSE(handle.is_valid());
  15096. server_thread.join();
  15097. }
  15098. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15099. TEST_F(OpenStreamTest, Gzip) {
  15100. Client cli("127.0.0.1", port_);
  15101. auto handle = cli.open_stream("GET", "/compressible", {},
  15102. {{"Accept-Encoding", "gzip"}});
  15103. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  15104. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15105. }
  15106. #endif
  15107. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15108. TEST_F(OpenStreamTest, Brotli) {
  15109. Client cli("127.0.0.1", port_);
  15110. auto handle =
  15111. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  15112. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  15113. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15114. }
  15115. #endif
  15116. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15117. TEST_F(OpenStreamTest, Zstd) {
  15118. Client cli("127.0.0.1", port_);
  15119. auto handle = cli.open_stream("GET", "/compressible", {},
  15120. {{"Accept-Encoding", "zstd"}});
  15121. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  15122. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15123. }
  15124. #endif
  15125. #ifdef CPPHTTPLIB_SSL_ENABLED
  15126. class SSLOpenStreamTest : public ::testing::Test {
  15127. protected:
  15128. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  15129. void SetUp() override {
  15130. svr_.Get("/hello", [](const Request &, Response &res) {
  15131. res.set_content("Hello SSL World!", "text/plain");
  15132. });
  15133. svr_.Get("/chunked", [](const Request &, Response &res) {
  15134. res.set_chunked_content_provider("text/plain",
  15135. [](size_t offset, DataSink &sink) {
  15136. if (offset < 15) {
  15137. sink.write("chunk", 5);
  15138. return true;
  15139. }
  15140. sink.done();
  15141. return true;
  15142. });
  15143. });
  15144. svr_.Post("/echo", [](const Request &req, Response &res) {
  15145. res.set_content(req.body, req.get_header_value("Content-Type"));
  15146. });
  15147. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  15148. std::string body = req.body;
  15149. res.set_chunked_content_provider(
  15150. "text/plain", [body](size_t offset, DataSink &sink) {
  15151. if (offset < body.size()) {
  15152. sink.write(body.data() + offset, body.size() - offset);
  15153. }
  15154. sink.done();
  15155. return true;
  15156. });
  15157. });
  15158. port_ = svr_.bind_to_any_port("127.0.0.1");
  15159. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15160. svr_.wait_until_ready();
  15161. }
  15162. void TearDown() override {
  15163. svr_.stop();
  15164. if (thread_.joinable()) thread_.join();
  15165. }
  15166. SSLServer svr_;
  15167. std::thread thread_;
  15168. int port_ = 0;
  15169. };
  15170. TEST_F(SSLOpenStreamTest, Basic) {
  15171. SSLClient cli("127.0.0.1", port_);
  15172. cli.enable_server_certificate_verification(false);
  15173. auto handle = cli.open_stream("GET", "/hello");
  15174. ASSERT_TRUE(handle.is_valid());
  15175. EXPECT_EQ("Hello SSL World!", read_all(handle));
  15176. }
  15177. TEST_F(SSLOpenStreamTest, Chunked) {
  15178. SSLClient cli("127.0.0.1", port_);
  15179. cli.enable_server_certificate_verification(false);
  15180. auto handle = cli.open_stream("GET", "/chunked");
  15181. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15182. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15183. "Transfer-Encoding") == "chunked");
  15184. auto body = read_all(handle);
  15185. EXPECT_EQ("chunkchunkchunk", body);
  15186. }
  15187. TEST_F(SSLOpenStreamTest, Post) {
  15188. SSLClient cli("127.0.0.1", port_);
  15189. cli.enable_server_certificate_verification(false);
  15190. auto handle =
  15191. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  15192. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15193. EXPECT_EQ(200, handle.response->status);
  15194. auto body = read_all(handle);
  15195. EXPECT_EQ("Hello SSL POST", body);
  15196. }
  15197. TEST_F(SSLOpenStreamTest, PostChunked) {
  15198. SSLClient cli("127.0.0.1", port_);
  15199. cli.enable_server_certificate_verification(false);
  15200. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  15201. "Chunked SSL Data", "text/plain");
  15202. ASSERT_TRUE(handle.is_valid());
  15203. EXPECT_EQ(200, handle.response->status);
  15204. auto body = read_all(handle);
  15205. EXPECT_EQ("Chunked SSL Data", body);
  15206. }
  15207. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  15208. // Content-Length is terminated by the server closing the connection. When the
  15209. // SSL peer sends a close_notify after the body, the client must treat it as a
  15210. // clean EOF and return a successful response rather than an error.
  15211. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  15212. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15213. ASSERT_TRUE(svr.is_valid());
  15214. svr.set_keep_alive_max_count(1);
  15215. const std::string expected_body = "Hello from connection-close response!";
  15216. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  15217. res.set_content_provider("text/plain",
  15218. [&](size_t offset, DataSink &sink) -> bool {
  15219. if (offset < expected_body.size()) {
  15220. sink.write(expected_body.data() + offset,
  15221. expected_body.size() - offset);
  15222. }
  15223. sink.done();
  15224. return true;
  15225. });
  15226. });
  15227. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  15228. auto se = detail::scope_exit([&] {
  15229. svr.stop();
  15230. listen_thread.join();
  15231. ASSERT_FALSE(svr.is_running());
  15232. });
  15233. svr.wait_until_ready();
  15234. SSLClient cli(HOST, PORT);
  15235. cli.enable_server_certificate_verification(false);
  15236. auto res = cli.Get("/no-content-length");
  15237. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  15238. EXPECT_EQ(StatusCode::OK_200, res->status);
  15239. EXPECT_EQ(expected_body, res->body);
  15240. }
  15241. #endif // CPPHTTPLIB_SSL_ENABLED
  15242. //==============================================================================
  15243. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  15244. // results for various scenarios.
  15245. //==============================================================================
  15246. TEST(ParityTest, GetVsOpenStream) {
  15247. Server svr;
  15248. const std::string path = "/parity";
  15249. const std::string content = "Parity test content: hello world";
  15250. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15251. res.set_content(content, "text/plain");
  15252. });
  15253. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15254. auto se = detail::scope_exit([&] {
  15255. svr.stop();
  15256. t.join();
  15257. ASSERT_FALSE(svr.is_running());
  15258. });
  15259. svr.wait_until_ready();
  15260. Client cli(HOST, PORT);
  15261. // Non-stream path
  15262. auto r1 = cli.Get(path);
  15263. ASSERT_TRUE(r1);
  15264. EXPECT_EQ(StatusCode::OK_200, r1->status);
  15265. // Stream path
  15266. auto h = cli.open_stream("GET", path);
  15267. ASSERT_TRUE(h.is_valid());
  15268. EXPECT_EQ(r1->body, read_all(h));
  15269. }
  15270. // Helper to compress data with provided compressor type T
  15271. template <typename Compressor>
  15272. static std::string compress_payload_for_parity(const std::string &in) {
  15273. std::string out;
  15274. Compressor compressor;
  15275. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  15276. [&](const char *data, size_t n) {
  15277. out.append(data, n);
  15278. return true;
  15279. });
  15280. EXPECT_TRUE(ok);
  15281. return out;
  15282. }
  15283. // Helper function for compression parity tests
  15284. template <typename Compressor>
  15285. static void test_compression_parity(const std::string &original,
  15286. const std::string &path,
  15287. const std::string &encoding) {
  15288. const std::string compressed =
  15289. compress_payload_for_parity<Compressor>(original);
  15290. Server svr;
  15291. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15292. res.set_content(compressed, "application/octet-stream");
  15293. res.set_header("Content-Encoding", encoding);
  15294. });
  15295. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  15296. auto se = detail::scope_exit([&] {
  15297. svr.stop();
  15298. t.join();
  15299. ASSERT_FALSE(svr.is_running());
  15300. });
  15301. svr.wait_until_ready();
  15302. Client cli(HOST, PORT);
  15303. // Non-streaming
  15304. {
  15305. auto res = cli.Get(path);
  15306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15307. EXPECT_EQ(StatusCode::OK_200, res->status);
  15308. EXPECT_EQ(original, res->body);
  15309. }
  15310. // Streaming
  15311. {
  15312. auto h = cli.open_stream("GET", path);
  15313. ASSERT_TRUE(h.is_valid());
  15314. EXPECT_EQ(original, read_all(h));
  15315. }
  15316. }
  15317. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15318. TEST(ParityTest, Gzip) {
  15319. test_compression_parity<detail::gzip_compressor>(
  15320. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  15321. }
  15322. #endif
  15323. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15324. TEST(ParityTest, Brotli) {
  15325. test_compression_parity<detail::brotli_compressor>(
  15326. "Hello, brotli parity test payload", "/parity-br", "br");
  15327. }
  15328. #endif
  15329. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15330. TEST(ParityTest, Zstd) {
  15331. test_compression_parity<detail::zstd_compressor>(
  15332. "Zstandard parity test payload", "/parity-zstd", "zstd");
  15333. }
  15334. #endif
  15335. //==============================================================================
  15336. // New Stream API Tests
  15337. //==============================================================================
  15338. inline std::string read_body(httplib::stream::Result &result) {
  15339. std::string body;
  15340. while (result.next()) {
  15341. body.append(result.data(), result.size());
  15342. }
  15343. return body;
  15344. }
  15345. TEST(ClientConnectionTest, Basic) {
  15346. httplib::ClientConnection conn;
  15347. EXPECT_FALSE(conn.is_open());
  15348. conn.sock = 1;
  15349. EXPECT_TRUE(conn.is_open());
  15350. httplib::ClientConnection conn2(std::move(conn));
  15351. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  15352. conn2.sock = INVALID_SOCKET;
  15353. }
  15354. // Unified test server for all stream::* tests
  15355. class StreamApiTest : public ::testing::Test {
  15356. protected:
  15357. void SetUp() override {
  15358. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15359. res.set_content("Hello World!", "text/plain");
  15360. });
  15361. svr_.Get("/echo-params",
  15362. [](const httplib::Request &req, httplib::Response &res) {
  15363. std::string r;
  15364. for (const auto &p : req.params) {
  15365. if (!r.empty()) r += "&";
  15366. r += p.first + "=" + p.second;
  15367. }
  15368. res.set_content(r, "text/plain");
  15369. });
  15370. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15371. res.set_content(req.body, req.get_header_value("Content-Type"));
  15372. });
  15373. svr_.Post("/echo-headers",
  15374. [](const httplib::Request &req, httplib::Response &res) {
  15375. std::string r;
  15376. for (const auto &h : req.headers)
  15377. r += h.first + ": " + h.second + "\n";
  15378. res.set_content(r, "text/plain");
  15379. });
  15380. svr_.Post("/echo-params",
  15381. [](const httplib::Request &req, httplib::Response &res) {
  15382. std::string r = "params:";
  15383. for (const auto &p : req.params)
  15384. r += p.first + "=" + p.second + ";";
  15385. res.set_content(r + " body:" + req.body, "text/plain");
  15386. });
  15387. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  15388. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  15389. });
  15390. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15391. res.set_content("PUT:" + req.body, "text/plain");
  15392. });
  15393. svr_.Patch("/echo",
  15394. [](const httplib::Request &req, httplib::Response &res) {
  15395. res.set_content("PATCH:" + req.body, "text/plain");
  15396. });
  15397. svr_.Delete(
  15398. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  15399. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  15400. "text/plain");
  15401. });
  15402. svr_.Get("/head-test",
  15403. [](const httplib::Request &, httplib::Response &res) {
  15404. res.set_content("body for HEAD", "text/plain");
  15405. });
  15406. svr_.Options("/options",
  15407. [](const httplib::Request &, httplib::Response &res) {
  15408. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  15409. });
  15410. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  15411. svr_.wait_until_ready();
  15412. }
  15413. void TearDown() override {
  15414. svr_.stop();
  15415. if (thread_.joinable()) thread_.join();
  15416. }
  15417. httplib::Server svr_;
  15418. std::thread thread_;
  15419. };
  15420. // stream::Get tests
  15421. TEST_F(StreamApiTest, GetBasic) {
  15422. httplib::Client cli(HOST, PORT);
  15423. auto result = httplib::stream::Get(cli, "/hello");
  15424. ASSERT_TRUE(result.is_valid());
  15425. EXPECT_EQ(200, result.status());
  15426. EXPECT_EQ("Hello World!", read_body(result));
  15427. }
  15428. TEST_F(StreamApiTest, GetWithParams) {
  15429. httplib::Client cli(HOST, PORT);
  15430. httplib::Params params{{"foo", "bar"}};
  15431. auto result = httplib::stream::Get(cli, "/echo-params", params);
  15432. ASSERT_TRUE(result.is_valid());
  15433. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  15434. }
  15435. TEST_F(StreamApiTest, GetConnectionError) {
  15436. httplib::Client cli(HOST, 9999);
  15437. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  15438. }
  15439. TEST_F(StreamApiTest, Get404) {
  15440. httplib::Client cli(HOST, PORT);
  15441. auto result = httplib::stream::Get(cli, "/nonexistent");
  15442. EXPECT_TRUE(result.is_valid());
  15443. EXPECT_EQ(404, result.status());
  15444. }
  15445. // stream::Post tests
  15446. TEST_F(StreamApiTest, PostBasic) {
  15447. httplib::Client cli(HOST, PORT);
  15448. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  15449. "application/json");
  15450. ASSERT_TRUE(result.is_valid());
  15451. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  15452. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  15453. }
  15454. TEST_F(StreamApiTest, PostWithHeaders) {
  15455. httplib::Client cli(HOST, PORT);
  15456. httplib::Headers headers{{"X-Custom", "value"}};
  15457. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  15458. "text/plain");
  15459. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  15460. }
  15461. TEST_F(StreamApiTest, PostWithParams) {
  15462. httplib::Client cli(HOST, PORT);
  15463. httplib::Params params{{"k", "v"}};
  15464. auto result =
  15465. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  15466. auto body = read_body(result);
  15467. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  15468. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  15469. }
  15470. TEST_F(StreamApiTest, PostLarge) {
  15471. httplib::Client cli(HOST, PORT);
  15472. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  15473. size_t total = 0;
  15474. while (result.next()) {
  15475. total += result.size();
  15476. }
  15477. EXPECT_EQ(100u * 1024u, total);
  15478. }
  15479. // stream::Put/Patch tests
  15480. TEST_F(StreamApiTest, PutAndPatch) {
  15481. httplib::Client cli(HOST, PORT);
  15482. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  15483. EXPECT_EQ("PUT:test", read_body(put));
  15484. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  15485. EXPECT_EQ("PATCH:test", read_body(patch));
  15486. }
  15487. // stream::Delete tests
  15488. TEST_F(StreamApiTest, Delete) {
  15489. httplib::Client cli(HOST, PORT);
  15490. auto del1 = httplib::stream::Delete(cli, "/resource");
  15491. EXPECT_EQ("Deleted", read_body(del1));
  15492. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  15493. EXPECT_EQ("Deleted:data", read_body(del2));
  15494. }
  15495. // stream::Head/Options tests
  15496. TEST_F(StreamApiTest, HeadAndOptions) {
  15497. httplib::Client cli(HOST, PORT);
  15498. auto head = httplib::stream::Head(cli, "/head-test");
  15499. EXPECT_TRUE(head.is_valid());
  15500. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  15501. auto opts = httplib::stream::Options(cli, "/options");
  15502. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  15503. }
  15504. // SSL stream::* tests
  15505. #ifdef CPPHTTPLIB_SSL_ENABLED
  15506. class SSLStreamApiTest : public ::testing::Test {
  15507. protected:
  15508. void SetUp() override {
  15509. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15510. res.set_content("Hello SSL!", "text/plain");
  15511. });
  15512. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15513. res.set_content(req.body, "text/plain");
  15514. });
  15515. port_ = svr_.bind_to_any_port("127.0.0.1");
  15516. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15517. svr_.wait_until_ready();
  15518. }
  15519. void TearDown() override {
  15520. svr_.stop();
  15521. if (thread_.joinable()) thread_.join();
  15522. }
  15523. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  15524. std::thread thread_;
  15525. int port_ = 0;
  15526. };
  15527. TEST_F(SSLStreamApiTest, GetAndPost) {
  15528. httplib::SSLClient cli("127.0.0.1", port_);
  15529. cli.enable_server_certificate_verification(false);
  15530. auto get = httplib::stream::Get(cli, "/hello");
  15531. EXPECT_EQ("Hello SSL!", read_body(get));
  15532. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  15533. EXPECT_EQ("test", read_body(post));
  15534. }
  15535. #endif
  15536. // Tests for Error::Timeout and Error::ConnectionClosed error types
  15537. // These errors are set in SocketStream/SSLSocketStream and propagated through
  15538. // BodyReader
  15539. TEST(ErrorHandlingTest, StreamReadTimeout) {
  15540. // Test that read timeout during streaming is detected
  15541. // Use a large content-length response where server delays mid-stream
  15542. Server svr;
  15543. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15544. // Send a large response with delay in the middle
  15545. res.set_content_provider(
  15546. 1000, // content_length
  15547. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  15548. if (offset < 100) {
  15549. // Send first 100 bytes immediately
  15550. std::string data(100, 'A');
  15551. sink.write(data.c_str(), data.size());
  15552. return true;
  15553. }
  15554. // Then delay longer than client timeout
  15555. std::this_thread::sleep_for(std::chrono::seconds(3));
  15556. std::string data(900, 'B');
  15557. sink.write(data.c_str(), data.size());
  15558. return true;
  15559. });
  15560. });
  15561. auto port = 8091;
  15562. std::thread t([&]() { svr.listen("localhost", port); });
  15563. svr.wait_until_ready();
  15564. Client cli("localhost", port);
  15565. cli.set_read_timeout(1, 0); // 1 second timeout
  15566. auto handle = cli.open_stream("GET", "/slow-stream");
  15567. ASSERT_TRUE(handle.is_valid());
  15568. char buf[256];
  15569. ssize_t total = 0;
  15570. ssize_t n;
  15571. bool got_error = false;
  15572. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15573. total += n;
  15574. }
  15575. if (n < 0) {
  15576. got_error = true;
  15577. // Should be timeout or read error
  15578. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15579. handle.get_read_error() == Error::Read)
  15580. << "Actual error: " << to_string(handle.get_read_error());
  15581. }
  15582. // Either we got an error, or we got less data than expected
  15583. EXPECT_TRUE(got_error || total < 1000)
  15584. << "Expected timeout but got all " << total << " bytes";
  15585. svr.stop();
  15586. t.join();
  15587. }
  15588. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  15589. // Test connection closed detection via BodyReader
  15590. Server svr;
  15591. std::atomic<bool> close_now{false};
  15592. svr.Get("/will-close", [&](const Request &, Response &res) {
  15593. res.set_content_provider(
  15594. 10000, // Large content_length that we won't fully send
  15595. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15596. if (offset < 100) {
  15597. std::string data(100, 'X');
  15598. sink.write(data.c_str(), data.size());
  15599. return true;
  15600. }
  15601. // Wait for signal then abort
  15602. while (!close_now) {
  15603. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15604. }
  15605. return false; // Abort - server will close connection
  15606. });
  15607. });
  15608. auto port = 8092;
  15609. std::thread t([&]() { svr.listen("localhost", port); });
  15610. svr.wait_until_ready();
  15611. Client cli("localhost", port);
  15612. auto handle = cli.open_stream("GET", "/will-close");
  15613. ASSERT_TRUE(handle.is_valid());
  15614. char buf[256];
  15615. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15616. EXPECT_GT(n, 0) << "First read should succeed";
  15617. // Signal server to close
  15618. close_now = true;
  15619. // Keep reading until error or EOF
  15620. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15621. // Keep reading
  15622. }
  15623. // Should get an error since content_length wasn't satisfied
  15624. if (n < 0) {
  15625. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15626. handle.get_read_error() == Error::Read)
  15627. << "Actual error: " << to_string(handle.get_read_error());
  15628. }
  15629. svr.stop();
  15630. t.join();
  15631. }
  15632. #ifdef CPPHTTPLIB_SSL_ENABLED
  15633. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  15634. // Test that read timeout during SSL streaming is detected
  15635. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15636. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15637. res.set_content_provider(
  15638. 1000, "text/plain",
  15639. [](size_t offset, size_t /*length*/, DataSink &sink) {
  15640. if (offset < 100) {
  15641. std::string data(100, 'A');
  15642. sink.write(data.c_str(), data.size());
  15643. return true;
  15644. }
  15645. std::this_thread::sleep_for(std::chrono::seconds(3));
  15646. std::string data(900, 'B');
  15647. sink.write(data.c_str(), data.size());
  15648. return true;
  15649. });
  15650. });
  15651. auto port = 8093;
  15652. std::thread t([&]() { svr.listen("localhost", port); });
  15653. svr.wait_until_ready();
  15654. SSLClient cli("localhost", port);
  15655. cli.enable_server_certificate_verification(false);
  15656. cli.set_read_timeout(1, 0); // 1 second timeout
  15657. auto handle = cli.open_stream("GET", "/slow-stream");
  15658. ASSERT_TRUE(handle.is_valid());
  15659. char buf[256];
  15660. ssize_t total = 0;
  15661. ssize_t n;
  15662. bool got_error = false;
  15663. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15664. total += n;
  15665. }
  15666. if (n < 0) {
  15667. got_error = true;
  15668. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15669. handle.get_read_error() == Error::Read)
  15670. << "Actual error: " << to_string(handle.get_read_error());
  15671. }
  15672. EXPECT_TRUE(got_error || total < 1000)
  15673. << "Expected timeout but got all " << total << " bytes";
  15674. svr.stop();
  15675. t.join();
  15676. }
  15677. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  15678. // Test SSL connection closed detection
  15679. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15680. std::atomic<bool> close_now{false};
  15681. svr.Get("/will-close", [&](const Request &, Response &res) {
  15682. res.set_content_provider(
  15683. 10000, "text/plain",
  15684. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15685. if (offset < 100) {
  15686. std::string data(100, 'X');
  15687. sink.write(data.c_str(), data.size());
  15688. return true;
  15689. }
  15690. while (!close_now) {
  15691. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15692. }
  15693. return false;
  15694. });
  15695. });
  15696. auto port = 8094;
  15697. std::thread t([&]() { svr.listen("localhost", port); });
  15698. svr.wait_until_ready();
  15699. SSLClient cli("localhost", port);
  15700. cli.enable_server_certificate_verification(false);
  15701. auto handle = cli.open_stream("GET", "/will-close");
  15702. ASSERT_TRUE(handle.is_valid());
  15703. char buf[256];
  15704. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15705. EXPECT_GT(n, 0);
  15706. // Signal server to close
  15707. close_now = true;
  15708. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15709. // Keep reading
  15710. }
  15711. if (n < 0) {
  15712. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15713. handle.get_read_error() == Error::Read)
  15714. << "Actual error: " << to_string(handle.get_read_error());
  15715. }
  15716. svr.stop();
  15717. t.join();
  15718. }
  15719. #endif
  15720. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  15721. using namespace httplib;
  15722. // Create a test file
  15723. const char *fname = "etag_testfile.txt";
  15724. const char *content = "etag-content";
  15725. {
  15726. std::ofstream ofs(fname);
  15727. ofs << content;
  15728. ASSERT_TRUE(ofs.good());
  15729. }
  15730. Server svr;
  15731. svr.set_mount_point("/static", ".");
  15732. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15733. svr.wait_until_ready();
  15734. Client cli(HOST, PORT);
  15735. // First request: should get 200 with ETag header
  15736. auto res1 = cli.Get("/static/etag_testfile.txt");
  15737. ASSERT_TRUE(res1);
  15738. ASSERT_EQ(200, res1->status);
  15739. ASSERT_TRUE(res1->has_header("ETag"));
  15740. std::string etag = res1->get_header_value("ETag");
  15741. EXPECT_FALSE(etag.empty());
  15742. // Verify ETag format: W/"hex-hex"
  15743. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  15744. EXPECT_EQ('W', etag[0]);
  15745. EXPECT_EQ('/', etag[1]);
  15746. EXPECT_EQ('"', etag[2]);
  15747. EXPECT_EQ('"', etag.back());
  15748. // Exact match: expect 304 Not Modified
  15749. Headers h2 = {{"If-None-Match", etag}};
  15750. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  15751. ASSERT_TRUE(res2);
  15752. EXPECT_EQ(304, res2->status);
  15753. // Wildcard match: expect 304 Not Modified
  15754. Headers h3 = {{"If-None-Match", "*"}};
  15755. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  15756. ASSERT_TRUE(res3);
  15757. EXPECT_EQ(304, res3->status);
  15758. // Non-matching ETag: expect 200
  15759. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  15760. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  15761. ASSERT_TRUE(res4);
  15762. EXPECT_EQ(200, res4->status);
  15763. // Multiple ETags with one matching: expect 304
  15764. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  15765. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  15766. ASSERT_TRUE(res5);
  15767. EXPECT_EQ(304, res5->status);
  15768. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  15769. // that equivalent to the single comma-separated list above, so the match on
  15770. // the second line must still be found.
  15771. Headers h6;
  15772. h6.emplace("If-None-Match", "W/\"other\"");
  15773. h6.emplace("If-None-Match", etag);
  15774. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  15775. ASSERT_TRUE(res6);
  15776. EXPECT_EQ(304, res6->status);
  15777. svr.stop();
  15778. t.join();
  15779. std::remove(fname);
  15780. }
  15781. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  15782. using namespace httplib;
  15783. Server svr;
  15784. svr.set_mount_point("/static", ".");
  15785. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15786. svr.wait_until_ready();
  15787. Client cli(HOST, PORT);
  15788. // Send If-None-Match: * to a non-existent file
  15789. Headers h = {{"If-None-Match", "*"}};
  15790. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  15791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15792. EXPECT_EQ(404, res->status);
  15793. svr.stop();
  15794. t.join();
  15795. }
  15796. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  15797. using namespace httplib;
  15798. // Create a test file
  15799. const char *fname = "etag_boundary_testfile.txt";
  15800. const char *content = "boundary-test";
  15801. {
  15802. std::ofstream ofs(fname);
  15803. ofs << content;
  15804. ASSERT_TRUE(ofs.good());
  15805. }
  15806. Server svr;
  15807. svr.set_mount_point("/static", ".");
  15808. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15809. svr.wait_until_ready();
  15810. Client cli(HOST, PORT);
  15811. // Get the actual ETag
  15812. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  15813. ASSERT_TRUE(res1);
  15814. ASSERT_EQ(200, res1->status);
  15815. ASSERT_TRUE(res1->has_header("ETag"));
  15816. std::string etag = res1->get_header_value("ETag");
  15817. // Test 1: Very long ETag value (longer than actual ETag)
  15818. // Should NOT match and return 200 (not trigger out-of-bounds read)
  15819. Headers h1 = {{"If-None-Match", "W/"
  15820. "\"very-long-etag-value-that-is-much-longer-"
  15821. "than-the-actual-etag-value\""}};
  15822. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  15823. ASSERT_TRUE(res2);
  15824. EXPECT_EQ(200, res2->status); // Should not match
  15825. // Test 2: Long string followed by wildcard
  15826. // Should match on "*" and return 304 (without out-of-bounds read on the long
  15827. // string)
  15828. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  15829. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  15830. ASSERT_TRUE(res3);
  15831. EXPECT_EQ(304, res3->status); // Should match on "*"
  15832. // Test 3: Wildcard followed by long string
  15833. // Should match on "*" immediately and return 304
  15834. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  15835. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  15836. ASSERT_TRUE(res4);
  15837. EXPECT_EQ(304, res4->status); // Should match on "*"
  15838. // Test 4: Multiple long non-matching values
  15839. // Should NOT match and return 200 (test that all comparisons are safe)
  15840. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  15841. "W/\"second-long-non-matching-value\", "
  15842. "W/\"third-long-non-matching-value\""}};
  15843. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  15844. ASSERT_TRUE(res5);
  15845. EXPECT_EQ(200, res5->status); // Should not match
  15846. // Test 5: Single character that is not "*" (edge case)
  15847. Headers h5 = {{"If-None-Match", "X"}};
  15848. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  15849. ASSERT_TRUE(res6);
  15850. EXPECT_EQ(200, res6->status); // Should not match
  15851. svr.stop();
  15852. t.join();
  15853. std::remove(fname);
  15854. }
  15855. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  15856. using namespace httplib;
  15857. // Create a test file
  15858. const char *fname = "ims_testfile.txt";
  15859. const char *content = "if-modified-since-test";
  15860. {
  15861. std::ofstream ofs(fname);
  15862. ofs << content;
  15863. ASSERT_TRUE(ofs.good());
  15864. }
  15865. Server svr;
  15866. svr.set_mount_point("/static", ".");
  15867. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15868. svr.wait_until_ready();
  15869. Client cli(HOST, PORT);
  15870. // First request: should get 200 with Last-Modified header
  15871. auto res1 = cli.Get("/static/ims_testfile.txt");
  15872. ASSERT_TRUE(res1);
  15873. ASSERT_EQ(200, res1->status);
  15874. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15875. std::string last_modified = res1->get_header_value("Last-Modified");
  15876. EXPECT_FALSE(last_modified.empty());
  15877. // If-Modified-Since with same time: expect 304
  15878. Headers h2 = {{"If-Modified-Since", last_modified}};
  15879. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  15880. ASSERT_TRUE(res2);
  15881. EXPECT_EQ(304, res2->status);
  15882. // If-Modified-Since with future time: expect 304
  15883. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15884. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  15885. ASSERT_TRUE(res3);
  15886. EXPECT_EQ(304, res3->status);
  15887. // If-Modified-Since with past time: expect 200
  15888. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15889. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  15890. ASSERT_TRUE(res4);
  15891. EXPECT_EQ(200, res4->status);
  15892. // If-None-Match takes precedence over If-Modified-Since
  15893. // (send matching ETag with old If-Modified-Since -> should still be 304)
  15894. ASSERT_TRUE(res1->has_header("ETag"));
  15895. std::string etag = res1->get_header_value("ETag");
  15896. Headers h5 = {{"If-None-Match", etag},
  15897. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15898. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  15899. ASSERT_TRUE(res5);
  15900. EXPECT_EQ(304, res5->status);
  15901. svr.stop();
  15902. t.join();
  15903. std::remove(fname);
  15904. }
  15905. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  15906. using namespace httplib;
  15907. Server svr;
  15908. // Endpoint that returns compressible content
  15909. svr.Get("/compressible", [](const Request &, Response &res) {
  15910. // Return a large enough body to trigger compression
  15911. std::string body(1000, 'a');
  15912. res.set_content(body, "text/plain");
  15913. });
  15914. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15915. svr.wait_until_ready();
  15916. Client cli(HOST, PORT);
  15917. // Request with gzip support: should get Vary header when compressed
  15918. cli.set_compress(true);
  15919. auto res1 = cli.Get("/compressible");
  15920. ASSERT_TRUE(res1);
  15921. EXPECT_EQ(200, res1->status);
  15922. // If Content-Encoding is set, Vary should also be set
  15923. if (res1->has_header("Content-Encoding")) {
  15924. EXPECT_TRUE(res1->has_header("Vary"));
  15925. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  15926. }
  15927. // Request without Accept-Encoding header: should not have compression
  15928. Headers h_no_compress;
  15929. auto res2 = cli.Get("/compressible", h_no_compress);
  15930. ASSERT_TRUE(res2);
  15931. EXPECT_EQ(200, res2->status);
  15932. // Verify Vary header is present when compression is applied
  15933. // (the exact behavior depends on server configuration)
  15934. svr.stop();
  15935. t.join();
  15936. }
  15937. TEST(ETagTest, IfRangeWithETag) {
  15938. using namespace httplib;
  15939. // Create a test file with known content
  15940. const char *fname = "if_range_testfile.txt";
  15941. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  15942. {
  15943. std::ofstream ofs(fname);
  15944. ofs << content;
  15945. ASSERT_TRUE(ofs.good());
  15946. }
  15947. Server svr;
  15948. svr.set_mount_point("/static", ".");
  15949. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15950. svr.wait_until_ready();
  15951. Client cli(HOST, PORT);
  15952. // First request: get ETag
  15953. auto res1 = cli.Get("/static/if_range_testfile.txt");
  15954. ASSERT_TRUE(res1);
  15955. ASSERT_EQ(200, res1->status);
  15956. ASSERT_TRUE(res1->has_header("ETag"));
  15957. std::string etag = res1->get_header_value("ETag");
  15958. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  15959. // Since our server generates weak ETags (W/"..."), If-Range with our
  15960. // ETag should NOT result in partial content - it should return full content.
  15961. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  15962. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  15963. ASSERT_TRUE(res2);
  15964. // Weak ETag in If-Range -> full content (200), not partial (206)
  15965. EXPECT_EQ(200, res2->status);
  15966. EXPECT_EQ(content, res2->body);
  15967. EXPECT_FALSE(res2->has_header("Content-Range"));
  15968. // Range request with non-matching If-Range (ETag): should get 200 (full
  15969. // content)
  15970. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  15971. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  15972. ASSERT_TRUE(res3);
  15973. EXPECT_EQ(200, res3->status);
  15974. EXPECT_EQ(content, res3->body);
  15975. EXPECT_FALSE(res3->has_header("Content-Range"));
  15976. // Range request with strong ETag (hypothetical - our server doesn't generate
  15977. // strong ETags, but if client sends a strong ETag that doesn't match, it
  15978. // should return full content)
  15979. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  15980. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  15981. ASSERT_TRUE(res4);
  15982. EXPECT_EQ(200, res4->status);
  15983. EXPECT_EQ(content, res4->body);
  15984. EXPECT_FALSE(res4->has_header("Content-Range"));
  15985. svr.stop();
  15986. t.join();
  15987. std::remove(fname);
  15988. }
  15989. TEST(ETagTest, IfRangeWithDate) {
  15990. using namespace httplib;
  15991. // Create a test file
  15992. const char *fname = "if_range_date_testfile.txt";
  15993. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  15994. {
  15995. std::ofstream ofs(fname);
  15996. ofs << content;
  15997. ASSERT_TRUE(ofs.good());
  15998. }
  15999. Server svr;
  16000. svr.set_mount_point("/static", ".");
  16001. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16002. svr.wait_until_ready();
  16003. Client cli(HOST, PORT);
  16004. // First request: get Last-Modified
  16005. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  16006. ASSERT_TRUE(res1);
  16007. ASSERT_EQ(200, res1->status);
  16008. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16009. std::string last_modified = res1->get_header_value("Last-Modified");
  16010. // Range request with matching If-Range (date): should get 206
  16011. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  16012. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  16013. ASSERT_TRUE(res2);
  16014. EXPECT_EQ(206, res2->status);
  16015. EXPECT_EQ("FGHIJ", res2->body);
  16016. // Range request with old If-Range date: should get 200 (full content)
  16017. Headers h3 = {{"Range", "bytes=5-9"},
  16018. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16019. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  16020. ASSERT_TRUE(res3);
  16021. EXPECT_EQ(200, res3->status);
  16022. EXPECT_EQ(content, res3->body);
  16023. // Range request with future If-Range date: should get 206
  16024. Headers h4 = {{"Range", "bytes=0-4"},
  16025. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16026. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  16027. ASSERT_TRUE(res4);
  16028. EXPECT_EQ(206, res4->status);
  16029. EXPECT_EQ("ABCDE", res4->body);
  16030. svr.stop();
  16031. t.join();
  16032. std::remove(fname);
  16033. }
  16034. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  16035. using namespace httplib;
  16036. const char *fname = "etag_malformed.txt";
  16037. const char *content = "malformed-etag";
  16038. {
  16039. std::ofstream ofs(fname);
  16040. ofs << content;
  16041. ASSERT_TRUE(ofs.good());
  16042. }
  16043. Server svr;
  16044. svr.set_mount_point("/static", ".");
  16045. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16046. svr.wait_until_ready();
  16047. Client cli(HOST, PORT);
  16048. // baseline: should get 200 and an ETag
  16049. auto res1 = cli.Get("/static/etag_malformed.txt");
  16050. ASSERT_TRUE(res1);
  16051. ASSERT_EQ(200, res1->status);
  16052. ASSERT_TRUE(res1->has_header("ETag"));
  16053. // Malformed ETag value (missing quotes) should be treated as non-matching
  16054. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  16055. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  16056. ASSERT_TRUE(res_bad);
  16057. EXPECT_EQ(200, res_bad->status);
  16058. // Whitespace-only header value should be considered invalid / non-matching
  16059. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  16060. "Host: localhost\r\n"
  16061. "If-None-Match: \r\n"
  16062. "Connection: close\r\n"
  16063. "\r\n";
  16064. std::string out;
  16065. ASSERT_TRUE(send_request(5, raw_req, &out));
  16066. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16067. svr.stop();
  16068. t.join();
  16069. std::remove(fname);
  16070. }
  16071. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  16072. using namespace httplib;
  16073. const char *fname = "ims_invalid_format.txt";
  16074. const char *content = "ims-bad-format";
  16075. {
  16076. std::ofstream ofs(fname);
  16077. ofs << content;
  16078. ASSERT_TRUE(ofs.good());
  16079. }
  16080. Server svr;
  16081. svr.set_mount_point("/static", ".");
  16082. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16083. svr.wait_until_ready();
  16084. Client cli(HOST, PORT);
  16085. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  16086. ASSERT_TRUE(res1);
  16087. ASSERT_EQ(200, res1->status);
  16088. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16089. // If-Modified-Since with invalid format should not result in 304
  16090. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  16091. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  16092. ASSERT_TRUE(res_bad);
  16093. EXPECT_EQ(200, res_bad->status);
  16094. // If-Range with invalid date format should be treated as mismatch -> full
  16095. // content (200)
  16096. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  16097. {"If-Range", "invalid-date"}};
  16098. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  16099. ASSERT_TRUE(res_ifrange);
  16100. EXPECT_EQ(200, res_ifrange->status);
  16101. svr.stop();
  16102. t.join();
  16103. std::remove(fname);
  16104. }
  16105. TEST(ETagTest, IfRangeWithMalformedETag) {
  16106. using namespace httplib;
  16107. const char *fname = "ifrange_malformed.txt";
  16108. const std::string content = "0123456789";
  16109. {
  16110. std::ofstream ofs(fname);
  16111. ofs << content;
  16112. ASSERT_TRUE(ofs.good());
  16113. }
  16114. Server svr;
  16115. svr.set_mount_point("/static", ".");
  16116. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16117. svr.wait_until_ready();
  16118. Client cli(HOST, PORT);
  16119. // First request: get ETag
  16120. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  16121. ASSERT_TRUE(res1);
  16122. ASSERT_EQ(200, res1->status);
  16123. ASSERT_TRUE(res1->has_header("ETag"));
  16124. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  16125. // full content (200)
  16126. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  16127. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  16128. ASSERT_TRUE(res2);
  16129. EXPECT_EQ(200, res2->status);
  16130. EXPECT_EQ(content, res2->body);
  16131. svr.stop();
  16132. t.join();
  16133. std::remove(fname);
  16134. }
  16135. TEST(ETagTest, ExtremeLargeDateValues) {
  16136. using namespace httplib;
  16137. const char *fname = "ims_extreme_date.txt";
  16138. const char *content = "ims-extreme-date";
  16139. {
  16140. std::ofstream ofs(fname);
  16141. ofs << content;
  16142. ASSERT_TRUE(ofs.good());
  16143. }
  16144. Server svr;
  16145. svr.set_mount_point("/static", ".");
  16146. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16147. svr.wait_until_ready();
  16148. Client cli(HOST, PORT);
  16149. auto res1 = cli.Get(std::string("/static/") + fname);
  16150. ASSERT_TRUE(res1);
  16151. ASSERT_EQ(200, res1->status);
  16152. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16153. // Extremely large year that may overflow date parsing routines.
  16154. Headers h_large_date = {
  16155. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16156. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  16157. ASSERT_TRUE(res_bad);
  16158. // Expect server to treat this as invalid/mismatch and return full content
  16159. EXPECT_EQ(200, res_bad->status);
  16160. // If-Range with extremely large date should be treated as mismatch -> full
  16161. // content (200)
  16162. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  16163. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16164. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  16165. ASSERT_TRUE(res_ifrange);
  16166. EXPECT_EQ(200, res_ifrange->status);
  16167. svr.stop();
  16168. t.join();
  16169. std::remove(fname);
  16170. }
  16171. TEST(ETagTest, NegativeFileModificationTime) {
  16172. using namespace httplib;
  16173. const char *fname = "ims_negative_mtime.txt";
  16174. const std::string content = "negative-mtime";
  16175. {
  16176. std::ofstream ofs(fname);
  16177. ofs << content;
  16178. ASSERT_TRUE(ofs.good());
  16179. }
  16180. // Try to set file mtime to a negative value. This may fail on some
  16181. // platforms/filesystems; if it fails, the test will still verify server
  16182. // behaves safely by performing a regular conditional request.
  16183. #if defined(__APPLE__) || defined(__linux__)
  16184. bool set_negative = false;
  16185. do {
  16186. struct timeval times[2];
  16187. // access time: now
  16188. times[0].tv_sec = time(nullptr);
  16189. times[0].tv_usec = 0;
  16190. // modification time: negative (e.g., -1)
  16191. times[1].tv_sec = -1;
  16192. times[1].tv_usec = 0;
  16193. if (utimes(fname, times) == 0) { set_negative = true; }
  16194. } while (0);
  16195. #else
  16196. bool set_negative = false;
  16197. #endif
  16198. Server svr;
  16199. svr.set_mount_point("/static", ".");
  16200. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16201. svr.wait_until_ready();
  16202. Client cli(HOST, PORT);
  16203. auto res1 = cli.Get(std::string("/static/") + fname);
  16204. ASSERT_TRUE(res1);
  16205. ASSERT_EQ(200, res1->status);
  16206. bool has_last_modified = res1->has_header("Last-Modified");
  16207. std::string last_modified;
  16208. if (has_last_modified) {
  16209. last_modified = res1->get_header_value("Last-Modified");
  16210. }
  16211. if (set_negative) {
  16212. // If we successfully set a negative mtime, ensure server returns a
  16213. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  16214. // with an old date and ensure server handles it without crash.
  16215. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  16216. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  16217. ASSERT_TRUE(res2);
  16218. // Behavior may vary; at minimum ensure server responds (200 or 304).
  16219. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  16220. } else {
  16221. // Could not set negative mtime on this platform; fall back to verifying
  16222. // that normal invalid/malformed dates are treated safely (non-304).
  16223. Headers h_bad_date = {
  16224. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16225. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  16226. ASSERT_TRUE(res_bad);
  16227. EXPECT_EQ(200, res_bad->status);
  16228. }
  16229. svr.stop();
  16230. t.join();
  16231. std::remove(fname);
  16232. }
  16233. //==============================================================================
  16234. // SSE Parsing Tests
  16235. //==============================================================================
  16236. class SSEParsingTest : public ::testing::Test {
  16237. protected:
  16238. // Test helper that mimics SSE parsing behavior
  16239. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  16240. int &retry_ms) {
  16241. // Blank line signals end of event
  16242. if (line.empty() || line == "\r") { return true; }
  16243. // Lines starting with ':' are comments (ignored)
  16244. if (!line.empty() && line[0] == ':') { return false; }
  16245. // Find the colon separator
  16246. auto colon_pos = line.find(':');
  16247. if (colon_pos == std::string::npos) {
  16248. // Line with no colon is treated as field name with empty value
  16249. return false;
  16250. }
  16251. std::string field = line.substr(0, colon_pos);
  16252. std::string value;
  16253. // Value starts after colon, skip optional single space
  16254. if (colon_pos + 1 < line.size()) {
  16255. size_t value_start = colon_pos + 1;
  16256. if (line[value_start] == ' ') { value_start++; }
  16257. value = line.substr(value_start);
  16258. // Remove trailing \r if present
  16259. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  16260. }
  16261. // Handle known fields
  16262. if (field == "event") {
  16263. msg.event = value;
  16264. } else if (field == "data") {
  16265. // Multiple data lines are concatenated with newlines
  16266. if (!msg.data.empty()) { msg.data += "\n"; }
  16267. msg.data += value;
  16268. } else if (field == "id") {
  16269. // Empty id is valid (clears the last event ID)
  16270. msg.id = value;
  16271. } else if (field == "retry") {
  16272. // Parse retry interval in milliseconds
  16273. {
  16274. int v = 0;
  16275. auto res =
  16276. detail::from_chars(value.data(), value.data() + value.size(), v);
  16277. if (res.ec == std::errc{}) { retry_ms = v; }
  16278. }
  16279. }
  16280. // Unknown fields are ignored per SSE spec
  16281. return false;
  16282. }
  16283. };
  16284. // Test: Single-line data
  16285. TEST_F(SSEParsingTest, SingleLineData) {
  16286. sse::SSEMessage msg;
  16287. int retry_ms = 3000;
  16288. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  16289. EXPECT_EQ(msg.data, "hello");
  16290. EXPECT_EQ(msg.event, "message");
  16291. // Blank line ends event
  16292. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16293. }
  16294. // Test: Multi-line data
  16295. TEST_F(SSEParsingTest, MultiLineData) {
  16296. sse::SSEMessage msg;
  16297. int retry_ms = 3000;
  16298. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  16299. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  16300. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  16301. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  16302. }
  16303. // Test: Custom event types
  16304. TEST_F(SSEParsingTest, CustomEventType) {
  16305. sse::SSEMessage msg;
  16306. int retry_ms = 3000;
  16307. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  16308. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  16309. EXPECT_EQ(msg.event, "update");
  16310. EXPECT_EQ(msg.data, "payload");
  16311. }
  16312. // Test: Event ID handling
  16313. TEST_F(SSEParsingTest, EventIdHandling) {
  16314. sse::SSEMessage msg;
  16315. int retry_ms = 3000;
  16316. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  16317. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  16318. EXPECT_EQ(msg.id, "12345");
  16319. }
  16320. // Test: Empty event ID (clears last event ID)
  16321. TEST_F(SSEParsingTest, EmptyEventId) {
  16322. sse::SSEMessage msg;
  16323. msg.id = "previous";
  16324. int retry_ms = 3000;
  16325. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  16326. EXPECT_EQ(msg.id, "");
  16327. }
  16328. // Test: Retry field parsing
  16329. TEST_F(SSEParsingTest, RetryFieldParsing) {
  16330. sse::SSEMessage msg;
  16331. int retry_ms = 3000;
  16332. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  16333. EXPECT_EQ(retry_ms, 5000);
  16334. }
  16335. // Test: Invalid retry value
  16336. TEST_F(SSEParsingTest, InvalidRetryValue) {
  16337. sse::SSEMessage msg;
  16338. int retry_ms = 3000;
  16339. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  16340. EXPECT_EQ(retry_ms, 3000); // Unchanged
  16341. }
  16342. // Test: Comments (lines starting with :)
  16343. TEST_F(SSEParsingTest, CommentsIgnored) {
  16344. sse::SSEMessage msg;
  16345. int retry_ms = 3000;
  16346. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  16347. EXPECT_EQ(msg.data, "");
  16348. EXPECT_EQ(msg.event, "message");
  16349. }
  16350. // Test: Colon in value
  16351. TEST_F(SSEParsingTest, ColonInValue) {
  16352. sse::SSEMessage msg;
  16353. int retry_ms = 3000;
  16354. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  16355. EXPECT_EQ(msg.data, "hello:world:test");
  16356. }
  16357. // Test: Line with no colon (field name only)
  16358. TEST_F(SSEParsingTest, FieldNameOnly) {
  16359. sse::SSEMessage msg;
  16360. int retry_ms = 3000;
  16361. // According to SSE spec, this is treated as field name with empty value
  16362. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  16363. // Since we don't recognize "data" without colon, data should be empty
  16364. EXPECT_EQ(msg.data, "");
  16365. }
  16366. // Test: Trailing \r handling
  16367. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  16368. sse::SSEMessage msg;
  16369. int retry_ms = 3000;
  16370. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  16371. EXPECT_EQ(msg.data, "hello");
  16372. }
  16373. // Test: Unknown fields ignored
  16374. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  16375. sse::SSEMessage msg;
  16376. int retry_ms = 3000;
  16377. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  16378. EXPECT_EQ(msg.data, "");
  16379. EXPECT_EQ(msg.event, "message");
  16380. }
  16381. // Test: Space after colon is optional
  16382. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  16383. sse::SSEMessage msg1, msg2;
  16384. int retry_ms = 3000;
  16385. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  16386. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  16387. EXPECT_EQ(msg1.data, "hello");
  16388. EXPECT_EQ(msg2.data, "hello");
  16389. }
  16390. // Test: SSEMessage clear
  16391. TEST_F(SSEParsingTest, MessageClear) {
  16392. sse::SSEMessage msg;
  16393. msg.event = "custom";
  16394. msg.data = "some data";
  16395. msg.id = "123";
  16396. msg.clear();
  16397. EXPECT_EQ(msg.event, "message");
  16398. EXPECT_EQ(msg.data, "");
  16399. EXPECT_EQ(msg.id, "");
  16400. }
  16401. // Test: Complete event parsing
  16402. TEST_F(SSEParsingTest, CompleteEventParsing) {
  16403. sse::SSEMessage msg;
  16404. int retry_ms = 3000;
  16405. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  16406. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  16407. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  16408. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  16409. // Blank line ends event
  16410. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16411. EXPECT_EQ(msg.event, "notification");
  16412. EXPECT_EQ(msg.id, "evt-42");
  16413. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  16414. EXPECT_EQ(retry_ms, 1000);
  16415. }
  16416. //==============================================================================
  16417. // Integration Tests with Server
  16418. //==============================================================================
  16419. class SSEIntegrationTest : public ::testing::Test {
  16420. protected:
  16421. void SetUp() override {
  16422. stop_server_.store(false);
  16423. events_.clear();
  16424. server_ = httplib::detail::make_unique<Server>();
  16425. setup_server();
  16426. start_server();
  16427. }
  16428. void TearDown() override {
  16429. stop_server_.store(true);
  16430. event_cv_.notify_all();
  16431. server_->stop();
  16432. if (server_thread_.joinable()) { server_thread_.join(); }
  16433. }
  16434. void setup_server() {
  16435. // Simple SSE endpoint
  16436. server_->Get("/events", [this](const Request &req, Response &res) {
  16437. auto last_id = req.get_header_value("Last-Event-ID");
  16438. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  16439. res.set_chunked_content_provider(
  16440. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  16441. std::unique_lock<std::mutex> lock(event_mutex_);
  16442. if (event_cv_.wait_for(
  16443. lock, std::chrono::milliseconds(200), [this] {
  16444. return !events_.empty() || stop_server_.load();
  16445. })) {
  16446. if (stop_server_.load()) { return false; }
  16447. if (!events_.empty()) {
  16448. std::string event = events_.front();
  16449. events_.erase(events_.begin());
  16450. sink.write(event.data(), event.size());
  16451. return true;
  16452. }
  16453. }
  16454. return !stop_server_.load();
  16455. });
  16456. });
  16457. // Endpoint that returns error
  16458. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  16459. res.status = 500;
  16460. res.set_content("Internal Server Error", "text/plain");
  16461. });
  16462. // Endpoint for custom event types
  16463. server_->Get("/custom-events", [](const Request &, Response &res) {
  16464. res.set_chunked_content_provider(
  16465. "text/event-stream", [](size_t offset, DataSink &sink) {
  16466. if (offset == 0) {
  16467. std::string event = "event: update\ndata: updated\n\n"
  16468. "event: delete\ndata: deleted\n\n";
  16469. sink.write(event.data(), event.size());
  16470. }
  16471. return false; // End stream after sending
  16472. });
  16473. });
  16474. }
  16475. void start_server() {
  16476. port_ = server_->bind_to_any_port(HOST);
  16477. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16478. // Wait for server to start
  16479. while (!server_->is_running()) {
  16480. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16481. }
  16482. }
  16483. int get_port() const { return port_; }
  16484. void send_event(const std::string &event) {
  16485. std::lock_guard<std::mutex> lock(event_mutex_);
  16486. events_.push_back(event);
  16487. event_cv_.notify_all();
  16488. }
  16489. std::unique_ptr<Server> server_;
  16490. std::thread server_thread_;
  16491. std::mutex event_mutex_;
  16492. std::condition_variable event_cv_;
  16493. std::vector<std::string> events_;
  16494. std::atomic<bool> stop_server_{false};
  16495. std::string last_received_event_id_;
  16496. int port_ = 0;
  16497. };
  16498. // Test: Successful connection and on_open callback
  16499. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  16500. // Add a simple endpoint that sends one event and closes
  16501. server_->Get("/simple-event", [](const Request &, Response &res) {
  16502. res.set_chunked_content_provider(
  16503. "text/event-stream", [](size_t offset, DataSink &sink) {
  16504. if (offset == 0) {
  16505. std::string event = "data: hello\n\n";
  16506. sink.write(event.data(), event.size());
  16507. }
  16508. return false; // Close stream after sending
  16509. });
  16510. });
  16511. Client client("localhost", get_port());
  16512. sse::SSEClient sse(client, "/simple-event");
  16513. std::atomic<bool> open_called{false};
  16514. std::atomic<bool> message_received{false};
  16515. sse.on_open([&open_called]() { open_called.store(true); });
  16516. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  16517. if (msg.data == "hello") { message_received.store(true); }
  16518. });
  16519. sse.set_reconnect_interval(100);
  16520. sse.set_max_reconnect_attempts(1);
  16521. // Start async
  16522. sse.start_async();
  16523. // Wait for message to be processed
  16524. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16525. sse.stop();
  16526. EXPECT_TRUE(open_called.load());
  16527. EXPECT_TRUE(message_received.load());
  16528. }
  16529. // Test: on_message callback
  16530. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  16531. // Endpoint that sends multiple events then closes
  16532. server_->Get("/multi-event", [](const Request &, Response &res) {
  16533. res.set_chunked_content_provider(
  16534. "text/event-stream", [](size_t offset, DataSink &sink) {
  16535. if (offset == 0) {
  16536. std::string events = "data: message1\n\ndata: message2\n\n";
  16537. sink.write(events.data(), events.size());
  16538. }
  16539. return false;
  16540. });
  16541. });
  16542. Client client("localhost", get_port());
  16543. sse::SSEClient sse(client, "/multi-event");
  16544. std::vector<std::string> received_messages;
  16545. std::mutex messages_mutex;
  16546. sse.on_message([&](const sse::SSEMessage &msg) {
  16547. std::lock_guard<std::mutex> lock(messages_mutex);
  16548. received_messages.push_back(msg.data);
  16549. });
  16550. sse.set_reconnect_interval(100);
  16551. sse.set_max_reconnect_attempts(1);
  16552. sse.start_async();
  16553. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16554. sse.stop();
  16555. std::lock_guard<std::mutex> lock(messages_mutex);
  16556. EXPECT_GE(received_messages.size(), 2u);
  16557. if (received_messages.size() >= 2) {
  16558. EXPECT_EQ(received_messages[0], "message1");
  16559. EXPECT_EQ(received_messages[1], "message2");
  16560. }
  16561. }
  16562. // Test: on_event for specific types
  16563. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  16564. Client client("localhost", get_port());
  16565. sse::SSEClient sse(client, "/custom-events");
  16566. std::atomic<bool> update_received{false};
  16567. std::atomic<bool> delete_received{false};
  16568. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  16569. if (msg.data == "updated") { update_received.store(true); }
  16570. });
  16571. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  16572. if (msg.data == "deleted") { delete_received.store(true); }
  16573. });
  16574. sse.set_max_reconnect_attempts(1);
  16575. sse.start_async();
  16576. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  16577. sse.stop();
  16578. EXPECT_TRUE(update_received.load());
  16579. EXPECT_TRUE(delete_received.load());
  16580. }
  16581. // Test: on_error callback on connection failure
  16582. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  16583. // Connect to a non-existent port
  16584. Client client("localhost", 59999);
  16585. sse::SSEClient sse(client, "/events");
  16586. std::atomic<bool> error_called{false};
  16587. Error received_error = Error::Success;
  16588. sse.on_error([&](Error err) {
  16589. error_called.store(true);
  16590. received_error = err;
  16591. });
  16592. sse.set_reconnect_interval(50);
  16593. sse.set_max_reconnect_attempts(1);
  16594. sse.start_async();
  16595. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16596. sse.stop();
  16597. EXPECT_TRUE(error_called.load());
  16598. EXPECT_NE(received_error, Error::Success);
  16599. }
  16600. // Test: Last-Event-ID header sent on reconnect
  16601. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  16602. // Endpoint that sends event with ID
  16603. server_->Get("/event-with-id", [](const Request &, Response &res) {
  16604. res.set_chunked_content_provider(
  16605. "text/event-stream", [](size_t offset, DataSink &sink) {
  16606. if (offset == 0) {
  16607. std::string event = "id: evt-123\ndata: test\n\n";
  16608. sink.write(event.data(), event.size());
  16609. }
  16610. return false;
  16611. });
  16612. });
  16613. Client client("localhost", get_port());
  16614. sse::SSEClient sse(client, "/event-with-id");
  16615. std::atomic<bool> id_received{false};
  16616. sse.on_message([&](const sse::SSEMessage &msg) {
  16617. if (!msg.id.empty()) { id_received.store(true); }
  16618. });
  16619. sse.set_reconnect_interval(100);
  16620. sse.set_max_reconnect_attempts(1);
  16621. sse.start_async();
  16622. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16623. sse.stop();
  16624. EXPECT_TRUE(id_received.load());
  16625. EXPECT_EQ(sse.last_event_id(), "evt-123");
  16626. }
  16627. // Test: Manual stop
  16628. TEST_F(SSEIntegrationTest, ManualStop) {
  16629. // Endpoint that sends one event and stays open briefly
  16630. std::atomic<bool> handler_running{true};
  16631. server_->Get("/stay-open", [&handler_running](const Request &,
  16632. Response &res) {
  16633. res.set_chunked_content_provider(
  16634. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  16635. if (offset == 0) {
  16636. std::string event = "data: connected\n\n";
  16637. sink.write(event.data(), event.size());
  16638. }
  16639. // Keep connection open while handler_running is true
  16640. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  16641. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16642. }
  16643. return false;
  16644. });
  16645. });
  16646. Client client("localhost", get_port());
  16647. sse::SSEClient sse(client, "/stay-open");
  16648. std::atomic<bool> connected{false};
  16649. sse.on_open([&connected]() { connected.store(true); });
  16650. sse.set_reconnect_interval(100);
  16651. sse.set_max_reconnect_attempts(1);
  16652. sse.start_async();
  16653. // Wait for connection to establish
  16654. for (int i = 0; i < 20 && !connected.load(); ++i) {
  16655. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16656. }
  16657. EXPECT_TRUE(connected.load());
  16658. EXPECT_TRUE(sse.is_connected());
  16659. // Signal handler to stop
  16660. handler_running.store(false);
  16661. // Stop SSE client
  16662. sse.stop();
  16663. EXPECT_FALSE(sse.is_connected());
  16664. }
  16665. // Test: SSEClient with custom headers
  16666. TEST_F(SSEIntegrationTest, CustomHeaders) {
  16667. // Setup a server endpoint that checks for custom header
  16668. std::atomic<bool> header_received{false};
  16669. server_->Get("/header-check", [&](const Request &req, Response &res) {
  16670. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  16671. header_received.store(true);
  16672. }
  16673. res.set_chunked_content_provider("text/event-stream",
  16674. [](size_t, DataSink &) { return false; });
  16675. });
  16676. Client client("localhost", get_port());
  16677. Headers headers = {{"X-Custom-Header", "custom-value"}};
  16678. sse::SSEClient sse(client, "/header-check", headers);
  16679. sse.set_max_reconnect_attempts(1);
  16680. sse.start_async();
  16681. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16682. sse.stop();
  16683. EXPECT_TRUE(header_received.load());
  16684. }
  16685. // Test: Reconnect interval configuration
  16686. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  16687. Client client("localhost", get_port());
  16688. sse::SSEClient sse(client, "/events");
  16689. auto &result = sse.set_reconnect_interval(500);
  16690. // Builder pattern should return reference to self
  16691. EXPECT_EQ(&result, &sse);
  16692. }
  16693. // Test: Max reconnect attempts
  16694. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  16695. // Connect to non-existent port to force reconnects
  16696. Client client("localhost", 59998);
  16697. sse::SSEClient sse(client, "/events");
  16698. std::atomic<int> error_count{0};
  16699. sse.on_error([&](Error) { error_count.fetch_add(1); });
  16700. sse.set_reconnect_interval(50);
  16701. sse.set_max_reconnect_attempts(2);
  16702. auto start = std::chrono::steady_clock::now();
  16703. sse.start(); // Blocking call
  16704. auto end = std::chrono::steady_clock::now();
  16705. // Should have stopped after 2 failed attempts
  16706. EXPECT_GE(error_count.load(), 2);
  16707. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  16708. auto duration =
  16709. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  16710. #ifdef _WIN32
  16711. // Windows is much slower for socket connection failures
  16712. EXPECT_LT(duration.count(), 7000);
  16713. #else
  16714. EXPECT_LT(duration.count(), 1000);
  16715. #endif
  16716. }
  16717. // Test: Multi-line data in integration
  16718. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  16719. // Endpoint with multi-line data
  16720. server_->Get("/multiline-data", [](const Request &, Response &res) {
  16721. res.set_chunked_content_provider(
  16722. "text/event-stream", [](size_t offset, DataSink &sink) {
  16723. if (offset == 0) {
  16724. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  16725. sink.write(event.data(), event.size());
  16726. }
  16727. return false;
  16728. });
  16729. });
  16730. Client client("localhost", get_port());
  16731. sse::SSEClient sse(client, "/multiline-data");
  16732. std::string received_data;
  16733. std::mutex data_mutex;
  16734. sse.on_message([&](const sse::SSEMessage &msg) {
  16735. std::lock_guard<std::mutex> lock(data_mutex);
  16736. received_data = msg.data;
  16737. });
  16738. sse.set_reconnect_interval(100);
  16739. sse.set_max_reconnect_attempts(1);
  16740. sse.start_async();
  16741. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16742. sse.stop();
  16743. std::lock_guard<std::mutex> lock(data_mutex);
  16744. EXPECT_EQ(received_data, "line1\nline2\nline3");
  16745. }
  16746. // Test: Auto-reconnect after server disconnection
  16747. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  16748. std::atomic<int> connection_count{0};
  16749. std::atomic<int> message_count{0};
  16750. // Endpoint that sends one event and closes, forcing reconnect
  16751. server_->Get("/reconnect-test",
  16752. [&connection_count](const Request &, Response &res) {
  16753. connection_count.fetch_add(1);
  16754. res.set_chunked_content_provider(
  16755. "text/event-stream", [](size_t offset, DataSink &sink) {
  16756. if (offset == 0) {
  16757. std::string event = "data: hello\n\n";
  16758. sink.write(event.data(), event.size());
  16759. }
  16760. return false; // Close connection after sending
  16761. });
  16762. });
  16763. Client client("localhost", get_port());
  16764. sse::SSEClient sse(client, "/reconnect-test");
  16765. sse.on_message([&message_count](const sse::SSEMessage &) {
  16766. message_count.fetch_add(1);
  16767. });
  16768. sse.set_reconnect_interval(100);
  16769. sse.set_max_reconnect_attempts(3);
  16770. sse.start_async();
  16771. // Wait long enough for multiple reconnects
  16772. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16773. sse.stop();
  16774. // Should have connected multiple times (initial + reconnects)
  16775. EXPECT_GE(connection_count.load(), 2);
  16776. // Should have received messages from multiple connections
  16777. EXPECT_GE(message_count.load(), 2);
  16778. }
  16779. // Test: Last-Event-ID sent on reconnect
  16780. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  16781. std::atomic<int> connection_count{0};
  16782. std::vector<std::string> received_last_event_ids;
  16783. std::mutex id_mutex;
  16784. // Endpoint that checks Last-Event-ID header and sends event with ID
  16785. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  16786. int conn = connection_count.fetch_add(1);
  16787. // Capture the Last-Event-ID header from each connection
  16788. {
  16789. std::lock_guard<std::mutex> lock(id_mutex);
  16790. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  16791. }
  16792. res.set_chunked_content_provider(
  16793. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  16794. if (offset == 0) {
  16795. std::string event =
  16796. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  16797. sink.write(event.data(), event.size());
  16798. }
  16799. return false;
  16800. });
  16801. });
  16802. Client client("localhost", get_port());
  16803. sse::SSEClient sse(client, "/reconnect-with-id");
  16804. sse.set_reconnect_interval(100);
  16805. sse.set_max_reconnect_attempts(3);
  16806. sse.start_async();
  16807. // Wait for at least 2 connections
  16808. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16809. sse.stop();
  16810. // Verify behavior
  16811. std::lock_guard<std::mutex> lock(id_mutex);
  16812. EXPECT_GE(received_last_event_ids.size(), 2u);
  16813. // First connection should have no Last-Event-ID
  16814. if (!received_last_event_ids.empty()) {
  16815. EXPECT_EQ(received_last_event_ids[0], "");
  16816. }
  16817. // Second connection should have Last-Event-ID from first connection
  16818. if (received_last_event_ids.size() >= 2) {
  16819. EXPECT_EQ(received_last_event_ids[1], "event-0");
  16820. }
  16821. }
  16822. // Test: set_headers updates headers used on reconnect
  16823. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  16824. std::vector<std::string> received_tokens;
  16825. std::mutex token_mutex;
  16826. // Endpoint that captures Authorization header
  16827. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  16828. {
  16829. std::lock_guard<std::mutex> lock(token_mutex);
  16830. received_tokens.push_back(req.get_header_value("Authorization"));
  16831. }
  16832. res.set_chunked_content_provider(
  16833. "text/event-stream", [](size_t offset, DataSink &sink) {
  16834. if (offset == 0) {
  16835. std::string event = "data: hello\n\n";
  16836. sink.write(event.data(), event.size());
  16837. }
  16838. return false; // Close connection to trigger reconnect
  16839. });
  16840. });
  16841. Client client("localhost", get_port());
  16842. Headers headers = {{"Authorization", "Bearer old-token"}};
  16843. sse::SSEClient sse(client, "/auth-check", headers);
  16844. // Update headers on each successful connection
  16845. sse.on_open(
  16846. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  16847. sse.set_reconnect_interval(100);
  16848. sse.set_max_reconnect_attempts(3);
  16849. sse.start_async();
  16850. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16851. sse.stop();
  16852. std::lock_guard<std::mutex> lock(token_mutex);
  16853. ASSERT_GE(received_tokens.size(), 2u);
  16854. // First connection uses original header
  16855. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  16856. // Second connection uses updated header from set_headers
  16857. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  16858. }
  16859. // Test: 401 allows reconnection (so on_error can refresh headers)
  16860. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  16861. std::atomic<int> connection_count{0};
  16862. // Endpoint: returns 401 on first attempt, 200 on second
  16863. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  16864. int conn = connection_count.fetch_add(1);
  16865. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  16866. res.status = StatusCode::Unauthorized_401;
  16867. res.set_content("Unauthorized", "text/plain");
  16868. return;
  16869. }
  16870. res.set_chunked_content_provider(
  16871. "text/event-stream", [](size_t offset, DataSink &sink) {
  16872. if (offset == 0) {
  16873. std::string event = "data: authenticated\n\n";
  16874. sink.write(event.data(), event.size());
  16875. }
  16876. return false;
  16877. });
  16878. });
  16879. Client client("localhost", get_port());
  16880. Headers headers = {{"Authorization", "Bearer expired"}};
  16881. sse::SSEClient sse(client, "/auth-retry", headers);
  16882. std::atomic<bool> message_received{false};
  16883. // Refresh token on error
  16884. sse.on_error(
  16885. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  16886. sse.on_message([&](const sse::SSEMessage &msg) {
  16887. if (msg.data == "authenticated") { message_received.store(true); }
  16888. });
  16889. sse.set_reconnect_interval(100);
  16890. sse.set_max_reconnect_attempts(3);
  16891. sse.start_async();
  16892. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16893. sse.stop();
  16894. // Should have reconnected after 401 and succeeded with new token
  16895. EXPECT_GE(connection_count.load(), 2);
  16896. EXPECT_TRUE(message_received.load());
  16897. }
  16898. TEST(Issue2318Test, EmptyHostString) {
  16899. {
  16900. httplib::Client cli_empty("", PORT);
  16901. auto res = cli_empty.Get("/");
  16902. ASSERT_FALSE(res);
  16903. EXPECT_EQ(httplib::Error::Connection, res.error());
  16904. }
  16905. {
  16906. httplib::Client cli(" ", PORT);
  16907. auto res = cli.Get("/");
  16908. ASSERT_FALSE(res);
  16909. EXPECT_EQ(httplib::Error::Connection, res.error());
  16910. }
  16911. }
  16912. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16913. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  16914. Server svr;
  16915. // Set a small payload limit (1KB)
  16916. svr.set_payload_max_length(1024);
  16917. svr.Post("/test", [&](const Request &req, Response &res) {
  16918. res.set_content("Body size: " + std::to_string(req.body.size()),
  16919. "text/plain");
  16920. });
  16921. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16922. auto se = detail::scope_exit([&] {
  16923. svr.stop();
  16924. listen_thread.join();
  16925. });
  16926. svr.wait_until_ready();
  16927. // Create data that compresses well but exceeds limit when decompressed
  16928. // 8KB of repeated null bytes compresses to a very small size
  16929. std::string original_data(8 * 1024, '\0');
  16930. // Compress the data using gzip
  16931. std::string compressed_data;
  16932. detail::gzip_compressor compressor;
  16933. compressor.compress(original_data.data(), original_data.size(), true,
  16934. [&](const char *data, size_t size) {
  16935. compressed_data.append(data, size);
  16936. return true;
  16937. });
  16938. // Verify compression worked (compressed should be much smaller)
  16939. ASSERT_LT(compressed_data.size(), original_data.size());
  16940. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  16941. // Send compressed data with Content-Encoding: gzip
  16942. Client cli(HOST, PORT);
  16943. Headers headers = {{"Content-Encoding", "gzip"}};
  16944. auto res =
  16945. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  16946. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  16947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16948. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  16949. }
  16950. #endif
  16951. // ============================================================================
  16952. // OpenSSL-Specific Tests
  16953. // ============================================================================
  16954. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16955. X509 *readCertificate(const std::string &strFileName) {
  16956. std::ifstream inStream(strFileName);
  16957. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  16958. std::istreambuf_iterator<char>());
  16959. if (strCertPEM.empty()) return (nullptr);
  16960. BIO *pbCert = BIO_new(BIO_s_mem());
  16961. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  16962. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  16963. BIO_free(pbCert);
  16964. return (pCert);
  16965. }
  16966. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  16967. std::ifstream inStream(strFileName);
  16968. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  16969. std::istreambuf_iterator<char>());
  16970. if (strPrivateKeyPEM.empty()) return (nullptr);
  16971. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  16972. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  16973. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  16974. BIO_free(pbPrivKey);
  16975. return (pPrivateKey);
  16976. }
  16977. TEST(BindServerTest, UpdateCerts) {
  16978. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16979. int port = svr.bind_to_any_port("0.0.0.0");
  16980. ASSERT_TRUE(svr.is_valid());
  16981. ASSERT_TRUE(port > 0);
  16982. X509 *cert = readCertificate(SERVER_CERT_FILE);
  16983. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  16984. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  16985. ASSERT_TRUE(cert != nullptr);
  16986. ASSERT_TRUE(ca_cert != nullptr);
  16987. ASSERT_TRUE(key != nullptr);
  16988. X509_STORE *cert_store = X509_STORE_new();
  16989. X509_STORE_add_cert(cert_store, ca_cert);
  16990. // svr.update_certs(cert, key, cert_store); // deprecated
  16991. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  16992. CLIENT_CA_CERT_FILE);
  16993. ASSERT_TRUE(svr.is_valid());
  16994. svr.stop();
  16995. X509_STORE_free(cert_store);
  16996. X509_free(cert);
  16997. X509_free(ca_cert);
  16998. EVP_PKEY_free(key);
  16999. }
  17000. // Test that update_certs() updates client CA list correctly
  17001. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  17002. // Start with file-based constructor
  17003. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17004. ASSERT_TRUE(svr.is_valid());
  17005. // Initially no client CA list should be set
  17006. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17007. ASSERT_TRUE(ssl_ctx != nullptr);
  17008. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  17009. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  17010. EXPECT_EQ(0, count_before);
  17011. // Now update with client CA (PEM string)
  17012. std::string cert_pem, key_pem, ca_pem;
  17013. read_file(SERVER_CERT_FILE, cert_pem);
  17014. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  17015. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  17016. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  17017. ASSERT_TRUE(svr.is_valid());
  17018. // Now client CA list should be set
  17019. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  17020. ASSERT_TRUE(ca_list_after != nullptr);
  17021. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  17022. }
  17023. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  17024. // Test that the file-path SSLServer constructor properly sets the client CA
  17025. // list that is sent to clients during the TLS handshake (CertificateRequest)
  17026. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17027. ASSERT_TRUE(svr.is_valid());
  17028. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17029. ASSERT_TRUE(ssl_ctx != nullptr);
  17030. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  17031. ASSERT_TRUE(ca_list != nullptr);
  17032. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  17033. }
  17034. #endif
  17035. // ============================================================================
  17036. // MbedTLS-Specific Tests
  17037. // ============================================================================
  17038. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  17039. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  17040. using namespace httplib::tls;
  17041. // Track if callback was invoked
  17042. bool callback_invoked = false;
  17043. // The callback receives void* ctx which is actually MbedTlsContext*
  17044. // We can access the mbedtls_ssl_config via the context
  17045. auto setup_callback = [&callback_invoked](void *ctx) {
  17046. callback_invoked = true;
  17047. // Cast to MbedTlsContext* to access the ssl config
  17048. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  17049. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  17050. // Use static variables to hold certificate data (simplified for test)
  17051. static mbedtls_x509_crt own_cert;
  17052. static mbedtls_pk_context own_key;
  17053. static mbedtls_x509_crt ca_chain;
  17054. static bool initialized = false;
  17055. if (!initialized) {
  17056. mbedtls_x509_crt_init(&own_cert);
  17057. mbedtls_pk_init(&own_key);
  17058. mbedtls_x509_crt_init(&ca_chain);
  17059. // Load server certificate
  17060. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  17061. return false;
  17062. }
  17063. // Load server private key.
  17064. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  17065. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  17066. #if MBEDTLS_VERSION_MAJOR == 3
  17067. ,
  17068. mbedtls_ctr_drbg_random, nullptr
  17069. #endif
  17070. ) != 0) {
  17071. return false;
  17072. }
  17073. // Load CA chain for client verification
  17074. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  17075. return false;
  17076. }
  17077. initialized = true;
  17078. }
  17079. // Configure the SSL config
  17080. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  17081. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  17082. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17083. // Set minimum TLS version using mbedTLS native API
  17084. #if MBEDTLS_VERSION_MAJOR >= 3
  17085. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17086. #else
  17087. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17088. MBEDTLS_SSL_MINOR_VERSION_3);
  17089. #endif
  17090. return true;
  17091. };
  17092. SSLServer svr(setup_callback);
  17093. ASSERT_TRUE(svr.is_valid());
  17094. ASSERT_TRUE(callback_invoked);
  17095. svr.Get("/test", [&](const Request &req, Response &res) {
  17096. res.set_content("test", "text/plain");
  17097. auto cert = req.peer_cert();
  17098. ASSERT_TRUE(static_cast<bool>(cert));
  17099. auto common_name = cert.subject_cn();
  17100. EXPECT_EQ("Common Name", common_name);
  17101. });
  17102. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17103. auto se = detail::scope_exit([&] {
  17104. svr.stop();
  17105. t.join();
  17106. ASSERT_FALSE(svr.is_running());
  17107. });
  17108. svr.wait_until_ready();
  17109. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  17110. cli.enable_server_certificate_verification(false);
  17111. cli.set_connection_timeout(30);
  17112. auto res = cli.Get("/test");
  17113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17114. ASSERT_EQ(StatusCode::OK_200, res->status);
  17115. }
  17116. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  17117. // context (owning mbedtls_ssl_config) before shutting down a still-open
  17118. // keep-alive SSL session, which reads through that config in
  17119. // mbedtls_ssl_close_notify.
  17120. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  17121. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17122. ASSERT_TRUE(svr.is_valid());
  17123. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17124. res.set_content("test", "text/plain");
  17125. });
  17126. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17127. auto se = detail::scope_exit([&] {
  17128. svr.stop();
  17129. t.join();
  17130. ASSERT_FALSE(svr.is_running());
  17131. });
  17132. svr.wait_until_ready();
  17133. {
  17134. SSLClient cli(HOST, PORT);
  17135. cli.enable_server_certificate_verification(false);
  17136. cli.set_keep_alive(true);
  17137. auto res = cli.Get("/test");
  17138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17139. ASSERT_EQ(StatusCode::OK_200, res->status);
  17140. // cli is destructed here with the keep-alive SSL session still open.
  17141. }
  17142. }
  17143. #endif
  17144. // WebSocket Tests
  17145. TEST(WebSocketTest, RSVBitsMustBeZero) {
  17146. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  17147. // defining the meaning of these bits has been negotiated.
  17148. auto make_frame = [](uint8_t first_byte) {
  17149. std::string frame;
  17150. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  17151. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  17152. frame += "Hello";
  17153. return frame;
  17154. };
  17155. // RSV1 set (0x40)
  17156. {
  17157. detail::BufferStream strm;
  17158. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  17159. ws::Opcode opcode;
  17160. std::string payload;
  17161. bool fin;
  17162. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17163. false, 1024));
  17164. }
  17165. // RSV2 set (0x20)
  17166. {
  17167. detail::BufferStream strm;
  17168. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  17169. ws::Opcode opcode;
  17170. std::string payload;
  17171. bool fin;
  17172. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17173. false, 1024));
  17174. }
  17175. // RSV3 set (0x10)
  17176. {
  17177. detail::BufferStream strm;
  17178. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  17179. ws::Opcode opcode;
  17180. std::string payload;
  17181. bool fin;
  17182. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17183. false, 1024));
  17184. }
  17185. // No RSV bits set - should succeed
  17186. {
  17187. detail::BufferStream strm;
  17188. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  17189. ws::Opcode opcode;
  17190. std::string payload;
  17191. bool fin;
  17192. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17193. false, 1024));
  17194. EXPECT_EQ(ws::Opcode::Text, opcode);
  17195. EXPECT_EQ("Hello", payload);
  17196. EXPECT_TRUE(fin);
  17197. }
  17198. }
  17199. TEST(WebSocketTest, ControlFrameValidation) {
  17200. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  17201. // payload length <= 125.
  17202. // Ping with FIN=0 - must be rejected
  17203. {
  17204. detail::BufferStream strm;
  17205. std::string frame;
  17206. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  17207. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17208. strm.write(frame.data(), frame.size());
  17209. ws::Opcode opcode;
  17210. std::string payload;
  17211. bool fin;
  17212. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17213. false, 1024));
  17214. }
  17215. // Close with FIN=0 - must be rejected
  17216. {
  17217. detail::BufferStream strm;
  17218. std::string frame;
  17219. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  17220. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17221. strm.write(frame.data(), frame.size());
  17222. ws::Opcode opcode;
  17223. std::string payload;
  17224. bool fin;
  17225. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17226. false, 1024));
  17227. }
  17228. // Ping with payload_len=126 (extended length) - must be rejected
  17229. {
  17230. detail::BufferStream strm;
  17231. std::string frame;
  17232. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17233. frame += static_cast<char>(126); // payload_len=126 (>125)
  17234. frame += static_cast<char>(0x00); // extended length high byte
  17235. frame += static_cast<char>(126); // extended length low byte
  17236. frame += std::string(126, 'x');
  17237. strm.write(frame.data(), frame.size());
  17238. ws::Opcode opcode;
  17239. std::string payload;
  17240. bool fin;
  17241. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17242. false, 1024));
  17243. }
  17244. // Ping with FIN=1 and payload_len=125 - should succeed
  17245. {
  17246. detail::BufferStream strm;
  17247. std::string frame;
  17248. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17249. frame += static_cast<char>(125); // payload_len=125
  17250. frame += std::string(125, 'x');
  17251. strm.write(frame.data(), frame.size());
  17252. ws::Opcode opcode;
  17253. std::string payload;
  17254. bool fin;
  17255. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17256. false, 1024));
  17257. EXPECT_EQ(ws::Opcode::Ping, opcode);
  17258. EXPECT_EQ(125u, payload.size());
  17259. EXPECT_TRUE(fin);
  17260. }
  17261. }
  17262. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  17263. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  17264. // length MUST be 0.
  17265. // MSB set - must be rejected
  17266. {
  17267. detail::BufferStream strm;
  17268. std::string frame;
  17269. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17270. frame += static_cast<char>(127); // 64-bit extended length
  17271. frame += static_cast<char>(0x80); // MSB set (invalid)
  17272. frame += std::string(7, '\0'); // remaining 7 bytes of length
  17273. strm.write(frame.data(), frame.size());
  17274. ws::Opcode opcode;
  17275. std::string payload;
  17276. bool fin;
  17277. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17278. false, 1024));
  17279. }
  17280. // MSB clear - should pass length parsing (will be rejected by max_len,
  17281. // but that's a different check; use a small length to verify)
  17282. {
  17283. detail::BufferStream strm;
  17284. std::string frame;
  17285. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17286. frame += static_cast<char>(127); // 64-bit extended length
  17287. frame += std::string(7, '\0'); // high bytes = 0
  17288. frame += static_cast<char>(0x03); // length = 3
  17289. frame += "abc";
  17290. strm.write(frame.data(), frame.size());
  17291. ws::Opcode opcode;
  17292. std::string payload;
  17293. bool fin;
  17294. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17295. false, 1024));
  17296. EXPECT_EQ(ws::Opcode::Text, opcode);
  17297. EXPECT_EQ("abc", payload);
  17298. }
  17299. }
  17300. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  17301. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  17302. // Valid UTF-8
  17303. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  17304. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  17305. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  17306. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  17307. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  17308. // Invalid UTF-8
  17309. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  17310. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  17311. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  17312. EXPECT_FALSE(
  17313. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  17314. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  17315. }
  17316. TEST(WebSocketTest, ConnectAndDisconnect) {
  17317. Server svr;
  17318. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17319. std::string msg;
  17320. while (ws.read(msg)) {}
  17321. });
  17322. auto port = svr.bind_to_any_port(HOST);
  17323. std::thread t([&]() { svr.listen_after_bind(); });
  17324. svr.wait_until_ready();
  17325. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17326. auto res = client.connect();
  17327. ASSERT_TRUE(res);
  17328. EXPECT_EQ(Error::Success, res.error());
  17329. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  17330. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  17331. EXPECT_TRUE(client.is_open());
  17332. client.close();
  17333. EXPECT_FALSE(client.is_open());
  17334. svr.stop();
  17335. t.join();
  17336. }
  17337. TEST(WebSocketTest, ValidURL) {
  17338. ws::WebSocketClient ws1("ws://localhost:8080/path");
  17339. EXPECT_TRUE(ws1.is_valid());
  17340. ws::WebSocketClient ws2("ws://example.com/path");
  17341. EXPECT_TRUE(ws2.is_valid());
  17342. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  17343. EXPECT_TRUE(ws3.is_valid());
  17344. #ifdef CPPHTTPLIB_SSL_ENABLED
  17345. ws::WebSocketClient wss1("wss://example.com/path");
  17346. EXPECT_TRUE(wss1.is_valid());
  17347. ws::WebSocketClient wss2("wss://example.com:443/path");
  17348. EXPECT_TRUE(wss2.is_valid());
  17349. #endif
  17350. }
  17351. TEST(WebSocketTest, InvalidURL) {
  17352. // No scheme
  17353. ws::WebSocketClient ws1("localhost:8080/path");
  17354. EXPECT_FALSE(ws1.is_valid());
  17355. // No path
  17356. ws::WebSocketClient ws2("ws://localhost:8080");
  17357. EXPECT_FALSE(ws2.is_valid());
  17358. // Empty string
  17359. ws::WebSocketClient ws3("");
  17360. EXPECT_FALSE(ws3.is_valid());
  17361. // Missing host
  17362. ws::WebSocketClient ws4("ws://:8080/path");
  17363. EXPECT_FALSE(ws4.is_valid());
  17364. // Port number overflow — should not crash
  17365. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  17366. EXPECT_FALSE(ws5.is_valid());
  17367. // Port out of range
  17368. ws::WebSocketClient ws6("ws://localhost:99999/path");
  17369. EXPECT_FALSE(ws6.is_valid());
  17370. }
  17371. TEST(WebSocketTest, UnsupportedScheme) {
  17372. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17373. ws::WebSocketClient ws1("http://localhost:8080/path");
  17374. EXPECT_FALSE(ws1.is_valid());
  17375. ws::WebSocketClient ws2("https://localhost:8080/path");
  17376. EXPECT_FALSE(ws2.is_valid());
  17377. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  17378. EXPECT_FALSE(ws3.is_valid());
  17379. #else
  17380. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  17381. std::invalid_argument);
  17382. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  17383. std::invalid_argument);
  17384. #endif
  17385. }
  17386. TEST(WebSocketTest, ConnectWhenInvalid) {
  17387. ws::WebSocketClient ws("not a valid url");
  17388. EXPECT_FALSE(ws.is_valid());
  17389. auto res = ws.connect();
  17390. EXPECT_FALSE(res);
  17391. EXPECT_EQ(Error::Connection, res.error());
  17392. EXPECT_EQ(-1, res.status());
  17393. }
  17394. TEST(WebSocketTest, ConnectRefusedReportsError) {
  17395. // Grab a port that is free, then close it again so nothing listens there
  17396. Server svr;
  17397. auto port = svr.bind_to_any_port(HOST);
  17398. svr.stop();
  17399. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17400. auto res = client.connect();
  17401. ASSERT_FALSE(res);
  17402. EXPECT_EQ(Error::Connection, res.error());
  17403. EXPECT_EQ(-1, res.status());
  17404. }
  17405. TEST(WebSocketTest, DefaultPort) {
  17406. ws::WebSocketClient ws1("ws://example.com/path");
  17407. EXPECT_TRUE(ws1.is_valid());
  17408. // ws:// defaults to port 80 (verified by successful parse)
  17409. #ifdef CPPHTTPLIB_SSL_ENABLED
  17410. ws::WebSocketClient ws2("wss://example.com/path");
  17411. EXPECT_TRUE(ws2.is_valid());
  17412. // wss:// defaults to port 443 (verified by successful parse)
  17413. #endif
  17414. }
  17415. TEST(WebSocketTest, IPv6LiteralAddress) {
  17416. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  17417. EXPECT_TRUE(ws1.is_valid());
  17418. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  17419. EXPECT_TRUE(ws2.is_valid());
  17420. }
  17421. TEST(WebSocketTest, ComplexPath) {
  17422. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  17423. EXPECT_TRUE(ws1.is_valid());
  17424. ws::WebSocketClient ws2("ws://localhost:8080/");
  17425. EXPECT_TRUE(ws2.is_valid());
  17426. }
  17427. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  17428. Server svr;
  17429. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17430. std::string msg;
  17431. while (ws.read(msg)) {}
  17432. });
  17433. auto port = svr.bind_to_any_port(HOST);
  17434. std::thread t([&]() { svr.listen_after_bind(); });
  17435. svr.wait_until_ready();
  17436. auto another_host = "example.com";
  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({{another_host, wrong_ip}});
  17440. ASSERT_TRUE(client.connect());
  17441. EXPECT_TRUE(client.is_open());
  17442. client.close();
  17443. svr.stop();
  17444. t.join();
  17445. }
  17446. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  17447. Server svr;
  17448. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17449. std::string msg;
  17450. while (ws.read(msg)) {}
  17451. });
  17452. auto port = svr.bind_to_any_port(HOST);
  17453. std::thread t([&]() { svr.listen_after_bind(); });
  17454. svr.wait_until_ready();
  17455. auto wrong_ip = "192.0.2.1";
  17456. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17457. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  17458. client.set_connection_timeout(1);
  17459. client.set_read_timeout(1);
  17460. client.set_write_timeout(1);
  17461. EXPECT_FALSE(client.connect());
  17462. EXPECT_FALSE(client.is_open());
  17463. svr.stop();
  17464. t.join();
  17465. }
  17466. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  17467. // A mapped value that is not an IP literal must be resolved. HOST resolves
  17468. // from the hosts file, so this test needs no external DNS. "target.invalid"
  17469. // (RFC 6761) is only a map key and the Host header value.
  17470. auto host = "target.invalid";
  17471. Server svr;
  17472. std::string received_host;
  17473. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17474. received_host = req.get_header_value("Host");
  17475. std::string msg;
  17476. while (ws.read(msg)) {}
  17477. });
  17478. auto port = svr.bind_to_any_port(HOST);
  17479. std::thread t([&]() { svr.listen_after_bind(); });
  17480. // ASSERT_* below returns from the test body, which would leave t joinable
  17481. // and make ~thread call std::terminate.
  17482. auto se = detail::scope_exit([&] {
  17483. svr.stop();
  17484. if (t.joinable()) { t.join(); }
  17485. });
  17486. svr.wait_until_ready();
  17487. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  17488. std::to_string(port) + "/ws");
  17489. client.set_hostname_addr_map({{host, HOST}});
  17490. ASSERT_TRUE(client.connect());
  17491. EXPECT_TRUE(client.is_open());
  17492. client.close();
  17493. svr.stop();
  17494. t.join();
  17495. // The mapping only redirects the connection; the identity stays host_.
  17496. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  17497. }
  17498. class WebSocketIntegrationTest : public ::testing::Test {
  17499. protected:
  17500. void SetUp() override {
  17501. server_ = httplib::detail::make_unique<Server>();
  17502. setup_server();
  17503. start_server();
  17504. }
  17505. void TearDown() override {
  17506. server_->stop();
  17507. if (server_thread_.joinable()) { server_thread_.join(); }
  17508. }
  17509. void setup_server() {
  17510. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17511. std::string msg;
  17512. ws::ReadResult ret;
  17513. while ((ret = ws.read(msg))) {
  17514. if (ret == ws::Binary) {
  17515. ws.send(msg.data(), msg.size());
  17516. } else {
  17517. ws.send(msg);
  17518. }
  17519. }
  17520. });
  17521. server_->WebSocket("/ws-echo-string",
  17522. [](const Request &, ws::WebSocket &ws) {
  17523. std::string msg;
  17524. while (ws.read(msg)) {
  17525. ws.send("echo: " + msg);
  17526. }
  17527. });
  17528. server_->WebSocket(
  17529. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  17530. // Echo back request metadata
  17531. ws.send("path:" + req.path);
  17532. ws.send("header:" + req.get_header_value("X-Test-Header"));
  17533. std::string msg;
  17534. while (ws.read(msg)) {}
  17535. });
  17536. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  17537. std::string msg;
  17538. ws.read(msg); // wait for a message
  17539. ws.close();
  17540. });
  17541. server_->WebSocket("/ws-close-status",
  17542. [](const Request &, ws::WebSocket &ws) {
  17543. std::string msg;
  17544. ws.read(msg); // wait for a message
  17545. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  17546. });
  17547. server_->WebSocket(
  17548. "/ws-subprotocol",
  17549. [](const Request &, ws::WebSocket &ws) {
  17550. std::string msg;
  17551. while (ws.read(msg)) {
  17552. ws.send(msg);
  17553. }
  17554. },
  17555. [](const std::vector<std::string> &protocols) -> std::string {
  17556. for (const auto &p : protocols) {
  17557. if (p == "graphql-ws") { return p; }
  17558. }
  17559. return "";
  17560. });
  17561. }
  17562. void start_server() {
  17563. port_ = server_->bind_to_any_port(HOST);
  17564. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17565. server_->wait_until_ready();
  17566. }
  17567. std::unique_ptr<Server> server_;
  17568. std::thread server_thread_;
  17569. int port_ = 0;
  17570. };
  17571. TEST_F(WebSocketIntegrationTest, TextEcho) {
  17572. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17573. "/ws-echo");
  17574. ASSERT_TRUE(client.connect());
  17575. ASSERT_TRUE(client.is_open());
  17576. ASSERT_TRUE(client.send("Hello WebSocket"));
  17577. std::string msg;
  17578. EXPECT_EQ(ws::Text, client.read(msg));
  17579. EXPECT_EQ("Hello WebSocket", msg);
  17580. client.close();
  17581. }
  17582. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  17583. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17584. "/ws-echo");
  17585. ASSERT_TRUE(client.connect());
  17586. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  17587. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  17588. std::string msg;
  17589. EXPECT_EQ(ws::Binary, client.read(msg));
  17590. EXPECT_EQ(binary_data, msg);
  17591. client.close();
  17592. }
  17593. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  17594. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17595. "/ws-echo");
  17596. ASSERT_TRUE(client.connect());
  17597. for (int i = 0; i < 10; i++) {
  17598. auto text = "message " + std::to_string(i);
  17599. ASSERT_TRUE(client.send(text));
  17600. std::string msg;
  17601. ASSERT_TRUE(client.read(msg));
  17602. EXPECT_EQ(text, msg);
  17603. }
  17604. client.close();
  17605. }
  17606. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  17607. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17608. "/ws-close");
  17609. ASSERT_TRUE(client.connect());
  17610. // Send a message to trigger the server to close
  17611. ASSERT_TRUE(client.send("trigger close"));
  17612. // The server will close, so read should return false
  17613. std::string msg;
  17614. EXPECT_FALSE(client.read(msg));
  17615. EXPECT_FALSE(client.is_open());
  17616. }
  17617. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  17618. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17619. "/ws-echo");
  17620. ASSERT_TRUE(client.connect());
  17621. // 128KB message
  17622. std::string large_data(128 * 1024, 'X');
  17623. ASSERT_TRUE(client.send(large_data));
  17624. std::string msg;
  17625. ASSERT_TRUE(client.read(msg));
  17626. EXPECT_EQ(large_data, msg);
  17627. client.close();
  17628. }
  17629. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  17630. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17631. "/ws-echo");
  17632. ASSERT_TRUE(client.connect());
  17633. const int num_threads = 4;
  17634. std::vector<std::thread> threads;
  17635. std::atomic<int> send_count{0};
  17636. for (int t = 0; t < num_threads; t++) {
  17637. threads.emplace_back([&client, &send_count, t]() {
  17638. for (int i = 0; i < 5; i++) {
  17639. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  17640. if (client.send(text)) { send_count++; }
  17641. }
  17642. });
  17643. }
  17644. for (auto &th : threads) {
  17645. th.join();
  17646. }
  17647. int received = 0;
  17648. std::string msg;
  17649. while (received < send_count.load()) {
  17650. if (!client.read(msg)) { break; }
  17651. received++;
  17652. }
  17653. EXPECT_EQ(send_count.load(), received);
  17654. client.close();
  17655. }
  17656. TEST_F(WebSocketIntegrationTest, ReadString) {
  17657. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17658. "/ws-echo-string");
  17659. ASSERT_TRUE(client.connect());
  17660. ASSERT_TRUE(client.send("hello"));
  17661. std::string msg;
  17662. ASSERT_TRUE(client.read(msg));
  17663. EXPECT_EQ("echo: hello", msg);
  17664. ASSERT_TRUE(client.send("world"));
  17665. ASSERT_TRUE(client.read(msg));
  17666. EXPECT_EQ("echo: world", msg);
  17667. client.close();
  17668. }
  17669. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  17670. Headers headers = {{"X-Test-Header", "test-value"}};
  17671. ws::WebSocketClient client(
  17672. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  17673. ASSERT_TRUE(client.connect());
  17674. std::string msg;
  17675. ASSERT_TRUE(client.read(msg));
  17676. EXPECT_EQ("path:/ws-request-info", msg);
  17677. ASSERT_TRUE(client.read(msg));
  17678. EXPECT_EQ("header:test-value", msg);
  17679. client.close();
  17680. }
  17681. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  17682. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17683. "/ws-echo");
  17684. client.set_read_timeout(1, 0); // 1 second
  17685. ASSERT_TRUE(client.connect());
  17686. // Don't send anything — server echo handler waits for a message,
  17687. // so read() should time out and return false.
  17688. std::string msg;
  17689. EXPECT_FALSE(client.read(msg));
  17690. }
  17691. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  17692. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17693. "/ws-echo");
  17694. client.set_read_timeout(5, 0);
  17695. ASSERT_TRUE(client.connect());
  17696. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17697. // The server should reject it and close the connection.
  17698. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  17699. client.send(oversized);
  17700. // The server's read() should have failed due to payload limit,
  17701. // so our read() should return false (connection closed).
  17702. std::string msg;
  17703. EXPECT_FALSE(client.read(msg));
  17704. }
  17705. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  17706. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17707. "/ws-echo");
  17708. client.set_read_timeout(10, 0);
  17709. ASSERT_TRUE(client.connect());
  17710. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17711. // This should succeed.
  17712. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  17713. ASSERT_TRUE(client.send(at_limit));
  17714. std::string msg;
  17715. ASSERT_TRUE(client.read(msg));
  17716. EXPECT_EQ(at_limit.size(), msg.size());
  17717. client.close();
  17718. }
  17719. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  17720. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17721. "/nonexistent");
  17722. auto res = client.connect();
  17723. EXPECT_FALSE(res);
  17724. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  17725. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  17726. EXPECT_FALSE(client.is_open());
  17727. }
  17728. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  17729. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17730. "/ws-echo");
  17731. ASSERT_TRUE(client.connect());
  17732. ASSERT_TRUE(client.send(""));
  17733. std::string msg;
  17734. EXPECT_EQ(ws::Text, client.read(msg));
  17735. EXPECT_EQ("", msg);
  17736. client.close();
  17737. }
  17738. TEST_F(WebSocketIntegrationTest, Reconnect) {
  17739. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17740. "/ws-echo");
  17741. // First connection
  17742. ASSERT_TRUE(client.connect());
  17743. ASSERT_TRUE(client.send("first"));
  17744. std::string msg;
  17745. ASSERT_TRUE(client.read(msg));
  17746. EXPECT_EQ("first", msg);
  17747. client.close();
  17748. EXPECT_FALSE(client.is_open());
  17749. // Reconnect using the same client object
  17750. ASSERT_TRUE(client.connect());
  17751. ASSERT_TRUE(client.is_open());
  17752. ASSERT_TRUE(client.send("second"));
  17753. ASSERT_TRUE(client.read(msg));
  17754. EXPECT_EQ("second", msg);
  17755. client.close();
  17756. }
  17757. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  17758. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17759. "/ws-close-status");
  17760. ASSERT_TRUE(client.connect());
  17761. // Trigger the server to close with GoingAway status
  17762. ASSERT_TRUE(client.send("trigger"));
  17763. // read() should return false after receiving the close frame
  17764. std::string msg;
  17765. EXPECT_FALSE(client.read(msg));
  17766. EXPECT_FALSE(client.is_open());
  17767. }
  17768. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  17769. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17770. "/ws-echo");
  17771. ASSERT_TRUE(client.connect());
  17772. client.close(ws::CloseStatus::GoingAway, "client leaving");
  17773. EXPECT_FALSE(client.is_open());
  17774. }
  17775. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  17776. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  17777. ws::WebSocketClient client(
  17778. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17779. ASSERT_TRUE(client.connect());
  17780. // Server should have selected graphql-ws
  17781. EXPECT_EQ("graphql-ws", client.subprotocol());
  17782. client.close();
  17783. }
  17784. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  17785. Headers headers;
  17786. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  17787. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  17788. ws::WebSocketClient client(
  17789. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17790. ASSERT_TRUE(client.connect());
  17791. // The offer on the second field line counts too, so graphql-ws is selected
  17792. EXPECT_EQ("graphql-ws", client.subprotocol());
  17793. client.close();
  17794. }
  17795. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  17796. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  17797. ws::WebSocketClient client(
  17798. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17799. ASSERT_TRUE(client.connect());
  17800. // Server should not have selected any subprotocol
  17801. EXPECT_TRUE(client.subprotocol().empty());
  17802. client.close();
  17803. }
  17804. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  17805. // Connect without requesting any subprotocol
  17806. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17807. "/ws-subprotocol");
  17808. ASSERT_TRUE(client.connect());
  17809. EXPECT_TRUE(client.subprotocol().empty());
  17810. client.close();
  17811. }
  17812. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  17813. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17814. "/ws-echo");
  17815. client.set_tcp_nodelay(true);
  17816. client.set_connection_timeout(3, 0);
  17817. bool socket_options_called = false;
  17818. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  17819. ASSERT_TRUE(client.connect());
  17820. ASSERT_TRUE(client.is_open());
  17821. EXPECT_TRUE(socket_options_called);
  17822. ASSERT_TRUE(client.send("hello"));
  17823. std::string msg;
  17824. auto result = client.read(msg);
  17825. EXPECT_EQ(result, ws::ReadResult::Text);
  17826. EXPECT_EQ(msg, "hello");
  17827. client.close();
  17828. }
  17829. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  17830. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17831. "/ws-echo");
  17832. client.set_connection_timeout(std::chrono::seconds(3));
  17833. client.set_write_timeout(std::chrono::seconds(3));
  17834. // A sub-second remainder exercises the seconds/microseconds split.
  17835. client.set_read_timeout(std::chrono::milliseconds(1500));
  17836. ASSERT_TRUE(client.connect());
  17837. auto start = std::chrono::steady_clock::now();
  17838. std::string msg;
  17839. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  17840. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17841. std::chrono::steady_clock::now() - start)
  17842. .count();
  17843. // Above 1s so that dropping the microseconds half of the split fails here,
  17844. // and well under the 300s default so that ignoring the setter fails too.
  17845. EXPECT_GE(elapsed, 1400);
  17846. EXPECT_LT(elapsed, 30000);
  17847. }
  17848. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  17849. Server svr;
  17850. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  17851. if (!req.has_header("Authorization")) {
  17852. res.status = StatusCode::Unauthorized_401;
  17853. res.set_content("Unauthorized", "text/plain");
  17854. return Server::HandlerResponse::Handled;
  17855. }
  17856. return Server::HandlerResponse::Unhandled;
  17857. });
  17858. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17859. std::string msg;
  17860. while (ws.read(msg)) {
  17861. ws.send(msg);
  17862. }
  17863. });
  17864. auto port = svr.bind_to_any_port("localhost");
  17865. std::thread t([&]() { svr.listen_after_bind(); });
  17866. svr.wait_until_ready();
  17867. // Without Authorization header - should be rejected before upgrade
  17868. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  17869. EXPECT_FALSE(client1.connect());
  17870. // With Authorization header - should succeed
  17871. Headers headers = {{"Authorization", "Bearer token123"}};
  17872. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  17873. headers);
  17874. ASSERT_TRUE(client2.connect());
  17875. ASSERT_TRUE(client2.send("hello"));
  17876. std::string msg;
  17877. ASSERT_TRUE(client2.read(msg));
  17878. EXPECT_EQ("hello", msg);
  17879. client2.close();
  17880. svr.stop();
  17881. t.join();
  17882. }
  17883. TEST(WebSocketTest, QueryStringInHandshake) {
  17884. Server svr;
  17885. std::mutex mtx;
  17886. std::string received_target;
  17887. std::string received_token;
  17888. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17889. {
  17890. std::lock_guard<std::mutex> lock(mtx);
  17891. received_target = req.target;
  17892. if (req.has_param("token")) {
  17893. received_token = req.get_param_value("token");
  17894. }
  17895. }
  17896. std::string msg;
  17897. while (ws.read(msg)) {
  17898. ws.send(msg);
  17899. }
  17900. });
  17901. auto port = svr.bind_to_any_port("localhost");
  17902. std::thread t([&]() { svr.listen_after_bind(); });
  17903. svr.wait_until_ready();
  17904. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  17905. "/ws?token=ABC&session=123");
  17906. ASSERT_TRUE(client.connect());
  17907. // Round-trip ensures the handler has run and captured the request.
  17908. ASSERT_TRUE(client.send("hello"));
  17909. std::string msg;
  17910. ASSERT_TRUE(client.read(msg));
  17911. EXPECT_EQ("hello", msg);
  17912. client.close();
  17913. {
  17914. std::lock_guard<std::mutex> lock(mtx);
  17915. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  17916. EXPECT_EQ("ABC", received_token);
  17917. }
  17918. svr.stop();
  17919. t.join();
  17920. }
  17921. // Run a handshake against a throwaway server and hand the request the server
  17922. // received back to the caller, so tests can assert on the headers the client
  17923. // actually put on the wire.
  17924. static void capture_websocket_handshake_request(
  17925. const Headers &client_headers,
  17926. std::function<void(const Request &, int port)> verify) {
  17927. Server svr;
  17928. std::mutex mtx;
  17929. Request received;
  17930. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17931. {
  17932. std::lock_guard<std::mutex> lock(mtx);
  17933. received = req;
  17934. }
  17935. std::string msg;
  17936. while (ws.read(msg)) {
  17937. ws.send(msg);
  17938. }
  17939. });
  17940. auto port = svr.bind_to_any_port("localhost");
  17941. std::thread t([&]() { svr.listen_after_bind(); });
  17942. auto se = detail::scope_exit([&] {
  17943. svr.stop();
  17944. t.join();
  17945. });
  17946. svr.wait_until_ready();
  17947. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  17948. client_headers);
  17949. ASSERT_TRUE(client.connect());
  17950. ASSERT_TRUE(client.send("hello"));
  17951. std::string msg;
  17952. ASSERT_TRUE(client.read(msg));
  17953. client.close();
  17954. {
  17955. std::lock_guard<std::mutex> lock(mtx);
  17956. verify(received, port);
  17957. }
  17958. }
  17959. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  17960. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  17961. // Non-default port must be present in the Host header. Default ports
  17962. // (80/443) are omitted; that logic is covered by
  17963. // MakeHostAndPortStringTest.
  17964. EXPECT_EQ("localhost:" + std::to_string(port),
  17965. req.get_header_value("Host"));
  17966. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  17967. req.get_header_value("User-Agent"));
  17968. EXPECT_FALSE(req.has_header("Accept"));
  17969. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  17970. EXPECT_FALSE(req.has_header("Content-Length"));
  17971. });
  17972. }
  17973. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  17974. capture_websocket_handshake_request(
  17975. {{"Host", "example.com"},
  17976. {"User-Agent", "custom-agent"},
  17977. {"X-Custom", "value"}},
  17978. [](const Request &req, int) {
  17979. EXPECT_EQ("example.com", req.get_header_value("Host"));
  17980. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  17981. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  17982. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  17983. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  17984. });
  17985. }
  17986. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  17987. capture_websocket_handshake_request(
  17988. {{"Upgrade", "bogus"},
  17989. {"Connection", "close"},
  17990. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  17991. {"Sec-WebSocket-Version", "8"}},
  17992. [](const Request &req, int) {
  17993. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  17994. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  17995. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  17996. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  17997. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  17998. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  17999. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  18000. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  18001. req.get_header_value("Sec-WebSocket-Key"));
  18002. });
  18003. }
  18004. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  18005. // A header the client refuses to send must abort the handshake before any
  18006. // part of it reaches the wire; a lone request line would otherwise sit in
  18007. // the peer's buffer as a truncated request.
  18008. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18009. ASSERT_NE(INVALID_SOCKET, srv);
  18010. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  18011. sockaddr_in addr{};
  18012. addr.sin_family = AF_INET;
  18013. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  18014. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18015. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18016. ASSERT_EQ(0, ::listen(srv, 1));
  18017. sockaddr_in bound{};
  18018. socklen_t bound_len = sizeof(bound);
  18019. ASSERT_EQ(
  18020. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  18021. auto port = ntohs(bound.sin_port);
  18022. ssize_t received = -1;
  18023. std::thread t([&] {
  18024. // Bound every blocking call so a regression fails the test with a bad
  18025. // value instead of hanging the suite.
  18026. fd_set rfds;
  18027. FD_ZERO(&rfds);
  18028. FD_SET(srv, &rfds);
  18029. timeval tv{5, 0};
  18030. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  18031. 0) {
  18032. return;
  18033. }
  18034. sockaddr_in cli_addr{};
  18035. socklen_t cli_len = sizeof(cli_addr);
  18036. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18037. if (cli == INVALID_SOCKET) { return; }
  18038. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  18039. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18040. char buf[4096];
  18041. received = ::recv(cli, buf, sizeof(buf), 0);
  18042. });
  18043. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  18044. // connect() has already shut the socket down by the time it returns false,
  18045. // so the peer sees EOF without waiting for the client to be destroyed.
  18046. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  18047. {{"X-Bad", "a\r\nInjected: 1"}});
  18048. EXPECT_FALSE(client.connect());
  18049. t.join();
  18050. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  18051. EXPECT_EQ(0, received);
  18052. }
  18053. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  18054. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  18055. // contains "upgrade" as a substring is a different token and must not
  18056. // start a WebSocket handshake.
  18057. auto make_request = [](const std::vector<std::string> &connection_values) {
  18058. Request req;
  18059. req.method = "GET";
  18060. req.headers.emplace("Upgrade", "websocket");
  18061. for (const auto &value : connection_values) {
  18062. req.headers.emplace("Connection", value);
  18063. }
  18064. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18065. req.headers.emplace("Sec-WebSocket-Version", "13");
  18066. return req;
  18067. };
  18068. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  18069. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  18070. EXPECT_TRUE(
  18071. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  18072. EXPECT_TRUE(
  18073. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  18074. EXPECT_TRUE(
  18075. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  18076. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  18077. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  18078. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  18079. EXPECT_FALSE(
  18080. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  18081. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  18082. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18083. }
  18084. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  18085. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  18086. // asks recipients to match each protocol-name case-insensitively, and RFC
  18087. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  18088. // client naming websocket alongside another protocol, or on a second field
  18089. // line, is offering websocket; a value that merely contains "websocket" as a
  18090. // substring is a different protocol name and is not.
  18091. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  18092. Request req;
  18093. req.method = "GET";
  18094. for (const auto &value : upgrade_values) {
  18095. req.headers.emplace("Upgrade", value);
  18096. }
  18097. req.headers.emplace("Connection", "Upgrade");
  18098. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18099. req.headers.emplace("Sec-WebSocket-Version", "13");
  18100. return req;
  18101. };
  18102. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  18103. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  18104. EXPECT_TRUE(
  18105. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  18106. EXPECT_TRUE(
  18107. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  18108. EXPECT_TRUE(
  18109. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  18110. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  18111. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  18112. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  18113. EXPECT_FALSE(
  18114. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  18115. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  18116. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18117. }
  18118. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  18119. Server svr;
  18120. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  18121. auto port = svr.bind_to_any_port("localhost");
  18122. std::thread t([&]() { svr.listen_after_bind(); });
  18123. auto se = detail::scope_exit([&] {
  18124. svr.stop();
  18125. t.join();
  18126. });
  18127. svr.wait_until_ready();
  18128. Headers headers = {{"Upgrade", "websocket"},
  18129. {"Connection", "notupgrade"},
  18130. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  18131. {"Sec-WebSocket-Version", "13"}};
  18132. Client cli("localhost", port);
  18133. auto res = cli.Get("/ws", headers);
  18134. // The route exists only as a WebSocket route, so a request that fails the
  18135. // handshake check falls through to ordinary routing.
  18136. ASSERT_TRUE(res);
  18137. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  18138. }
  18139. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  18140. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  18141. // Connection value is the only thing left for the client to reject.
  18142. Server svr;
  18143. svr.Get("/ws", [](const Request &req, Response &res) {
  18144. res.status = StatusCode::SwitchingProtocol_101;
  18145. res.set_header("Upgrade", "websocket");
  18146. res.set_header("Connection", "notupgrade");
  18147. res.set_header("Sec-WebSocket-Accept",
  18148. detail::websocket_accept_key(
  18149. req.get_header_value("Sec-WebSocket-Key")));
  18150. });
  18151. auto port = svr.bind_to_any_port("localhost");
  18152. std::thread t([&]() { svr.listen_after_bind(); });
  18153. auto se = detail::scope_exit([&] {
  18154. svr.stop();
  18155. t.join();
  18156. });
  18157. svr.wait_until_ready();
  18158. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18159. auto res = client.connect();
  18160. EXPECT_FALSE(res);
  18161. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18162. EXPECT_FALSE(client.is_open());
  18163. }
  18164. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  18165. // The socket path doubles as the URL host, so it must not contain '/'.
  18166. const char *shard = getenv("GTEST_SHARD_INDEX");
  18167. const std::string sock_path =
  18168. shard ? std::string("httplib-ws-") + shard + ".sock"
  18169. : std::string("httplib-ws.sock");
  18170. std::remove(sock_path.c_str());
  18171. Server svr;
  18172. std::mutex mtx;
  18173. std::string received_host;
  18174. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18175. {
  18176. std::lock_guard<std::mutex> lock(mtx);
  18177. received_host = req.get_header_value("Host");
  18178. }
  18179. std::string msg;
  18180. while (ws.read(msg)) {
  18181. ws.send(msg);
  18182. }
  18183. });
  18184. svr.set_address_family(AF_UNIX);
  18185. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  18186. auto se = detail::scope_exit([&] {
  18187. svr.stop();
  18188. t.join();
  18189. std::remove(sock_path.c_str());
  18190. });
  18191. svr.wait_until_ready();
  18192. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  18193. client.set_address_family(AF_UNIX);
  18194. ASSERT_TRUE(client.connect());
  18195. ASSERT_TRUE(client.send("hello"));
  18196. std::string msg;
  18197. ASSERT_TRUE(client.read(msg));
  18198. client.close();
  18199. {
  18200. std::lock_guard<std::mutex> lock(mtx);
  18201. // There is no host:port for a Unix socket, so the same "localhost"
  18202. // placeholder the HTTP client uses is expected.
  18203. EXPECT_EQ("localhost", received_host);
  18204. }
  18205. }
  18206. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18207. class WebSocketSSLIntegrationTest : public ::testing::Test {
  18208. protected:
  18209. void SetUp() override {
  18210. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  18211. SERVER_PRIVATE_KEY_FILE);
  18212. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18213. std::string msg;
  18214. ws::ReadResult ret;
  18215. while ((ret = ws.read(msg))) {
  18216. if (ret == ws::Binary) {
  18217. ws.send(msg.data(), msg.size());
  18218. } else {
  18219. ws.send(msg);
  18220. }
  18221. }
  18222. });
  18223. port_ = server_->bind_to_any_port(HOST);
  18224. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18225. server_->wait_until_ready();
  18226. }
  18227. void TearDown() override {
  18228. server_->stop();
  18229. if (server_thread_.joinable()) { server_thread_.join(); }
  18230. }
  18231. std::unique_ptr<SSLServer> server_;
  18232. std::thread server_thread_;
  18233. int port_ = 0;
  18234. };
  18235. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  18236. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18237. "/ws-echo");
  18238. client.enable_server_certificate_verification(false);
  18239. ASSERT_TRUE(client.connect());
  18240. ASSERT_TRUE(client.is_open());
  18241. ASSERT_TRUE(client.send("Hello WSS"));
  18242. std::string msg;
  18243. EXPECT_EQ(ws::Text, client.read(msg));
  18244. EXPECT_EQ("Hello WSS", msg);
  18245. client.close();
  18246. }
  18247. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  18248. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  18249. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  18250. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  18251. // client (without calling close() first) is the only path that runs
  18252. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  18253. // bug exactly.
  18254. //
  18255. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  18256. // when linked against an instrumented libssl; run under Valgrind to catch it
  18257. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  18258. // suite (the freed session otherwise stalls on the close handshake) — this test
  18259. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  18260. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  18261. {
  18262. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18263. "/ws-echo");
  18264. client.enable_server_certificate_verification(false);
  18265. client.set_read_timeout(2, 0);
  18266. client.set_write_timeout(2, 0);
  18267. ASSERT_TRUE(client.connect());
  18268. ASSERT_TRUE(client.is_open());
  18269. ASSERT_TRUE(client.send("still open"));
  18270. // Intentionally do NOT call client.close(): leaving scope runs
  18271. // shutdown_and_close() with the WebSocket still open, which must send the
  18272. // close frame while the TLS session is still alive.
  18273. }
  18274. }
  18275. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  18276. // shutdown_and_close() at the start of connect(), reproducing the same
  18277. // use-after-free within the test body rather than at scope exit. The second
  18278. // connect must succeed and echo, proving the close handshake ran over a live
  18279. // session. See the note above about memory-tool requirements.
  18280. TEST_F(WebSocketSSLIntegrationTest,
  18281. ReconnectWhileOpenSendsCloseOverLiveSession) {
  18282. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18283. "/ws-echo");
  18284. client.enable_server_certificate_verification(false);
  18285. client.set_read_timeout(2, 0);
  18286. client.set_write_timeout(2, 0);
  18287. ASSERT_TRUE(client.connect());
  18288. ASSERT_TRUE(client.is_open());
  18289. ASSERT_TRUE(client.send("still open"));
  18290. // Reconnect without closing first: connect() calls shutdown_and_close() on
  18291. // the still-open connection, which must not touch a freed TLS session.
  18292. ASSERT_TRUE(client.connect());
  18293. ASSERT_TRUE(client.is_open());
  18294. ASSERT_TRUE(client.send("after reconnect"));
  18295. std::string msg;
  18296. EXPECT_EQ(ws::Text, client.read(msg));
  18297. EXPECT_EQ("after reconnect", msg);
  18298. client.close();
  18299. }
  18300. #endif
  18301. #ifdef CPPHTTPLIB_SSL_ENABLED
  18302. class WebSocketSSLCATest : public ::testing::Test {
  18303. protected:
  18304. void SetUp() override {
  18305. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  18306. SERVER_PRIVATE_KEY_FILE);
  18307. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18308. std::string msg;
  18309. while (ws.read(msg)) {
  18310. ws.send(msg);
  18311. }
  18312. });
  18313. port_ = server_->bind_to_any_port("127.0.0.1");
  18314. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18315. server_->wait_until_ready();
  18316. }
  18317. void TearDown() override {
  18318. server_->stop();
  18319. if (server_thread_.joinable()) { server_thread_.join(); }
  18320. }
  18321. std::string url() const {
  18322. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  18323. }
  18324. std::unique_ptr<SSLServer> server_;
  18325. std::thread server_thread_;
  18326. int port_ = 0;
  18327. };
  18328. // A custom CA loaded as PEM verifies the server with full certificate
  18329. // verification enabled
  18330. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  18331. ws::WebSocketClient client(url());
  18332. std::string cert;
  18333. read_file(SERVER_CERT2_FILE, cert);
  18334. client.load_ca_cert_store(cert.c_str(), cert.size());
  18335. ASSERT_TRUE(client.connect());
  18336. ASSERT_TRUE(client.send("hello"));
  18337. std::string msg;
  18338. EXPECT_EQ(ws::Text, client.read(msg));
  18339. EXPECT_EQ("hello", msg);
  18340. client.close();
  18341. }
  18342. // A custom CA that does not cover the server must fail verification (the
  18343. // custom CA is exclusive; system certs are not loaded alongside it)
  18344. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  18345. ws::WebSocketClient client(url());
  18346. std::string cert;
  18347. read_file(CLIENT_CA_CERT_FILE, cert);
  18348. client.load_ca_cert_store(cert.c_str(), cert.size());
  18349. auto res = client.connect();
  18350. ASSERT_FALSE(res);
  18351. EXPECT_EQ(Error::SSLServerVerification, res.error());
  18352. EXPECT_EQ(-1, res.status());
  18353. EXPECT_NE(0u, res.ssl_backend_error());
  18354. }
  18355. // The same CA as a file path rather than PEM in memory
  18356. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  18357. ws::WebSocketClient client(url());
  18358. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18359. ASSERT_TRUE(client.connect());
  18360. ASSERT_TRUE(client.send("hello"));
  18361. std::string msg;
  18362. EXPECT_EQ(ws::Text, client.read(msg));
  18363. EXPECT_EQ("hello", msg);
  18364. client.close();
  18365. }
  18366. // ...and a CA file that does not cover the server still fails, so it is the
  18367. // path above that decides the outcome
  18368. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  18369. ws::WebSocketClient client(url());
  18370. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  18371. ASSERT_FALSE(client.connect());
  18372. }
  18373. // Regression test: reconnecting with a native custom CA store used to reuse
  18374. // a store handle the previous TLS context had already freed (use-after-free
  18375. // under the OpenSSL backend). The context now lives as long as the client.
  18376. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  18377. ws::WebSocketClient client(url());
  18378. std::string cert;
  18379. read_file(SERVER_CERT2_FILE, cert);
  18380. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  18381. ASSERT_TRUE(client.connect());
  18382. client.close();
  18383. ASSERT_TRUE(client.connect());
  18384. ASSERT_TRUE(client.send("again"));
  18385. std::string msg;
  18386. EXPECT_EQ(ws::Text, client.read(msg));
  18387. EXPECT_EQ("again", msg);
  18388. client.close();
  18389. }
  18390. // Regression test: a certificate with a trusted chain but no identity match
  18391. // for the server IP must be rejected. The Mbed TLS backend used to skip
  18392. // verification entirely for IP hosts, so this connection succeeded there.
  18393. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  18394. // chain verification while the identity check must still fail.
  18395. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  18396. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18397. ASSERT_TRUE(svr.is_valid());
  18398. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18399. std::string msg;
  18400. while (ws.read(msg)) {
  18401. ws.send(msg);
  18402. }
  18403. });
  18404. auto port = svr.bind_to_any_port("127.0.0.1");
  18405. auto t = std::thread([&]() { svr.listen_after_bind(); });
  18406. auto se = detail::scope_exit([&] {
  18407. svr.stop();
  18408. t.join();
  18409. });
  18410. svr.wait_until_ready();
  18411. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  18412. "/echo");
  18413. std::string cert;
  18414. read_file(SERVER_CERT_FILE, cert);
  18415. client.load_ca_cert_store(cert.c_str(), cert.size());
  18416. ASSERT_FALSE(client.connect());
  18417. }
  18418. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  18419. // SNI, so nothing binds the host name to the TLS session. These bind the
  18420. // server to "localhost" instead, the only shape that exercises the SNI and
  18421. // hostname-verification path with certificate verification left enabled.
  18422. class WebSocketSSLDnsHostTest : public ::testing::Test {
  18423. protected:
  18424. void Start(const char *cert_file) {
  18425. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  18426. SERVER_PRIVATE_KEY_FILE);
  18427. ASSERT_TRUE(server_->is_valid());
  18428. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18429. std::string msg;
  18430. while (ws.read(msg)) {
  18431. ws.send(msg);
  18432. }
  18433. });
  18434. port_ = server_->bind_to_any_port("localhost");
  18435. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18436. server_->wait_until_ready();
  18437. }
  18438. void TearDown() override {
  18439. if (server_) { server_->stop(); }
  18440. if (server_thread_.joinable()) { server_thread_.join(); }
  18441. }
  18442. std::string url() const {
  18443. return "wss://localhost:" + std::to_string(port_) + "/echo";
  18444. }
  18445. std::unique_ptr<SSLServer> server_;
  18446. std::thread server_thread_;
  18447. int port_ = 0;
  18448. };
  18449. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  18450. // out and the connection is usable
  18451. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  18452. Start(SERVER_CERT2_FILE);
  18453. ws::WebSocketClient client(url());
  18454. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18455. ASSERT_TRUE(client.connect());
  18456. ASSERT_TRUE(client.send("hello"));
  18457. std::string msg;
  18458. EXPECT_EQ(ws::Text, client.read(msg));
  18459. EXPECT_EQ("hello", msg);
  18460. client.close();
  18461. }
  18462. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  18463. // while the identity check must still reject "localhost"
  18464. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  18465. Start(SERVER_CERT_FILE);
  18466. ws::WebSocketClient client(url());
  18467. client.set_ca_cert_path(SERVER_CERT_FILE);
  18468. auto res = client.connect();
  18469. ASSERT_FALSE(res);
  18470. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  18471. EXPECT_EQ(-1, res.status());
  18472. }
  18473. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  18474. // disabled: the chain is still checked, only the identity check is skipped
  18475. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  18476. Start(SERVER_CERT_FILE);
  18477. ws::WebSocketClient client(url());
  18478. client.set_ca_cert_path(SERVER_CERT_FILE);
  18479. client.enable_server_hostname_verification(false);
  18480. ASSERT_TRUE(client.connect());
  18481. ASSERT_TRUE(client.send("hello"));
  18482. std::string msg;
  18483. EXPECT_EQ(ws::Text, client.read(msg));
  18484. EXPECT_EQ("hello", msg);
  18485. client.close();
  18486. }
  18487. // A CA that did not sign the server certificate fails the chain, even though
  18488. // the name would match
  18489. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  18490. Start(SERVER_CERT2_FILE);
  18491. ws::WebSocketClient client(url());
  18492. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  18493. ASSERT_FALSE(client.connect());
  18494. }
  18495. // With verification disabled, neither the chain nor the name is checked
  18496. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  18497. Start(SERVER_CERT_FILE);
  18498. ws::WebSocketClient client(url());
  18499. client.enable_server_certificate_verification(false);
  18500. ASSERT_TRUE(client.connect());
  18501. ASSERT_TRUE(client.send("hello"));
  18502. std::string msg;
  18503. EXPECT_EQ(ws::Text, client.read(msg));
  18504. EXPECT_EQ("hello", msg);
  18505. client.close();
  18506. }
  18507. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  18508. protected:
  18509. void SetUp() override {
  18510. server_ = httplib::detail::make_unique<SSLServer>(
  18511. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18512. ASSERT_TRUE(server_->is_valid());
  18513. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18514. std::string msg;
  18515. while (ws.read(msg)) {
  18516. ws.send(msg);
  18517. }
  18518. });
  18519. port_ = server_->bind_to_any_port("localhost");
  18520. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18521. server_->wait_until_ready();
  18522. }
  18523. void TearDown() override {
  18524. server_->stop();
  18525. if (server_thread_.joinable()) { server_thread_.join(); }
  18526. }
  18527. std::string url() const {
  18528. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  18529. }
  18530. void ConnectWithClientCert(const std::string &client_cert_file,
  18531. const std::string &client_private_key_file,
  18532. const char *private_key_password) {
  18533. std::string cert_pem, key_pem;
  18534. read_file(client_cert_file, cert_pem);
  18535. read_file(client_private_key_file, key_pem);
  18536. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  18537. key_pem.c_str(), key_pem.size(),
  18538. private_key_password};
  18539. ws::WebSocketClient client(url(), pem);
  18540. ASSERT_TRUE(client.is_valid());
  18541. client.enable_server_certificate_verification(false);
  18542. ASSERT_TRUE(client.connect());
  18543. ASSERT_TRUE(client.send("hello"));
  18544. std::string msg;
  18545. EXPECT_EQ(ws::Text, client.read(msg));
  18546. EXPECT_EQ("hello", msg);
  18547. client.close();
  18548. }
  18549. std::unique_ptr<SSLServer> server_;
  18550. std::thread server_thread_;
  18551. int port_ = 0;
  18552. };
  18553. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  18554. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  18555. }
  18556. // Control for the tests above: the fixture's server really does require a
  18557. // client certificate, so it is the PEM the constructor installed that decides
  18558. // the outcome.
  18559. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  18560. ws::WebSocketClient client(url());
  18561. ASSERT_TRUE(client.is_valid());
  18562. client.enable_server_certificate_verification(false);
  18563. EXPECT_FALSE(client.connect());
  18564. }
  18565. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  18566. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  18567. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  18568. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  18569. }
  18570. #endif
  18571. #if !defined(_WIN32)
  18572. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  18573. auto secret_dir = std::string("./symlink_test_secret");
  18574. auto served_dir = std::string("./symlink_test_served");
  18575. auto secret_file = secret_dir + "/secret.txt";
  18576. auto symlink_path = served_dir + "/escape";
  18577. // Setup: create directories and files
  18578. mkdir(secret_dir.c_str(), 0755);
  18579. mkdir(served_dir.c_str(), 0755);
  18580. {
  18581. std::ofstream ofs(secret_file);
  18582. ofs << "SECRET_DATA";
  18583. }
  18584. // Create symlink using absolute path so it resolves correctly
  18585. #ifdef PATH_MAX
  18586. char abs_secret[PATH_MAX];
  18587. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  18588. #else
  18589. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  18590. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  18591. ASSERT_NE(nullptr, abs_secret);
  18592. #endif
  18593. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  18594. auto se = detail::scope_exit([&] {
  18595. unlink(symlink_path.c_str());
  18596. unlink(secret_file.c_str());
  18597. rmdir(served_dir.c_str());
  18598. rmdir(secret_dir.c_str());
  18599. });
  18600. Server svr;
  18601. svr.set_mount_point("/", served_dir);
  18602. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18603. auto se2 = detail::scope_exit([&] {
  18604. svr.stop();
  18605. listen_thread.join();
  18606. });
  18607. svr.wait_until_ready();
  18608. Client cli("localhost", PORT);
  18609. // Symlink pointing outside base dir should be blocked
  18610. auto res = cli.Get("/escape/secret.txt");
  18611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18612. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18613. }
  18614. #endif
  18615. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  18616. // A GET request with Content-Length to a static file handler must have its
  18617. // body drained before the keep-alive connection is reused. Otherwise the
  18618. // unread body bytes are interpreted as the next HTTP request.
  18619. //
  18620. // The body is sent AFTER receiving the first response (as in the original
  18621. // PoC) so that the stream_line_reader cannot buffer it together with the
  18622. // headers of the first request.
  18623. Server svr;
  18624. svr.set_mount_point("/", "./www");
  18625. std::atomic<int> smuggled_count(0);
  18626. svr.Get("/smuggled", [&](const Request &, Response &res) {
  18627. smuggled_count++;
  18628. res.set_content("oops", "text/plain");
  18629. });
  18630. auto port = svr.bind_to_any_port("localhost");
  18631. thread t = thread([&] { svr.listen_after_bind(); });
  18632. auto se = detail::scope_exit([&] {
  18633. svr.stop();
  18634. t.join();
  18635. });
  18636. svr.wait_until_ready();
  18637. auto error = Error::Success;
  18638. auto sock = detail::create_client_socket(
  18639. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  18640. /*connection_timeout_sec=*/2, 0,
  18641. /*read_timeout_sec=*/2, 0,
  18642. /*write_timeout_sec=*/2, 0, std::string(), error);
  18643. ASSERT_NE(INVALID_SOCKET, sock);
  18644. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18645. // The "smuggled" request will be sent as the body of the outer GET
  18646. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  18647. "Host: localhost\r\n"
  18648. "Connection: close\r\n"
  18649. "\r\n";
  18650. // Step 1: Send only the outer request headers (no body yet)
  18651. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  18652. "Host: localhost\r\n"
  18653. "Content-Length: " +
  18654. std::to_string(smuggled.size()) +
  18655. "\r\n"
  18656. "\r\n";
  18657. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  18658. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  18659. // Step 2: Read the first response (server serves file without reading body)
  18660. std::string first_response;
  18661. char buf[4096];
  18662. for (;;) {
  18663. auto n = recv(sock, buf, sizeof(buf), 0);
  18664. if (n <= 0) break;
  18665. first_response.append(buf, static_cast<size_t>(n));
  18666. // Stop once we have a complete response (headers + body)
  18667. auto hdr_end = first_response.find("\r\n\r\n");
  18668. if (hdr_end != std::string::npos) {
  18669. // Check for Content-Length to know when the body is complete
  18670. auto cl_pos = first_response.find("Content-Length:");
  18671. if (cl_pos != std::string::npos) {
  18672. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  18673. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  18674. auto cl = std::stoul(
  18675. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  18676. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  18677. } else {
  18678. break; // No Content-Length, assume headers-only response
  18679. }
  18680. }
  18681. }
  18682. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  18683. // Step 3: Now send the body, which looks like a new HTTP request.
  18684. // On a vulnerable server the keep-alive loop reads this as a second request.
  18685. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  18686. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  18687. // Step 4: Try to read a second response (should NOT exist after fix)
  18688. std::string second_response;
  18689. for (;;) {
  18690. auto n = recv(sock, buf, sizeof(buf), 0);
  18691. if (n <= 0) break;
  18692. second_response.append(buf, static_cast<size_t>(n));
  18693. }
  18694. // The smuggled request must NOT have been processed
  18695. EXPECT_EQ(0, smuggled_count.load());
  18696. }
  18697. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18698. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  18699. // must be rejected with 400 Bad Request.
  18700. Server svr;
  18701. svr.Post("/test", [&](const Request &, Response &res) {
  18702. res.set_content("ok", "text/plain");
  18703. });
  18704. thread t = thread([&] { svr.listen(HOST, PORT); });
  18705. auto se = detail::scope_exit([&] {
  18706. svr.stop();
  18707. t.join();
  18708. ASSERT_FALSE(svr.is_running());
  18709. });
  18710. svr.wait_until_ready();
  18711. // Exact "chunked"
  18712. {
  18713. auto req = "POST /test HTTP/1.1\r\n"
  18714. "Host: localhost\r\n"
  18715. "Content-Length: 5\r\n"
  18716. "Transfer-Encoding: chunked\r\n"
  18717. "Connection: close\r\n"
  18718. "\r\n"
  18719. "hello";
  18720. std::string response;
  18721. ASSERT_TRUE(send_request(1, req, &response));
  18722. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18723. response.substr(0, response.find("\r\n")));
  18724. }
  18725. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  18726. {
  18727. auto req = "POST /test HTTP/1.1\r\n"
  18728. "Host: localhost\r\n"
  18729. "Content-Length: 5\r\n"
  18730. "Transfer-Encoding: gzip, chunked\r\n"
  18731. "Connection: close\r\n"
  18732. "\r\n"
  18733. "hello";
  18734. std::string response;
  18735. ASSERT_TRUE(send_request(1, req, &response));
  18736. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18737. response.substr(0, response.find("\r\n")));
  18738. }
  18739. }
  18740. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  18741. Server svr;
  18742. svr.Post("/test", [&](const Request &, Response &res) {
  18743. res.set_content("ok", "text/plain");
  18744. });
  18745. thread t = thread([&] { svr.listen(HOST, PORT); });
  18746. auto se = detail::scope_exit([&] {
  18747. svr.stop();
  18748. t.join();
  18749. ASSERT_FALSE(svr.is_running());
  18750. });
  18751. svr.wait_until_ready();
  18752. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  18753. // length cannot be determined, so the server must answer 400 and close
  18754. // rather than treat the request as bodyless and leave the body in the
  18755. // socket for the next request to pick up.
  18756. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  18757. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  18758. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  18759. std::string response;
  18760. ASSERT_TRUE(send_request(1, req, &response));
  18761. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18762. response.substr(0, response.find("\r\n")))
  18763. << transfer_encoding;
  18764. }
  18765. // RFC 9110 5.3: the codings may also be split across several
  18766. // Transfer-Encoding lines, which combine in the order they were received.
  18767. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  18768. // just like the single-line "chunked, gzip" above.
  18769. {
  18770. auto req = "POST /test HTTP/1.1\r\n"
  18771. "Host: localhost\r\n"
  18772. "Transfer-Encoding: chunked\r\n"
  18773. "Transfer-Encoding: gzip\r\n"
  18774. "\r\n"
  18775. "0\r\n\r\n";
  18776. std::string response;
  18777. ASSERT_TRUE(send_request(1, req, &response));
  18778. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18779. response.substr(0, response.find("\r\n")));
  18780. }
  18781. // A sequence ending in chunked stays valid.
  18782. auto req = "POST /test HTTP/1.1\r\n"
  18783. "Host: localhost\r\n"
  18784. "Transfer-Encoding: gzip, chunked\r\n"
  18785. "Connection: close\r\n"
  18786. "\r\n"
  18787. "0\r\n\r\n";
  18788. std::string response;
  18789. ASSERT_TRUE(send_request(1, req, &response));
  18790. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18791. // ...including when it is spread over several lines.
  18792. auto split_req = "POST /test HTTP/1.1\r\n"
  18793. "Host: localhost\r\n"
  18794. "Transfer-Encoding: gzip\r\n"
  18795. "Transfer-Encoding: chunked\r\n"
  18796. "Connection: close\r\n"
  18797. "\r\n"
  18798. "0\r\n\r\n";
  18799. std::string split_response;
  18800. ASSERT_TRUE(send_request(1, split_req, &split_response));
  18801. EXPECT_EQ("HTTP/1.1 200 OK",
  18802. split_response.substr(0, split_response.find("\r\n")));
  18803. }
  18804. // Regression for issue #2450: a DELETE without Content-Length on a
  18805. // keep-alive connection must not let the post-response drain consume the
  18806. // next request's bytes.
  18807. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  18808. Server svr;
  18809. std::atomic<int> delete_count(0);
  18810. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  18811. delete_count++;
  18812. res.status = StatusCode::NoContent_204;
  18813. });
  18814. auto port = svr.bind_to_any_port(HOST);
  18815. thread t = thread([&] { svr.listen_after_bind(); });
  18816. auto se = detail::scope_exit([&] {
  18817. svr.stop();
  18818. t.join();
  18819. });
  18820. svr.wait_until_ready();
  18821. auto error = Error::Success;
  18822. auto sock = detail::create_client_socket(
  18823. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18824. /*connection_timeout_sec=*/2, 0,
  18825. /*read_timeout_sec=*/2, 0,
  18826. /*write_timeout_sec=*/2, 0, std::string(), error);
  18827. ASSERT_NE(INVALID_SOCKET, sock);
  18828. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18829. auto send_request_and_read_response = [&](const std::string &req,
  18830. std::string &out) -> bool {
  18831. auto sent = send(sock, req.data(), req.size(), 0);
  18832. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  18833. char buf[4096];
  18834. for (;;) {
  18835. auto n = recv(sock, buf, sizeof(buf), 0);
  18836. if (n <= 0) { return !out.empty(); }
  18837. out.append(buf, static_cast<size_t>(n));
  18838. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  18839. }
  18840. };
  18841. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  18842. "Host: localhost\r\n"
  18843. "\r\n";
  18844. std::string resp1;
  18845. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  18846. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  18847. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  18848. "Host: localhost\r\n"
  18849. "Connection: close\r\n"
  18850. "\r\n";
  18851. std::string resp2;
  18852. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  18853. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  18854. EXPECT_EQ(2, delete_count.load());
  18855. }
  18856. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  18857. Server svr;
  18858. svr.Post("/ingest", [&](const Request &, Response &res,
  18859. const ContentReader &content_reader) {
  18860. auto consumed = content_reader([](const char *, size_t) { return false; });
  18861. EXPECT_FALSE(consumed);
  18862. res.status = StatusCode::Conflict_409;
  18863. res.set_header("Connection", "close");
  18864. });
  18865. auto port = svr.bind_to_any_port(HOST);
  18866. thread t = thread([&] { svr.listen_after_bind(); });
  18867. auto se = detail::scope_exit([&] {
  18868. svr.stop();
  18869. t.join();
  18870. });
  18871. svr.wait_until_ready();
  18872. auto error = Error::Success;
  18873. auto sock = detail::create_client_socket(
  18874. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18875. /*connection_timeout_sec=*/2, 0,
  18876. /*read_timeout_sec=*/1, 0,
  18877. /*write_timeout_sec=*/2, 0, std::string(), error);
  18878. ASSERT_NE(INVALID_SOCKET, sock);
  18879. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18880. std::string request = "POST /ingest HTTP/1.1\r\n"
  18881. "Host: localhost\r\n"
  18882. "Transfer-Encoding: chunked\r\n"
  18883. "\r\n"
  18884. "4\r\n"
  18885. "data\r\n";
  18886. auto sent = send(sock, request.data(), request.size(), 0);
  18887. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  18888. std::string response;
  18889. ssize_t received = 0;
  18890. do {
  18891. char buf[4096];
  18892. received = recv(sock, buf, sizeof(buf), 0);
  18893. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  18894. } while (received > 0);
  18895. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  18896. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  18897. EXPECT_EQ(0, received);
  18898. }
  18899. namespace no_proxy_test {
  18900. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  18901. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  18902. // calling listen().
  18903. class ScopedServer {
  18904. public:
  18905. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  18906. ~ScopedServer() {
  18907. svr_.stop();
  18908. if (th_.joinable()) { th_.join(); }
  18909. }
  18910. Server &svr() { return svr_; }
  18911. int port() const { return port_; }
  18912. void listen() {
  18913. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18914. svr_.wait_until_ready();
  18915. }
  18916. private:
  18917. Server svr_;
  18918. std::thread th_;
  18919. int port_ = 0;
  18920. };
  18921. class ProxyAndTargetServers {
  18922. public:
  18923. ProxyAndTargetServers() {
  18924. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  18925. proxy_hits_++;
  18926. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18927. res.set_content("via-proxy", "text/plain");
  18928. });
  18929. target_.Get(".*", [this](const Request &req, Response &res) {
  18930. target_hits_++;
  18931. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18932. res.set_content("direct", "text/plain");
  18933. });
  18934. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  18935. target_port_ = target_.bind_to_any_port("127.0.0.1");
  18936. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  18937. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  18938. proxy_mock_.wait_until_ready();
  18939. target_.wait_until_ready();
  18940. }
  18941. ~ProxyAndTargetServers() {
  18942. proxy_mock_.stop();
  18943. target_.stop();
  18944. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  18945. if (target_thread_.joinable()) { target_thread_.join(); }
  18946. }
  18947. Server &proxy_mock() { return proxy_mock_; }
  18948. Server &target() { return target_; }
  18949. int proxy_port() const { return proxy_port_; }
  18950. int target_port() const { return target_port_; }
  18951. int proxy_hits() const { return proxy_hits_.load(); }
  18952. int target_hits() const { return target_hits_.load(); }
  18953. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  18954. void reset_counters() {
  18955. proxy_hits_ = 0;
  18956. target_hits_ = 0;
  18957. last_had_proxy_authz_ = false;
  18958. }
  18959. private:
  18960. Server proxy_mock_;
  18961. Server target_;
  18962. std::thread proxy_thread_;
  18963. std::thread target_thread_;
  18964. int proxy_port_ = 0;
  18965. int target_port_ = 0;
  18966. std::atomic<int> proxy_hits_{0};
  18967. std::atomic<int> target_hits_{0};
  18968. std::atomic<bool> last_had_proxy_authz_{false};
  18969. };
  18970. inline std::unique_ptr<Client> make_client(const std::string &host,
  18971. ProxyAndTargetServers &s) {
  18972. auto cli = detail::make_unique<Client>(host, s.target_port());
  18973. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  18974. cli->set_proxy("127.0.0.1", s.proxy_port());
  18975. return cli;
  18976. }
  18977. } // namespace no_proxy_test
  18978. using no_proxy_test::make_client;
  18979. using no_proxy_test::ProxyAndTargetServers;
  18980. TEST(NoProxyTest, ExactHostnameBypasses) {
  18981. ProxyAndTargetServers s;
  18982. auto cli = make_client("example.com", s);
  18983. cli->set_no_proxy({"example.com"});
  18984. auto res = cli->Get("/");
  18985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18986. EXPECT_EQ(0, s.proxy_hits());
  18987. EXPECT_EQ(1, s.target_hits());
  18988. }
  18989. TEST(NoProxyTest, SubdomainBypasses) {
  18990. ProxyAndTargetServers s;
  18991. auto cli = make_client("foo.example.com", s);
  18992. cli->set_no_proxy({"example.com"});
  18993. auto res = cli->Get("/");
  18994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18995. EXPECT_EQ(0, s.proxy_hits());
  18996. EXPECT_EQ(1, s.target_hits());
  18997. }
  18998. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  18999. // Regression guard: "evilexample.com" must not be considered a subdomain
  19000. // of "example.com". Without the dot-boundary rule, a naive endsWith
  19001. // check would let traffic bypass the proxy and leak credentials direct
  19002. // to the attacker host.
  19003. ProxyAndTargetServers s;
  19004. auto cli = make_client("evilexample.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_GE(s.proxy_hits(), 1);
  19009. EXPECT_EQ(0, s.target_hits());
  19010. }
  19011. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  19012. ProxyAndTargetServers s;
  19013. auto cli = make_client("example.com.evil.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_GE(s.proxy_hits(), 1);
  19018. EXPECT_EQ(0, s.target_hits());
  19019. }
  19020. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  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, CaseInsensitiveHostname) {
  19030. ProxyAndTargetServers s;
  19031. auto cli = make_client("Example.COM", s);
  19032. cli->set_no_proxy({"EXAMPLE.com"});
  19033. auto res = cli->Get("/");
  19034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19035. EXPECT_EQ(0, s.proxy_hits());
  19036. EXPECT_EQ(1, s.target_hits());
  19037. }
  19038. TEST(NoProxyTest, TrailingDotIsNormalized) {
  19039. ProxyAndTargetServers s;
  19040. auto cli = make_client("example.com.", s);
  19041. cli->set_no_proxy({"example.com"});
  19042. auto res = cli->Get("/");
  19043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19044. EXPECT_EQ(0, s.proxy_hits());
  19045. EXPECT_EQ(1, s.target_hits());
  19046. }
  19047. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  19048. // Trailing dots must be normalized on BOTH sides — host and entry.
  19049. // An implementation that only strips the host-side trailing dot would
  19050. // fail to match host "example.com" against entry "example.com." because
  19051. // a literal substring search would compare 11 chars against 12.
  19052. ProxyAndTargetServers s;
  19053. auto cli = make_client("example.com", s);
  19054. cli->set_no_proxy({"example.com."});
  19055. auto res = cli->Get("/");
  19056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19057. EXPECT_EQ(0, s.proxy_hits());
  19058. EXPECT_EQ(1, s.target_hits());
  19059. }
  19060. TEST(NoProxyTest, WildcardBypassesEverything) {
  19061. ProxyAndTargetServers s;
  19062. auto cli = make_client("anything.invalid.test", s);
  19063. cli->set_no_proxy({"*"});
  19064. auto res = cli->Get("/");
  19065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19066. EXPECT_EQ(0, s.proxy_hits());
  19067. EXPECT_EQ(1, s.target_hits());
  19068. }
  19069. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  19070. ProxyAndTargetServers s;
  19071. Client cli("127.0.0.1", s.target_port());
  19072. cli.set_proxy("127.0.0.1", s.proxy_port());
  19073. cli.set_no_proxy({"127.0.0.1"});
  19074. auto res = cli.Get("/");
  19075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19076. EXPECT_EQ(0, s.proxy_hits());
  19077. EXPECT_EQ(1, s.target_hits());
  19078. }
  19079. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  19080. ProxyAndTargetServers s;
  19081. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  19082. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  19083. cli.set_proxy("127.0.0.1", s.proxy_port());
  19084. cli.set_no_proxy({"::1"});
  19085. auto res = cli.Get("/");
  19086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19087. EXPECT_EQ(0, s.proxy_hits());
  19088. EXPECT_EQ(1, s.target_hits());
  19089. }
  19090. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  19091. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  19092. // must still be recognized as IPv6 for CIDR matching. Implementations
  19093. // that detect IPv6 only when the host begins with '[' would parse the
  19094. // host as a hostname and miss the match.
  19095. ProxyAndTargetServers s;
  19096. Client cli("fe80::1", s.target_port());
  19097. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19098. cli.set_proxy("127.0.0.1", s.proxy_port());
  19099. cli.set_no_proxy({"fe80::/10"});
  19100. auto res = cli.Get("/");
  19101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19102. EXPECT_EQ(0, s.proxy_hits());
  19103. EXPECT_EQ(1, s.target_hits());
  19104. }
  19105. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  19106. ProxyAndTargetServers s;
  19107. Client cli("::1", s.target_port());
  19108. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  19109. cli.set_proxy("127.0.0.1", s.proxy_port());
  19110. cli.set_no_proxy({"[::1]"});
  19111. auto res = cli.Get("/");
  19112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19113. EXPECT_EQ(0, s.proxy_hits());
  19114. EXPECT_EQ(1, s.target_hits());
  19115. }
  19116. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  19117. ProxyAndTargetServers s;
  19118. Client cli("fe80::1", s.target_port());
  19119. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19120. cli.set_proxy("127.0.0.1", s.proxy_port());
  19121. cli.set_no_proxy({"[fe80::]/10"});
  19122. auto res = cli.Get("/");
  19123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19124. EXPECT_EQ(0, s.proxy_hits());
  19125. EXPECT_EQ(1, s.target_hits());
  19126. }
  19127. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  19128. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  19129. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  19130. // tricks via address-family conversion.
  19131. ProxyAndTargetServers s;
  19132. Client cli("::ffff:127.0.0.1", s.target_port());
  19133. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  19134. cli.set_proxy("127.0.0.1", s.proxy_port());
  19135. cli.set_no_proxy({"127.0.0.1"});
  19136. auto res = cli.Get("/");
  19137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19138. EXPECT_GE(s.proxy_hits(), 1);
  19139. EXPECT_EQ(0, s.target_hits());
  19140. }
  19141. TEST(NoProxyTest, IPv4CidrMatch) {
  19142. ProxyAndTargetServers s;
  19143. Client cli("127.0.0.1", s.target_port());
  19144. cli.set_proxy("127.0.0.1", s.proxy_port());
  19145. cli.set_no_proxy({"127.0.0.0/8"});
  19146. auto res = cli.Get("/");
  19147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19148. EXPECT_EQ(0, s.proxy_hits());
  19149. EXPECT_EQ(1, s.target_hits());
  19150. }
  19151. TEST(NoProxyTest, IPv4CidrNonMatch) {
  19152. ProxyAndTargetServers s;
  19153. Client cli("127.0.0.1", s.target_port());
  19154. cli.set_proxy("127.0.0.1", s.proxy_port());
  19155. cli.set_no_proxy({"10.0.0.0/8"});
  19156. auto res = cli.Get("/");
  19157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19158. EXPECT_GE(s.proxy_hits(), 1);
  19159. EXPECT_EQ(0, s.target_hits());
  19160. }
  19161. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  19162. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  19163. // IPv4 target matches.
  19164. ProxyAndTargetServers s;
  19165. Client cli("127.0.0.1", s.target_port());
  19166. cli.set_proxy("127.0.0.1", s.proxy_port());
  19167. cli.set_no_proxy({"0.0.0.0/0"});
  19168. auto res = cli.Get("/");
  19169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19170. EXPECT_EQ(0, s.proxy_hits());
  19171. EXPECT_EQ(1, s.target_hits());
  19172. }
  19173. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  19174. ProxyAndTargetServers s;
  19175. Client cli("127.0.0.1", s.target_port());
  19176. cli.set_proxy("127.0.0.1", s.proxy_port());
  19177. cli.set_no_proxy({"127.0.0.1"});
  19178. auto res = cli.Get("/");
  19179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19180. EXPECT_EQ(0, s.proxy_hits());
  19181. EXPECT_EQ(1, s.target_hits());
  19182. }
  19183. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  19184. ProxyAndTargetServers s;
  19185. Client cli("127.0.0.1", s.target_port());
  19186. cli.set_proxy("127.0.0.1", s.proxy_port());
  19187. cli.set_no_proxy({"127.0.0.0/33"});
  19188. auto res = cli.Get("/");
  19189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19190. EXPECT_GE(s.proxy_hits(), 1);
  19191. EXPECT_EQ(0, s.target_hits());
  19192. }
  19193. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  19194. // Empty prefix after the slash must be rejected, not silently treated as /32.
  19195. ProxyAndTargetServers s;
  19196. Client cli("127.0.0.1", s.target_port());
  19197. cli.set_proxy("127.0.0.1", s.proxy_port());
  19198. cli.set_no_proxy({"127.0.0.1/"});
  19199. auto res = cli.Get("/");
  19200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19201. EXPECT_GE(s.proxy_hits(), 1);
  19202. EXPECT_EQ(0, s.target_hits());
  19203. }
  19204. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  19205. ProxyAndTargetServers s;
  19206. auto cli = make_client("internal.corp", s);
  19207. cli->set_proxy_basic_auth("u", "p");
  19208. cli->set_no_proxy({"internal.corp"});
  19209. auto res = cli->Get("/");
  19210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19211. EXPECT_EQ(1, s.target_hits());
  19212. EXPECT_EQ(0, s.proxy_hits());
  19213. EXPECT_FALSE(s.last_had_proxy_authz())
  19214. << "Proxy-Authorization must not be sent direct to the target";
  19215. }
  19216. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  19217. ProxyAndTargetServers s;
  19218. auto cli = make_client("public.example", s);
  19219. cli->set_proxy_basic_auth("u", "p");
  19220. cli->set_no_proxy({"internal.corp"}); // does not match
  19221. auto res = cli->Get("/");
  19222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19223. EXPECT_GE(s.proxy_hits(), 1);
  19224. EXPECT_TRUE(s.last_had_proxy_authz());
  19225. }
  19226. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  19227. ProxyAndTargetServers s;
  19228. auto cli = make_client("anything.test", s);
  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, PortSpecificEntryRejected) {
  19235. ProxyAndTargetServers s;
  19236. auto cli = make_client("example.com", s);
  19237. cli->set_no_proxy({"example.com:8080"});
  19238. auto res = cli->Get("/");
  19239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19240. EXPECT_GE(s.proxy_hits(), 1);
  19241. EXPECT_EQ(0, s.target_hits());
  19242. }
  19243. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  19244. ProxyAndTargetServers s;
  19245. auto cli = make_client("anything.test", s);
  19246. cli->set_no_proxy({"", " ", "\t"});
  19247. auto res = cli->Get("/");
  19248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19249. EXPECT_GE(s.proxy_hits(), 1);
  19250. EXPECT_EQ(0, s.target_hits());
  19251. }
  19252. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  19253. // An entry with leading/trailing whitespace must still match — env-style
  19254. // values are commonly pasted with stray spaces and an implementation
  19255. // that feeds the raw token directly to inet_pton would fail to match
  19256. // valid CIDRs because of the spaces.
  19257. ProxyAndTargetServers s;
  19258. Client cli("127.0.0.1", s.target_port());
  19259. cli.set_proxy("127.0.0.1", s.proxy_port());
  19260. cli.set_no_proxy({" 127.0.0.0/8 "});
  19261. auto res = cli.Get("/");
  19262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19263. EXPECT_EQ(0, s.proxy_hits());
  19264. EXPECT_EQ(1, s.target_hits());
  19265. }
  19266. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  19267. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  19268. // go direct and must NOT carry Proxy-Authorization.
  19269. std::atomic<int> proxy_hits{0};
  19270. std::atomic<int> target_hits{0};
  19271. std::atomic<bool> target_saw_authz{false};
  19272. no_proxy_test::ScopedServer proxy_mock, target;
  19273. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19274. proxy_hits++;
  19275. res.status = 302;
  19276. res.set_header("Location", "http://127.0.0.1:" +
  19277. std::to_string(target.port()) + "/landed");
  19278. });
  19279. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19280. target_hits++;
  19281. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  19282. res.set_content("direct", "text/plain");
  19283. });
  19284. proxy_mock.listen();
  19285. target.listen();
  19286. Client cli("public.example", target.port());
  19287. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19288. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19289. cli.set_proxy_basic_auth("u", "p");
  19290. cli.set_no_proxy({"127.0.0.1"});
  19291. cli.set_follow_location(true);
  19292. auto res = cli.Get("/redir");
  19293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19294. EXPECT_GE(proxy_hits.load(), 1);
  19295. EXPECT_GE(target_hits.load(), 1);
  19296. EXPECT_FALSE(target_saw_authz.load());
  19297. }
  19298. #ifdef CPPHTTPLIB_SSL_ENABLED
  19299. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  19300. // Direct origin replying 407 must not trigger the digest retry; otherwise
  19301. // proxy creds would be sent to the (possibly hostile) origin.
  19302. std::atomic<int> target_hits{0};
  19303. std::atomic<bool> target_saw_proxy_authz{false};
  19304. no_proxy_test::ScopedServer target;
  19305. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19306. target_hits++;
  19307. if (req.has_header("Proxy-Authorization")) {
  19308. target_saw_proxy_authz = true;
  19309. }
  19310. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19311. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  19312. "nonce=\"abc\", algorithm=MD5");
  19313. });
  19314. target.listen();
  19315. // The proxy address is set to the target's port: the bypass MUST kick in;
  19316. // if it doesn't, the test still routes "via proxy" to the same server and
  19317. // the Proxy-Authorization assertion below catches the leak.
  19318. Client cli("evil.example", target.port());
  19319. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  19320. cli.set_proxy("127.0.0.1", target.port());
  19321. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19322. cli.set_no_proxy({"evil.example"});
  19323. auto res = cli.Get("/x");
  19324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19325. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19326. EXPECT_EQ(1, target_hits.load());
  19327. EXPECT_FALSE(target_saw_proxy_authz.load());
  19328. }
  19329. #endif
  19330. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  19331. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  19332. std::atomic<int> proxy_hits{0};
  19333. std::atomic<int> bypass_hits{0};
  19334. std::atomic<bool> proxy_saw_c_url{false};
  19335. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  19336. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  19337. proxy_hits++;
  19338. if (req.path.find("/start") != std::string::npos) {
  19339. res.status = 302;
  19340. res.set_header("Location", "http://127.0.0.1:" +
  19341. std::to_string(bypass_server.port()) +
  19342. "/middle");
  19343. return;
  19344. }
  19345. if (req.path.find("/end") != std::string::npos) {
  19346. proxy_saw_c_url = true;
  19347. res.set_content("c-via-proxy", "text/plain");
  19348. return;
  19349. }
  19350. res.set_content("unexpected", "text/plain");
  19351. });
  19352. // public.example's "advertised" port is arbitrary (the request never lands
  19353. // there — it goes through the proxy), but use a dynamic value to stay
  19354. // friendly with sharded parallel runs.
  19355. int public_port = bypass_server.port();
  19356. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  19357. bypass_hits++;
  19358. res.status = 302;
  19359. res.set_header("Location", "http://public.example:" +
  19360. std::to_string(public_port) + "/end");
  19361. });
  19362. proxy_mock.listen();
  19363. bypass_server.listen();
  19364. Client cli("public.example", public_port);
  19365. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19366. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19367. cli.set_no_proxy({"127.0.0.1"});
  19368. cli.set_follow_location(true);
  19369. auto res = cli.Get("/start");
  19370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19371. EXPECT_EQ(StatusCode::OK_200, res->status);
  19372. EXPECT_EQ("c-via-proxy", res->body);
  19373. EXPECT_GE(proxy_hits.load(), 2);
  19374. EXPECT_GE(bypass_hits.load(), 1);
  19375. EXPECT_TRUE(proxy_saw_c_url.load());
  19376. }
  19377. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  19378. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  19379. // request reconnects to the correct endpoint.
  19380. std::atomic<int> proxy_hits{0};
  19381. std::atomic<int> target_hits{0};
  19382. no_proxy_test::ScopedServer proxy_mock, target;
  19383. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19384. proxy_hits++;
  19385. res.set_content("via-proxy", "text/plain");
  19386. });
  19387. target.svr().Get(".*", [&](const Request &, Response &res) {
  19388. target_hits++;
  19389. res.set_content("direct", "text/plain");
  19390. });
  19391. proxy_mock.listen();
  19392. target.listen();
  19393. Client cli("public.example", target.port());
  19394. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19395. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19396. cli.set_keep_alive(true);
  19397. auto res1 = cli.Get("/a");
  19398. ASSERT_TRUE(res1);
  19399. EXPECT_EQ("via-proxy", res1->body);
  19400. EXPECT_EQ(1, proxy_hits.load());
  19401. EXPECT_EQ(0, target_hits.load());
  19402. cli.set_no_proxy({"public.example"});
  19403. auto res2 = cli.Get("/b");
  19404. ASSERT_TRUE(res2);
  19405. EXPECT_EQ("direct", res2->body);
  19406. EXPECT_EQ(1, proxy_hits.load());
  19407. EXPECT_EQ(1, target_hits.load());
  19408. }
  19409. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  19410. namespace proxy_tunnel_test {
  19411. // SSLServer counterpart to no_proxy_test::ScopedServer.
  19412. class ScopedSSLServer {
  19413. public:
  19414. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  19415. port_ = svr_.bind_to_any_port("127.0.0.1");
  19416. }
  19417. ~ScopedSSLServer() {
  19418. svr_.stop();
  19419. if (th_.joinable()) { th_.join(); }
  19420. }
  19421. SSLServer &svr() { return svr_; }
  19422. int port() const { return port_; }
  19423. void listen() {
  19424. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19425. svr_.wait_until_ready();
  19426. }
  19427. private:
  19428. SSLServer svr_;
  19429. std::thread th_;
  19430. int port_ = 0;
  19431. };
  19432. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  19433. class ScopedConnectProxy {
  19434. public:
  19435. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  19436. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  19437. if (listen_fd_ < 0) { return; }
  19438. int yes = 1;
  19439. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  19440. sockaddr_in a{};
  19441. a.sin_family = AF_INET;
  19442. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  19443. a.sin_port = 0;
  19444. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  19445. return;
  19446. }
  19447. socklen_t alen = sizeof(a);
  19448. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  19449. 0) {
  19450. return;
  19451. }
  19452. port_ = ntohs(a.sin_port);
  19453. if (::listen(listen_fd_, 1) != 0) { return; }
  19454. th_ = std::thread([this] { run(); });
  19455. }
  19456. ~ScopedConnectProxy() {
  19457. stop_ = true;
  19458. if (listen_fd_ >= 0) {
  19459. ::shutdown(listen_fd_, SHUT_RDWR);
  19460. ::close(listen_fd_);
  19461. }
  19462. if (th_.joinable()) { th_.join(); }
  19463. }
  19464. int port() const { return port_; }
  19465. int connect_hits() const { return connect_hits_.load(); }
  19466. private:
  19467. void run() {
  19468. while (!stop_.load()) {
  19469. fd_set rfds;
  19470. FD_ZERO(&rfds);
  19471. FD_SET(listen_fd_, &rfds);
  19472. timeval tv{0, 100 * 1000};
  19473. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  19474. if (sel <= 0) { continue; }
  19475. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  19476. if (client_fd < 0) { continue; }
  19477. std::string req;
  19478. char buf[2048];
  19479. while (req.find("\r\n\r\n") == std::string::npos) {
  19480. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  19481. if (n <= 0) { break; }
  19482. req.append(buf, static_cast<size_t>(n));
  19483. }
  19484. if (req.compare(0, 7, "CONNECT") != 0) {
  19485. ::close(client_fd);
  19486. continue;
  19487. }
  19488. connect_hits_++;
  19489. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  19490. ::send(client_fd, ok, std::strlen(ok), 0);
  19491. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  19492. sockaddr_in o{};
  19493. o.sin_family = AF_INET;
  19494. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  19495. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  19496. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  19497. 0) {
  19498. ::close(client_fd);
  19499. ::close(origin_fd);
  19500. continue;
  19501. }
  19502. auto forward = [](int from, int to) {
  19503. char b[8192];
  19504. for (;;) {
  19505. ssize_t n = ::recv(from, b, sizeof(b), 0);
  19506. if (n <= 0) { break; }
  19507. ssize_t off = 0;
  19508. while (off < n) {
  19509. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  19510. if (s <= 0) {
  19511. off = n;
  19512. break;
  19513. }
  19514. off += s;
  19515. }
  19516. }
  19517. ::shutdown(to, SHUT_WR);
  19518. };
  19519. std::thread t1([&] { forward(client_fd, origin_fd); });
  19520. std::thread t2([&] { forward(origin_fd, client_fd); });
  19521. t1.join();
  19522. t2.join();
  19523. ::close(client_fd);
  19524. ::close(origin_fd);
  19525. }
  19526. }
  19527. int forward_port_ = -1;
  19528. int listen_fd_ = -1;
  19529. int port_ = 0;
  19530. std::thread th_;
  19531. std::atomic<bool> stop_{false};
  19532. std::atomic<int> connect_hits_{0};
  19533. };
  19534. } // namespace proxy_tunnel_test
  19535. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  19536. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  19537. // retry; otherwise proxy creds would be sent to the origin.
  19538. std::atomic<int> origin_hits{0};
  19539. std::atomic<bool> origin_saw_proxy_authz{false};
  19540. proxy_tunnel_test::ScopedSSLServer origin;
  19541. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  19542. origin_hits++;
  19543. if (req.has_header("Proxy-Authorization")) {
  19544. origin_saw_proxy_authz = true;
  19545. }
  19546. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19547. res.set_header("Proxy-Authenticate",
  19548. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  19549. "algorithm=MD5");
  19550. });
  19551. origin.listen();
  19552. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  19553. ASSERT_NE(0, proxy.port());
  19554. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  19555. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  19556. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  19557. // and answer with its own status, making this test flaky.
  19558. SSLClient cli("127.0.0.1", origin.port());
  19559. cli.enable_server_certificate_verification(false);
  19560. cli.set_proxy("127.0.0.1", proxy.port());
  19561. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19562. auto res = cli.Get("/x");
  19563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19564. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19565. EXPECT_EQ(1, origin_hits.load());
  19566. EXPECT_FALSE(origin_saw_proxy_authz.load());
  19567. EXPECT_EQ(1, proxy.connect_hits());
  19568. }
  19569. #endif