test.cc 696 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852
  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. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  258. ASSERT_EQ(0, listen(s, 1));
  259. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  260. ASSERT_EQ(0, close(s));
  261. }};
  262. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  263. std::thread cli{[&] {
  264. const int s = socket(AF_INET, SOCK_STREAM, 0);
  265. ASSERT_LE(0, s);
  266. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  267. ASSERT_EQ(0, close(s));
  268. }};
  269. cli.join();
  270. svr.join();
  271. ASSERT_NE(disconnected_svr_sock, -1);
  272. const auto asSocketStream = [&](socket_t fd,
  273. std::function<bool(Stream &)> func) {
  274. return detail::process_client_socket(
  275. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  276. };
  277. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  278. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  279. // wait_writable() returns true because select_write() only checks if the
  280. // send buffer has space. Peer disconnection is detected later by send().
  281. EXPECT_TRUE(ss.wait_writable());
  282. return true;
  283. });
  284. ASSERT_EQ(0, close(disconnected_svr_sock));
  285. }
  286. #endif // #ifndef _WIN32
  287. TEST(SetSocketOptTest, TcpNoDelay) {
  288. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  289. ASSERT_NE(sock, INVALID_SOCKET);
  290. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  291. int val = 0;
  292. socklen_t len = sizeof(val);
  293. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  294. reinterpret_cast<char *>(&val), &len));
  295. EXPECT_NE(val, 0);
  296. detail::close_socket(sock);
  297. }
  298. TEST(ClientTest, MoveConstructible) {
  299. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  300. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  301. }
  302. TEST(ClientTest, MoveAssignable) {
  303. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  304. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  305. }
  306. #ifdef _WIN32
  307. TEST(StartupTest, WSAStartup) {
  308. WSADATA wsaData;
  309. int ret = WSAStartup(0x0002, &wsaData);
  310. ASSERT_EQ(0, ret);
  311. }
  312. #endif
  313. TEST(DecodePathTest, PercentCharacter) {
  314. EXPECT_EQ(
  315. decode_path_component(
  316. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  317. U8("descrip=Gastos áéíóúñÑ 6"));
  318. }
  319. TEST(DecodePathTest, PercentCharacterNUL) {
  320. string expected;
  321. expected.push_back('x');
  322. expected.push_back('\0');
  323. expected.push_back('x');
  324. EXPECT_EQ(decode_path_component("x%00x"), expected);
  325. }
  326. TEST(DecodePathTest, UnicodeEncoding) {
  327. // %u0041 = 'A' (1-byte UTF-8)
  328. EXPECT_EQ("A", decode_path_component("%u0041"));
  329. // %u00E9 = 'é' (2-byte UTF-8)
  330. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  331. // %u3042 = 'あ' (3-byte UTF-8)
  332. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  333. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  334. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  335. // %uD800 = surrogate (invalid, silently dropped)
  336. EXPECT_EQ("", decode_path_component("%uD800"));
  337. }
  338. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  339. // A sign or whitespace inside the two-character escape window must not be
  340. // accepted as a valid percent-encoding; the sequence is passed through
  341. // literally, matching decode_uri_component / decode_path_component.
  342. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  343. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  344. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  345. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  346. // Well-formed escapes still decode.
  347. EXPECT_EQ("-", decode_query_component("%2D", false));
  348. EXPECT_EQ("A", decode_query_component("%41", false));
  349. }
  350. TEST(SanitizeFilenameTest, VariousPatterns) {
  351. // Path traversal
  352. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  353. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  354. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  355. // Normal and edge cases
  356. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  357. EXPECT_EQ("filename.txt",
  358. httplib::sanitize_filename("/path/to/filename.txt"));
  359. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  360. EXPECT_EQ("", httplib::sanitize_filename(".."));
  361. EXPECT_EQ("", httplib::sanitize_filename(""));
  362. // Null bytes stripped
  363. EXPECT_EQ("safe.txt",
  364. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  365. // Whitespace-only rejected
  366. EXPECT_EQ("", httplib::sanitize_filename(" "));
  367. }
  368. // Forward declaration (see the base64_encode note below): split builds move the
  369. // definition into httplib.cc, so re-declaring it here lets the test link.
  370. namespace httplib {
  371. namespace detail {
  372. bool is_chunked_transfer_encoding(const Headers &headers);
  373. } // namespace detail
  374. } // namespace httplib
  375. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  376. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  377. auto make = [](std::initializer_list<const char *> lines) {
  378. Headers h;
  379. for (auto te : lines) {
  380. if (te) { h.emplace("Transfer-Encoding", te); }
  381. }
  382. return h;
  383. };
  384. // Sole coding, matched case-insensitively.
  385. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  386. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  387. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  388. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  389. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  390. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  391. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  392. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  393. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  394. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  395. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  396. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  397. // Multiple Transfer-Encoding lines: iteration order for duplicate keys is not
  398. // portable, so any line naming chunked is treated as chunked (fail safe).
  399. // The result must not depend on the order the lines were added.
  400. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  401. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  402. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  403. }
  404. // Forward declaration: in split builds split.py strips `inline` and moves the
  405. // definition into httplib.cc, so detail::base64_encode is not visible from the
  406. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  407. // in both header-only and split builds.
  408. namespace httplib {
  409. namespace detail {
  410. std::string base64_encode(const std::string &in);
  411. } // namespace detail
  412. } // namespace httplib
  413. TEST(Base64EncodeTest, KnownAnswers) {
  414. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  415. // where the accumulator's top bit is already set before the next shift.
  416. EXPECT_EQ("", detail::base64_encode(""));
  417. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  418. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  419. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  420. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  421. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  422. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  423. // High bytes keep the top bit set across several rounds.
  424. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  425. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  426. }
  427. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  428. string unescapedCharacters = "-_.!~*'()";
  429. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  430. }
  431. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  432. string reservedCharacters = ";,/?:@&=+$";
  433. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  434. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  435. }
  436. TEST(ClientQueryOrder, PreserveOrder) {
  437. // This test reproduces Issue #2259: client may reorder query parameters
  438. // when sending a GET request. The expected behavior is that the client
  439. // preserves the original query string order when the caller supplied it
  440. // as part of the path.
  441. Server svr;
  442. svr.Get("/", [&](const Request &req, Response &res) {
  443. // Echo back the raw target so the test can assert ordering
  444. res.set_content(req.target, "text/plain");
  445. });
  446. std::thread t{[&] { svr.listen(HOST, PORT); }};
  447. auto se = detail::scope_exit([&] {
  448. svr.stop();
  449. t.join();
  450. ASSERT_FALSE(svr.is_running());
  451. });
  452. svr.wait_until_ready();
  453. Client cli(HOST, PORT);
  454. ASSERT_TRUE(cli.is_valid());
  455. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  456. auto res = cli.Get(original);
  457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  458. // Expect the echoed target to exactly match the original path (order
  459. // preserved)
  460. EXPECT_EQ(res->body, original);
  461. }
  462. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  463. string chineseCharacters = U8("中国語");
  464. string russianCharacters = U8("дом");
  465. string brazilianCharacters = U8("óculos");
  466. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  467. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  468. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  469. "%D0%B4%D0%BE%D0%BC");
  470. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  471. }
  472. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  473. string unescapedCharacters = "-_.!~*'()";
  474. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  475. }
  476. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  477. string reservedCharacters = ";,/?:@&=+$";
  478. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  479. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  480. }
  481. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  482. string chineseCharacters = U8("中国語");
  483. string russianCharacters = U8("дом");
  484. string brazilianCharacters = U8("óculos");
  485. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  486. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  487. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  488. "%D0%B4%D0%BE%D0%BC");
  489. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  490. }
  491. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  492. // Issue #2082 use case: encoding path component with ampersand
  493. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  494. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  495. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  496. }
  497. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  498. string unescapedCharacters = "-_.!~*'()";
  499. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  500. }
  501. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  502. string reservedCharacters = ";,/?:@&=+$#";
  503. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  504. }
  505. TEST(EncodeUriTest, TestUTF8Characters) {
  506. string chineseCharacters = U8("中国語");
  507. string russianCharacters = U8("дом");
  508. string brazilianCharacters = U8("óculos");
  509. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  510. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  511. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  512. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  513. }
  514. TEST(EncodeUriTest, TestCompleteUri) {
  515. string uri =
  516. "https://example.com/path/to/resource?query=value&param=test#fragment";
  517. EXPECT_EQ(
  518. httplib::encode_uri(uri),
  519. "https://example.com/path/to/resource?query=value&param=test#fragment");
  520. }
  521. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  522. string uri =
  523. "https://example.com/path with spaces/file name.html?q=hello world";
  524. EXPECT_EQ(httplib::encode_uri(uri),
  525. "https://example.com/path%20with%20spaces/"
  526. "file%20name.html?q=hello%20world");
  527. }
  528. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  529. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  530. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  531. }
  532. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  533. string unescapedCharacters = "-_.!~*'()";
  534. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  535. }
  536. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  537. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  538. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  539. string encodedBrazilian = "%C3%B3culos";
  540. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  541. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  542. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  543. }
  544. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  545. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  546. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  547. "Piri Tommy Villiers - on & on");
  548. }
  549. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  550. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  551. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  552. }
  553. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  554. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  555. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  556. }
  557. TEST(DecodeUriTest, TestUTF8Characters) {
  558. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  559. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  560. string encodedBrazilian = "%C3%B3culos";
  561. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  562. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  563. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  564. }
  565. TEST(DecodeUriTest, TestCompleteUri) {
  566. string encodedUri = "https://example.com/path%20with%20spaces/"
  567. "file%20name.html?q=hello%20world";
  568. EXPECT_EQ(
  569. httplib::decode_uri(encodedUri),
  570. "https://example.com/path with spaces/file name.html?q=hello world");
  571. }
  572. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  573. string original =
  574. "https://example.com/path with spaces/file name.html?q=hello world";
  575. string encoded = httplib::encode_uri(original);
  576. string decoded = httplib::decode_uri(encoded);
  577. EXPECT_EQ(decoded, original);
  578. }
  579. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  580. string original = "Piri Tommy Villiers - on & on";
  581. string encoded = httplib::encode_uri_component(original);
  582. string decoded = httplib::decode_uri_component(encoded);
  583. EXPECT_EQ(decoded, original);
  584. }
  585. TEST(TrimTests, TrimStringTests) {
  586. EXPECT_EQ("abc", detail::trim_copy("abc"));
  587. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  588. EXPECT_TRUE(detail::trim_copy("").empty());
  589. }
  590. TEST(AsciiTest, LocaleIndependentClassification) {
  591. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  592. // which consult the global C locale: std::isalnum(0xC5) can return true
  593. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  594. // helpers must classify every byte by the ASCII grammar alone.
  595. for (int i = 0; i < 256; i++) {
  596. auto c = static_cast<char>(i);
  597. auto is_digit = i >= '0' && i <= '9';
  598. auto is_upper = i >= 'A' && i <= 'Z';
  599. auto is_lower = i >= 'a' && i <= 'z';
  600. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  601. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  602. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  603. << "byte " << i;
  604. }
  605. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  606. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  607. // Non-ASCII bytes must be percent-encoded, never passed through as
  608. // alphanumeric.
  609. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  610. }
  611. TEST(FromCharsTest, Double) {
  612. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  613. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  614. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  615. auto parse = [](const std::string &s, double &v) {
  616. return detail::from_chars(s.data(), s.data() + s.size(), v);
  617. };
  618. double v = -1.0;
  619. // Representative quality values.
  620. EXPECT_EQ(parse("0", v).ec, std::errc{});
  621. EXPECT_DOUBLE_EQ(v, 0.0);
  622. EXPECT_EQ(parse("1", v).ec, std::errc{});
  623. EXPECT_DOUBLE_EQ(v, 1.0);
  624. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  625. EXPECT_DOUBLE_EQ(v, 0.8);
  626. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  627. EXPECT_DOUBLE_EQ(v, 0.001);
  628. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  629. EXPECT_DOUBLE_EQ(v, 1.0);
  630. // A missing integer or fractional part is tolerated.
  631. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  632. EXPECT_DOUBLE_EQ(v, 0.5);
  633. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  634. EXPECT_DOUBLE_EQ(v, 5.0);
  635. // Values outside [0, 1] still parse; the caller range-checks them.
  636. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  637. EXPECT_DOUBLE_EQ(v, 123.456);
  638. // Stops at the first byte that is not part of the number and reports where.
  639. std::string trailing = "0.9, text/html";
  640. auto r = parse(trailing, v);
  641. EXPECT_EQ(r.ec, std::errc{});
  642. EXPECT_DOUBLE_EQ(v, 0.9);
  643. EXPECT_EQ(*r.ptr, ',');
  644. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  645. // outright, and an 'e'/'E' simply ends the number.
  646. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  647. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  648. std::string exp_input = "1.5e3";
  649. r = parse(exp_input, v);
  650. EXPECT_EQ(r.ec, std::errc{});
  651. EXPECT_DOUBLE_EQ(v, 1.5);
  652. EXPECT_EQ(*r.ptr, 'e');
  653. // Invalid inputs.
  654. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  655. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  656. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  657. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  658. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  659. // Pathological but well-formed inputs must stay bounded (no overflow, no
  660. // out-of-bounds table access) and stay within [0, 1] for the caller.
  661. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  662. std::errc{});
  663. EXPECT_DOUBLE_EQ(v, 0.0);
  664. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  665. std::errc{});
  666. EXPECT_GE(v, 0.0);
  667. EXPECT_LE(v, 1.0);
  668. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  669. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  670. }
  671. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  672. // Simple case without quality values
  673. std::vector<std::string> result1;
  674. EXPECT_TRUE(detail::parse_accept_header(
  675. "text/html,application/json,text/plain", result1));
  676. EXPECT_EQ(result1.size(), 3U);
  677. EXPECT_EQ(result1[0], "text/html");
  678. EXPECT_EQ(result1[1], "application/json");
  679. EXPECT_EQ(result1[2], "text/plain");
  680. // With quality values
  681. std::vector<std::string> result2;
  682. EXPECT_TRUE(detail::parse_accept_header(
  683. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  684. EXPECT_EQ(result2.size(), 3U);
  685. EXPECT_EQ(result2[0], "application/json"); // highest q value
  686. EXPECT_EQ(result2[1], "text/html");
  687. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  688. }
  689. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  690. // Mixed with and without quality values
  691. std::vector<std::string> result;
  692. EXPECT_TRUE(detail::parse_accept_header(
  693. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  694. EXPECT_EQ(result.size(), 3U);
  695. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  696. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  697. EXPECT_EQ(result[2], "application/json"); // q=0.5
  698. }
  699. TEST(ParseAcceptHeaderTest, EdgeCases) {
  700. // Empty header
  701. std::vector<std::string> empty_result;
  702. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  703. EXPECT_TRUE(empty_result.empty());
  704. // Single type
  705. std::vector<std::string> single_result;
  706. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  707. EXPECT_EQ(single_result.size(), 1U);
  708. EXPECT_EQ(single_result[0], "application/json");
  709. // Wildcard types
  710. std::vector<std::string> wildcard_result;
  711. EXPECT_TRUE(detail::parse_accept_header(
  712. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  713. EXPECT_EQ(wildcard_result.size(), 3U);
  714. EXPECT_EQ(wildcard_result[0], "application/json");
  715. EXPECT_EQ(wildcard_result[1], "text/*");
  716. EXPECT_EQ(wildcard_result[2], "*/*");
  717. }
  718. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  719. // Common browser Accept header
  720. std::vector<std::string> browser_result;
  721. EXPECT_TRUE(
  722. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  723. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  724. browser_result));
  725. EXPECT_EQ(browser_result.size(), 6U);
  726. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  727. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  728. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  729. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  730. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  731. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  732. // API client header
  733. std::vector<std::string> api_result;
  734. EXPECT_TRUE(detail::parse_accept_header(
  735. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  736. api_result));
  737. EXPECT_EQ(api_result.size(), 3U);
  738. EXPECT_EQ(api_result[0], "application/json");
  739. EXPECT_EQ(api_result[1], "application/xml");
  740. EXPECT_EQ(api_result[2], "text/plain");
  741. }
  742. TEST(ParseAcceptHeaderTest, SpecialCases) {
  743. // Quality value with 3 decimal places
  744. std::vector<std::string> decimal_result;
  745. EXPECT_TRUE(detail::parse_accept_header(
  746. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  747. EXPECT_EQ(decimal_result.size(), 2U);
  748. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  749. EXPECT_EQ(decimal_result[1], "text/html");
  750. // Zero quality (should still be included but with lowest priority)
  751. std::vector<std::string> zero_q_result;
  752. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  753. zero_q_result));
  754. EXPECT_EQ(zero_q_result.size(), 2U);
  755. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  756. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  757. // No spaces around commas
  758. std::vector<std::string> no_space_result;
  759. EXPECT_TRUE(detail::parse_accept_header(
  760. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  761. no_space_result));
  762. EXPECT_EQ(no_space_result.size(), 3U);
  763. EXPECT_EQ(no_space_result[0], "text/html");
  764. EXPECT_EQ(no_space_result[1], "application/json");
  765. EXPECT_EQ(no_space_result[2], "text/plain");
  766. }
  767. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  768. // Quality values always use '.' as the decimal separator, so parsing must
  769. // not depend on the process locale. An embedding application may have
  770. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  771. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  772. std::string saved = cur ? cur : "C";
  773. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  774. "fr_FR.UTF-8"};
  775. bool switched = false;
  776. for (const auto loc : comma_locales) {
  777. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  778. std::localeconv()->decimal_point[0] == ',') {
  779. switched = true;
  780. break;
  781. }
  782. }
  783. if (!switched) {
  784. std::setlocale(LC_NUMERIC, saved.c_str());
  785. GTEST_SKIP() << "no comma-decimal locale available on this host";
  786. }
  787. // The higher-weighted type appears later in the list, so a correct parse
  788. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  789. // sensitive parse reads both weights as 0 and leaves the original order.
  790. std::vector<std::string> result;
  791. EXPECT_TRUE(detail::parse_accept_header(
  792. "application/json;q=0.1,text/html;q=0.9", result));
  793. ASSERT_EQ(result.size(), 2U);
  794. EXPECT_EQ(result[0], "text/html");
  795. EXPECT_EQ(result[1], "application/json");
  796. std::setlocale(LC_NUMERIC, saved.c_str());
  797. }
  798. TEST(ParseAcceptHeaderTest, InvalidCases) {
  799. std::vector<std::string> result;
  800. // Invalid quality value (> 1.0)
  801. EXPECT_FALSE(
  802. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  803. // Invalid quality value (< 0.0)
  804. EXPECT_FALSE(
  805. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  806. // Invalid quality value (not a number)
  807. EXPECT_FALSE(detail::parse_accept_header(
  808. "text/html;q=invalid,application/json", result));
  809. // Empty quality value
  810. EXPECT_FALSE(
  811. detail::parse_accept_header("text/html;q=,application/json", result));
  812. // Invalid media type format (no slash and not wildcard)
  813. EXPECT_FALSE(
  814. detail::parse_accept_header("invalidtype,application/json", result));
  815. // Empty media type
  816. result.clear();
  817. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  818. // Only commas
  819. result.clear();
  820. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  821. // Valid cases should still work
  822. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  823. EXPECT_EQ(result.size(), 1U);
  824. EXPECT_EQ(result[0], "*/*");
  825. EXPECT_TRUE(detail::parse_accept_header("*", result));
  826. EXPECT_EQ(result.size(), 1U);
  827. EXPECT_EQ(result[0], "*");
  828. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  829. EXPECT_EQ(result.size(), 1U);
  830. EXPECT_EQ(result[0], "text/*");
  831. }
  832. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  833. Server svr;
  834. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  835. EXPECT_EQ(req.accept_content_types.size(), 3U);
  836. EXPECT_EQ(req.accept_content_types[0], "application/json");
  837. EXPECT_EQ(req.accept_content_types[1], "text/html");
  838. EXPECT_EQ(req.accept_content_types[2], "*/*");
  839. res.set_content("ok", "text/plain");
  840. });
  841. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  842. EXPECT_TRUE(false);
  843. res.set_content("bad request", "text/plain");
  844. });
  845. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  846. auto se = detail::scope_exit([&] {
  847. svr.stop();
  848. listen_thread.join();
  849. ASSERT_FALSE(svr.is_running());
  850. });
  851. svr.wait_until_ready();
  852. Client cli("localhost", PORT);
  853. {
  854. auto res = cli.Get(
  855. "/accept_ok",
  856. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  858. EXPECT_EQ(StatusCode::OK_200, res->status);
  859. }
  860. {
  861. auto res = cli.Get("/accept_bad_request",
  862. Headers{{"Accept", "text/html;q=abc,application/json"}});
  863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  864. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  865. }
  866. }
  867. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  868. Server svr;
  869. svr.Get("/", [](const Request & /*req*/, Response &res) {
  870. res.set_content("ok", "text/plain");
  871. });
  872. std::atomic<int> start_count{0};
  873. std::atomic<bool> running_when_called{false};
  874. svr.set_start_handler([&]() {
  875. running_when_called = svr.is_running();
  876. start_count++;
  877. });
  878. auto port = svr.bind_to_any_port(HOST);
  879. std::thread t([&]() { svr.listen_after_bind(); });
  880. auto se = detail::scope_exit([&] {
  881. svr.stop();
  882. t.join();
  883. ASSERT_FALSE(svr.is_running());
  884. });
  885. svr.wait_until_ready();
  886. // A successful request proves the accept loop is running, which the start
  887. // handler precedes; so by now the handler must have run exactly once.
  888. Client cli(HOST, port);
  889. cli.set_connection_timeout(std::chrono::seconds(5));
  890. auto res = cli.Get("/");
  891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  892. EXPECT_EQ(StatusCode::OK_200, res->status);
  893. EXPECT_EQ(1, start_count.load());
  894. EXPECT_TRUE(running_when_called.load());
  895. }
  896. TEST(DivideTest, DivideStringTests) {
  897. auto divide = [](const std::string &str, char d) {
  898. std::string lhs;
  899. std::string rhs;
  900. detail::divide(str, d,
  901. [&](const char *lhs_data, std::size_t lhs_size,
  902. const char *rhs_data, std::size_t rhs_size) {
  903. lhs.assign(lhs_data, lhs_size);
  904. rhs.assign(rhs_data, rhs_size);
  905. });
  906. return std::make_pair(std::move(lhs), std::move(rhs));
  907. };
  908. {
  909. const auto res = divide("", '=');
  910. EXPECT_EQ(res.first, "");
  911. EXPECT_EQ(res.second, "");
  912. }
  913. {
  914. const auto res = divide("=", '=');
  915. EXPECT_EQ(res.first, "");
  916. EXPECT_EQ(res.second, "");
  917. }
  918. {
  919. const auto res = divide(" ", '=');
  920. EXPECT_EQ(res.first, " ");
  921. EXPECT_EQ(res.second, "");
  922. }
  923. {
  924. const auto res = divide("a", '=');
  925. EXPECT_EQ(res.first, "a");
  926. EXPECT_EQ(res.second, "");
  927. }
  928. {
  929. const auto res = divide("a=", '=');
  930. EXPECT_EQ(res.first, "a");
  931. EXPECT_EQ(res.second, "");
  932. }
  933. {
  934. const auto res = divide("=b", '=');
  935. EXPECT_EQ(res.first, "");
  936. EXPECT_EQ(res.second, "b");
  937. }
  938. {
  939. const auto res = divide("a=b", '=');
  940. EXPECT_EQ(res.first, "a");
  941. EXPECT_EQ(res.second, "b");
  942. }
  943. {
  944. const auto res = divide("a=b=", '=');
  945. EXPECT_EQ(res.first, "a");
  946. EXPECT_EQ(res.second, "b=");
  947. }
  948. {
  949. const auto res = divide("a=b=c", '=');
  950. EXPECT_EQ(res.first, "a");
  951. EXPECT_EQ(res.second, "b=c");
  952. }
  953. }
  954. TEST(SplitTest, ParseQueryString) {
  955. string s = "key1=val1&key2=val2&key3=val3";
  956. Params dic;
  957. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  958. [&](const char *b, const char *e) {
  959. string key, val;
  960. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  961. if (key.empty()) {
  962. key.assign(b2, e2);
  963. } else {
  964. val.assign(b2, e2);
  965. }
  966. });
  967. dic.emplace(key, val);
  968. });
  969. EXPECT_EQ("val1", dic.find("key1")->second);
  970. EXPECT_EQ("val2", dic.find("key2")->second);
  971. EXPECT_EQ("val3", dic.find("key3")->second);
  972. }
  973. TEST(SplitTest, ParseInvalidQueryTests) {
  974. {
  975. string s = " ";
  976. Params dict;
  977. detail::parse_query_text(s, dict);
  978. EXPECT_TRUE(dict.empty());
  979. }
  980. {
  981. string s = " = =";
  982. Params dict;
  983. detail::parse_query_text(s, dict);
  984. EXPECT_TRUE(dict.empty());
  985. }
  986. }
  987. TEST(ParseQueryTest, ParseQueryString) {
  988. {
  989. std::string s = "key1=val1&key2=val2&key3=val3";
  990. Params dic;
  991. detail::parse_query_text(s, dic);
  992. EXPECT_EQ("val1", dic.find("key1")->second);
  993. EXPECT_EQ("val2", dic.find("key2")->second);
  994. EXPECT_EQ("val3", dic.find("key3")->second);
  995. }
  996. {
  997. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  998. Params dic;
  999. detail::parse_query_text(s, dic);
  1000. EXPECT_EQ("", dic.find("key1")->second);
  1001. EXPECT_EQ("val1", dic.find("key2")->second);
  1002. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1003. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1004. }
  1005. }
  1006. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1007. Params dic;
  1008. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1009. dic.emplace("key1", "val1");
  1010. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1011. dic.emplace("key2", "val2");
  1012. dic.emplace("key3", "val3");
  1013. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1014. }
  1015. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1016. string content_type = "multipart/form-data; boundary=something";
  1017. string boundary;
  1018. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1019. EXPECT_TRUE(ret);
  1020. EXPECT_EQ(boundary, "something");
  1021. }
  1022. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1023. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1024. string boundary;
  1025. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1026. EXPECT_TRUE(ret);
  1027. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1028. }
  1029. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1030. string content_type =
  1031. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1032. string boundary;
  1033. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1034. EXPECT_TRUE(ret);
  1035. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1036. }
  1037. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1038. string content_type =
  1039. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1040. string boundary;
  1041. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1042. EXPECT_TRUE(ret);
  1043. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1044. }
  1045. TEST(GetHeaderValueTest, DefaultValue) {
  1046. Headers headers = {{"Dummy", "Dummy"}};
  1047. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1048. EXPECT_STREQ("text/plain", val);
  1049. }
  1050. TEST(GetHeaderValueTest, DefaultValueInt) {
  1051. Headers headers = {{"Dummy", "Dummy"}};
  1052. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1053. EXPECT_EQ(100ull, val);
  1054. }
  1055. TEST(GetHeaderValueTest, RegularValue) {
  1056. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1057. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1058. EXPECT_STREQ("text/html", val);
  1059. }
  1060. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1061. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1062. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1063. EXPECT_STREQ("text/html", val);
  1064. }
  1065. TEST(GetHeaderValueTest, SetContent) {
  1066. Response res;
  1067. res.set_content("html", "text/html");
  1068. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1069. res.set_content("text", "text/plain");
  1070. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1071. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1072. }
  1073. TEST(GetHeaderValueTest, RegularValueInt) {
  1074. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1075. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1076. EXPECT_EQ(100ull, val);
  1077. }
  1078. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1079. Headers headers = {{"Content-Length", "x"}};
  1080. auto is_invalid_value = false;
  1081. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1082. is_invalid_value);
  1083. EXPECT_EQ(0ull, val);
  1084. EXPECT_TRUE(is_invalid_value);
  1085. }
  1086. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1087. // An all-digit value that overflows size_t must be reported as invalid, not
  1088. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1089. // a large length to a small one on 32-bit builds, leaving the framing length
  1090. // wrong while is_invalid_value stayed false.
  1091. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1092. auto is_invalid_value = false;
  1093. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1094. is_invalid_value);
  1095. EXPECT_TRUE(is_invalid_value);
  1096. // A well-formed length is unaffected.
  1097. Headers ok = {{"Content-Length", "1234"}};
  1098. is_invalid_value = false;
  1099. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1100. is_invalid_value);
  1101. EXPECT_EQ(1234ull, val);
  1102. EXPECT_FALSE(is_invalid_value);
  1103. }
  1104. TEST(GetHeaderValueTest, Range) {
  1105. {
  1106. Headers headers = {make_range_header({{1, -1}})};
  1107. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1108. EXPECT_STREQ("bytes=1-", val);
  1109. }
  1110. {
  1111. Headers headers = {make_range_header({{-1, 1}})};
  1112. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1113. EXPECT_STREQ("bytes=-1", val);
  1114. }
  1115. {
  1116. Headers headers = {make_range_header({{1, 10}})};
  1117. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1118. EXPECT_STREQ("bytes=1-10", val);
  1119. }
  1120. {
  1121. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1122. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1123. EXPECT_STREQ("bytes=1-10, 100-", val);
  1124. }
  1125. {
  1126. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1127. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1128. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1129. }
  1130. {
  1131. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1132. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1133. EXPECT_STREQ("bytes=0-0, -1", val);
  1134. }
  1135. }
  1136. // Joins every field of a Headers into "name=value " so a whole traversal can
  1137. // be compared in one assertion.
  1138. static std::string headers_to_string(const Headers &headers) {
  1139. std::string s;
  1140. for (const auto &header : headers) {
  1141. s += header.first + "=" + header.second + " ";
  1142. }
  1143. return s;
  1144. }
  1145. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1146. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1147. // to depend on the standard library (libstdc++ handed back duplicates in
  1148. // reverse insertion order, libc++ in insertion order).
  1149. Request req;
  1150. req.set_header("Accept-Encoding", "gzip");
  1151. req.set_header("Accept-Encoding", "deflate");
  1152. req.set_header("Accept-Encoding", "br");
  1153. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1154. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1155. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1156. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1157. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1158. }
  1159. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1160. Request req;
  1161. req.set_header("X-Test", "only");
  1162. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1163. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1164. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1165. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1166. }
  1167. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1168. Headers headers;
  1169. headers.emplace("Host", "example.com");
  1170. headers.emplace("Accept-Encoding", "gzip");
  1171. headers.emplace("User-Agent", "test");
  1172. headers.emplace("Accept-Encoding", "deflate");
  1173. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1174. "Accept-Encoding=deflate ",
  1175. headers_to_string(headers));
  1176. }
  1177. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1178. Headers headers = {{"Content-Type", "text/html"},
  1179. {"CONTENT-TYPE", "text/xml"}};
  1180. EXPECT_EQ(2U, headers.count("content-type"));
  1181. auto it = headers.find("content-type");
  1182. ASSERT_TRUE(it != headers.end());
  1183. EXPECT_EQ("text/html", it->second);
  1184. }
  1185. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1186. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1187. // drop only those fields and leave everything positioned between them.
  1188. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1189. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1190. auto rng = headers.equal_range("a");
  1191. headers.erase(rng.first, rng.second);
  1192. EXPECT_EQ("X=x Y=y Z=z ", headers_to_string(headers));
  1193. }
  1194. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1195. Headers headers = {
  1196. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1197. EXPECT_EQ(3U, headers.erase("A"));
  1198. EXPECT_EQ(0U, headers.count("A"));
  1199. EXPECT_EQ("B=2 C=4 ", headers_to_string(headers));
  1200. }
  1201. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1202. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1203. headers.emplace_front("Host", "example.com");
  1204. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1205. headers_to_string(headers));
  1206. }
  1207. TEST(ParseHeaderValueTest, Range) {
  1208. {
  1209. Ranges ranges;
  1210. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1211. EXPECT_TRUE(ret);
  1212. EXPECT_EQ(1u, ranges.size());
  1213. EXPECT_EQ(1u, ranges[0].first);
  1214. EXPECT_EQ(-1, ranges[0].second);
  1215. }
  1216. {
  1217. Ranges ranges;
  1218. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1219. EXPECT_TRUE(ret);
  1220. EXPECT_EQ(1u, ranges.size());
  1221. EXPECT_EQ(-1, ranges[0].first);
  1222. EXPECT_EQ(1u, ranges[0].second);
  1223. }
  1224. {
  1225. Ranges ranges;
  1226. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1227. EXPECT_TRUE(ret);
  1228. EXPECT_EQ(1u, ranges.size());
  1229. EXPECT_EQ(1u, ranges[0].first);
  1230. EXPECT_EQ(10u, ranges[0].second);
  1231. }
  1232. {
  1233. Ranges ranges;
  1234. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1235. EXPECT_FALSE(ret);
  1236. }
  1237. {
  1238. Ranges ranges;
  1239. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1240. EXPECT_TRUE(ret);
  1241. EXPECT_EQ(2u, ranges.size());
  1242. EXPECT_EQ(1u, ranges[0].first);
  1243. EXPECT_EQ(10u, ranges[0].second);
  1244. EXPECT_EQ(100u, ranges[1].first);
  1245. EXPECT_EQ(-1, ranges[1].second);
  1246. }
  1247. {
  1248. Ranges ranges;
  1249. auto ret =
  1250. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1251. EXPECT_TRUE(ret);
  1252. EXPECT_EQ(3u, ranges.size());
  1253. EXPECT_EQ(1u, ranges[0].first);
  1254. EXPECT_EQ(10u, ranges[0].second);
  1255. EXPECT_EQ(100u, ranges[1].first);
  1256. EXPECT_EQ(200u, ranges[1].second);
  1257. EXPECT_EQ(300u, ranges[2].first);
  1258. EXPECT_EQ(400u, ranges[2].second);
  1259. }
  1260. {
  1261. Ranges ranges;
  1262. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1263. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1264. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1265. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1266. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1267. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1268. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1269. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1270. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1271. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1272. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1273. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1274. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1275. EXPECT_TRUE(ranges.empty());
  1276. }
  1277. }
  1278. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1279. Request req;
  1280. req.set_header("Accept-Encoding", "gzip");
  1281. Response res;
  1282. res.set_header("Content-Type", "text/plain");
  1283. auto ret = detail::encoding_type(req, res);
  1284. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1285. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1286. #else
  1287. EXPECT_TRUE(ret == detail::EncodingType::None);
  1288. #endif
  1289. }
  1290. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1291. Request req;
  1292. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1293. Response res;
  1294. res.set_header("Content-Type", "text/plain");
  1295. auto ret = detail::encoding_type(req, res);
  1296. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1297. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1298. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1299. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1300. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1301. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1302. #else
  1303. EXPECT_TRUE(ret == detail::EncodingType::None);
  1304. #endif
  1305. }
  1306. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1307. Request req;
  1308. req.set_header("Accept-Encoding",
  1309. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1310. Response res;
  1311. res.set_header("Content-Type", "text/plain");
  1312. auto ret = detail::encoding_type(req, res);
  1313. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1314. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1315. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1316. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1317. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1318. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1319. #else
  1320. EXPECT_TRUE(ret == detail::EncodingType::None);
  1321. #endif
  1322. }
  1323. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1324. // All supported encodings rejected with q=0 should return None
  1325. Request req;
  1326. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1327. Response res;
  1328. res.set_header("Content-Type", "text/plain");
  1329. auto ret = detail::encoding_type(req, res);
  1330. EXPECT_TRUE(ret == detail::EncodingType::None);
  1331. }
  1332. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1333. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1334. Request req;
  1335. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1336. Response res;
  1337. res.set_header("Content-Type", "text/plain");
  1338. auto ret = detail::encoding_type(req, res);
  1339. EXPECT_TRUE(ret == detail::EncodingType::None);
  1340. }
  1341. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1342. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1343. Request req;
  1344. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1345. Response res;
  1346. res.set_header("Content-Type", "text/plain");
  1347. auto ret = detail::encoding_type(req, res);
  1348. EXPECT_TRUE(ret == detail::EncodingType::None);
  1349. }
  1350. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1351. // RFC 7231: Accept-Encoding values are case-insensitive
  1352. Request req;
  1353. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1354. Response res;
  1355. res.set_header("Content-Type", "text/plain");
  1356. auto ret = detail::encoding_type(req, res);
  1357. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1358. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1359. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1360. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1361. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1362. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1363. #else
  1364. EXPECT_TRUE(ret == detail::EncodingType::None);
  1365. #endif
  1366. }
  1367. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1368. // q value should determine priority, not hardcoded order
  1369. Request req;
  1370. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1371. Response res;
  1372. res.set_header("Content-Type", "text/plain");
  1373. auto ret = detail::encoding_type(req, res);
  1374. // gzip has highest q=1.0, so it should be selected even though
  1375. // br and zstd are also supported
  1376. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1377. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1378. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1379. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1380. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1381. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1382. #else
  1383. EXPECT_TRUE(ret == detail::EncodingType::None);
  1384. #endif
  1385. }
  1386. TEST(BufferStreamTest, read) {
  1387. detail::BufferStream strm1;
  1388. Stream &strm = strm1;
  1389. EXPECT_EQ(5, strm.write("hello"));
  1390. char buf[512];
  1391. EXPECT_EQ(2, strm.read(buf, 2));
  1392. EXPECT_EQ('h', buf[0]);
  1393. EXPECT_EQ('e', buf[1]);
  1394. EXPECT_EQ(2, strm.read(buf, 2));
  1395. EXPECT_EQ('l', buf[0]);
  1396. EXPECT_EQ('l', buf[1]);
  1397. EXPECT_EQ(1, strm.read(buf, 1));
  1398. EXPECT_EQ('o', buf[0]);
  1399. EXPECT_EQ(0, strm.read(buf, 1));
  1400. }
  1401. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1402. auto host = "www.httpwatch.com";
  1403. auto ip = hosted_at(host);
  1404. EXPECT_EQ("23.96.13.243", ip);
  1405. std::vector<std::string> addrs;
  1406. hosted_at(host, addrs);
  1407. EXPECT_EQ(1u, addrs.size());
  1408. }
  1409. #if 0 // It depends on each test environment...
  1410. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1411. auto host = "www.youtube.com";
  1412. std::vector<std::string> addrs;
  1413. hosted_at(host, addrs);
  1414. EXPECT_EQ(20u, addrs.size());
  1415. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1416. EXPECT_TRUE(it != addrs.end());
  1417. }
  1418. #endif
  1419. class ChunkedEncodingTest : public ::testing::Test {
  1420. protected:
  1421. ChunkedEncodingTest()
  1422. : cli_(HOST, PORT)
  1423. #ifdef CPPHTTPLIB_SSL_ENABLED
  1424. ,
  1425. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1426. #endif
  1427. {
  1428. cli_.set_connection_timeout(2);
  1429. #ifdef CPPHTTPLIB_SSL_ENABLED
  1430. cli_.enable_server_certificate_verification(false);
  1431. #endif
  1432. }
  1433. virtual void SetUp() {
  1434. read_file("./image.jpg", image_data_);
  1435. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1436. res.set_content("Hello World!", "text/plain");
  1437. });
  1438. svr_.Get(
  1439. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1440. res.set_chunked_content_provider(
  1441. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1442. size_t remaining = image_data_.size() - offset;
  1443. if (remaining == 0) {
  1444. sink.done();
  1445. } else {
  1446. constexpr size_t CHUNK_SIZE = 1024;
  1447. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1448. sink.write(&image_data_[offset], send_size);
  1449. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1450. }
  1451. return true;
  1452. });
  1453. });
  1454. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1455. svr_.wait_until_ready();
  1456. }
  1457. virtual void TearDown() {
  1458. svr_.stop();
  1459. if (!request_threads_.empty()) {
  1460. std::this_thread::sleep_for(std::chrono::seconds(1));
  1461. for (auto &t : request_threads_) {
  1462. t.join();
  1463. }
  1464. }
  1465. t_.join();
  1466. }
  1467. #ifdef CPPHTTPLIB_SSL_ENABLED
  1468. SSLClient cli_;
  1469. SSLServer svr_;
  1470. #else
  1471. Client cli_;
  1472. Server svr_;
  1473. #endif
  1474. thread t_;
  1475. std::vector<thread> request_threads_;
  1476. std::string image_data_;
  1477. };
  1478. TEST_F(ChunkedEncodingTest, NormalGet) {
  1479. auto res = cli_.Get("/chunked");
  1480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1481. std::string out;
  1482. read_file("./image.jpg", out);
  1483. EXPECT_EQ(StatusCode::OK_200, res->status);
  1484. EXPECT_EQ(out, res->body);
  1485. }
  1486. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1487. std::string body;
  1488. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1489. body.append(data, data_length);
  1490. return true;
  1491. });
  1492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1493. std::string out;
  1494. read_file("./image.jpg", out);
  1495. EXPECT_EQ(StatusCode::OK_200, res->status);
  1496. EXPECT_EQ(out, body);
  1497. }
  1498. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1499. std::string body;
  1500. auto res = cli_.Get(
  1501. "/chunked",
  1502. [&](const Response &response) {
  1503. EXPECT_EQ(StatusCode::OK_200, response.status);
  1504. return true;
  1505. },
  1506. [&](const char *data, size_t data_length) {
  1507. body.append(data, data_length);
  1508. return true;
  1509. });
  1510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1511. std::string out;
  1512. read_file("./image.jpg", out);
  1513. EXPECT_EQ(StatusCode::OK_200, res->status);
  1514. EXPECT_EQ(out, body);
  1515. }
  1516. TEST(RangeTest, FromHTTPBin_Online) {
  1517. auto host = "httpbingo.org";
  1518. auto path = std::string{"/range/32"};
  1519. #ifdef CPPHTTPLIB_SSL_ENABLED
  1520. auto port = 443;
  1521. SSLClient cli(host, port);
  1522. #else
  1523. auto port = 80;
  1524. Client cli(host, port);
  1525. #endif
  1526. cli.set_connection_timeout(5);
  1527. {
  1528. auto res = cli.Get(path);
  1529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1530. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1531. EXPECT_EQ(StatusCode::OK_200, res->status);
  1532. }
  1533. {
  1534. Headers headers = {make_range_header({{1, -1}})};
  1535. auto res = cli.Get(path, headers);
  1536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1537. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1538. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1539. }
  1540. {
  1541. Headers headers = {make_range_header({{1, 10}})};
  1542. auto res = cli.Get(path, headers);
  1543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1544. EXPECT_EQ("bcdefghijk", res->body);
  1545. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1546. }
  1547. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1548. // entire resource, while the original httpbin returned 200. Both are
  1549. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1550. {
  1551. Headers headers = {make_range_header({{0, 31}})};
  1552. auto res = cli.Get(path, headers);
  1553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1554. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1555. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1556. res->status == StatusCode::PartialContent_206);
  1557. }
  1558. {
  1559. Headers headers = {make_range_header({{0, -1}})};
  1560. auto res = cli.Get(path, headers);
  1561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1562. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1563. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1564. res->status == StatusCode::PartialContent_206);
  1565. }
  1566. // go-httpbin returns 206 with clamped range for over-range requests,
  1567. // while the original httpbin returned 416. Both behaviors are observed
  1568. // in real servers, so we only verify the request succeeds.
  1569. {
  1570. Headers headers = {make_range_header({{0, 32}})};
  1571. auto res = cli.Get(path, headers);
  1572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1573. }
  1574. }
  1575. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1576. auto host = "unresolvableaddress.local";
  1577. auto path = std::string{"/"};
  1578. #ifdef CPPHTTPLIB_SSL_ENABLED
  1579. auto port = 443;
  1580. SSLClient cli(host, port);
  1581. #else
  1582. auto port = 80;
  1583. Client cli(host, port);
  1584. #endif
  1585. cli.set_connection_timeout(1);
  1586. {
  1587. auto res = cli.Get(path);
  1588. ASSERT_FALSE(res);
  1589. }
  1590. std::this_thread::sleep_for(std::chrono::seconds(8));
  1591. }
  1592. #if defined(__linux__) && defined(__GLIBC__) && \
  1593. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1594. // Forward declaration: in split builds split.py strips `inline` and moves the
  1595. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1596. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1597. // against the symbol in both header-only and split builds.
  1598. namespace httplib {
  1599. namespace detail {
  1600. int getaddrinfo_with_timeout(const char *node, const char *service,
  1601. const struct addrinfo *hints,
  1602. struct addrinfo **res, time_t timeout_sec);
  1603. } // namespace detail
  1604. } // namespace httplib
  1605. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1606. //
  1607. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1608. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1609. // gai_suspend() call hits the connection timeout the function calls
  1610. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1611. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1612. // still alive and still references the now-destroyed stack frame.
  1613. //
  1614. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1615. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1616. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1617. // and runs them in a container.
  1618. namespace {
  1619. bool should_run_issue_2431_tests() {
  1620. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1621. return v && *v && std::string(v) != "0";
  1622. }
  1623. std::string unique_unresolvable_host(int n) {
  1624. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1625. // glibc still asks the configured nameserver — which is exactly the path
  1626. // we want to exercise. A unique label per call avoids the resolver cache.
  1627. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1628. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1629. std::to_string(n) + ".invalid";
  1630. }
  1631. } // namespace
  1632. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1633. if (!should_run_issue_2431_tests()) {
  1634. GTEST_SKIP()
  1635. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1636. }
  1637. for (int i = 0; i < 8; ++i) {
  1638. struct addrinfo hints;
  1639. memset(&hints, 0, sizeof(hints));
  1640. hints.ai_family = AF_UNSPEC;
  1641. hints.ai_socktype = SOCK_STREAM;
  1642. auto host = unique_unresolvable_host(i);
  1643. struct addrinfo *result = nullptr;
  1644. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1645. &result, /*timeout_sec=*/1);
  1646. if (rc == 0 && result) { freeaddrinfo(result); }
  1647. }
  1648. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1649. // stack region they still believe holds their gaicb.
  1650. std::this_thread::sleep_for(std::chrono::seconds(3));
  1651. }
  1652. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1653. if (!should_run_issue_2431_tests()) {
  1654. GTEST_SKIP()
  1655. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1656. }
  1657. std::atomic<bool> stop{false};
  1658. std::vector<std::thread> threads;
  1659. for (int t = 0; t < 8; ++t) {
  1660. threads.emplace_back([t, &stop] {
  1661. int i = 0;
  1662. while (!stop.load(std::memory_order_relaxed)) {
  1663. struct addrinfo hints;
  1664. memset(&hints, 0, sizeof(hints));
  1665. hints.ai_family = AF_UNSPEC;
  1666. hints.ai_socktype = SOCK_STREAM;
  1667. auto host = unique_unresolvable_host(t * 100000 + i++);
  1668. struct addrinfo *result = nullptr;
  1669. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1670. &result, /*timeout_sec=*/1);
  1671. if (rc == 0 && result) { freeaddrinfo(result); }
  1672. }
  1673. });
  1674. }
  1675. std::this_thread::sleep_for(std::chrono::seconds(8));
  1676. stop.store(true, std::memory_order_relaxed);
  1677. for (auto &th : threads) {
  1678. th.join();
  1679. }
  1680. std::this_thread::sleep_for(std::chrono::seconds(3));
  1681. }
  1682. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1683. if (!should_run_issue_2431_tests()) {
  1684. GTEST_SKIP()
  1685. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1686. }
  1687. std::atomic<bool> stop{false};
  1688. std::vector<std::thread> threads;
  1689. for (int t = 0; t < 8; ++t) {
  1690. threads.emplace_back([t, &stop] {
  1691. int i = 0;
  1692. while (!stop.load(std::memory_order_relaxed)) {
  1693. auto host = unique_unresolvable_host(t * 100000 + i++);
  1694. Client cli(host, 80);
  1695. cli.set_connection_timeout(1, 0);
  1696. cli.set_read_timeout(1, 0);
  1697. cli.set_write_timeout(1, 0);
  1698. (void)cli.Get("/");
  1699. }
  1700. });
  1701. }
  1702. std::this_thread::sleep_for(std::chrono::seconds(8));
  1703. stop.store(true, std::memory_order_relaxed);
  1704. for (auto &th : threads) {
  1705. th.join();
  1706. }
  1707. std::this_thread::sleep_for(std::chrono::seconds(3));
  1708. }
  1709. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1710. TEST(ConnectionErrorTest, InvalidHost) {
  1711. auto host = "-abcde.com";
  1712. #ifdef CPPHTTPLIB_SSL_ENABLED
  1713. auto port = 443;
  1714. SSLClient cli(host, port);
  1715. #else
  1716. auto port = 80;
  1717. Client cli(host, port);
  1718. #endif
  1719. cli.set_connection_timeout(std::chrono::seconds(2));
  1720. auto res = cli.Get("/");
  1721. ASSERT_TRUE(!res);
  1722. EXPECT_EQ(Error::Connection, res.error());
  1723. }
  1724. TEST(ConnectionErrorTest, InvalidHost2) {
  1725. auto host = "httpcan.org/";
  1726. #ifdef CPPHTTPLIB_SSL_ENABLED
  1727. SSLClient cli(host);
  1728. #else
  1729. Client cli(host);
  1730. #endif
  1731. cli.set_connection_timeout(std::chrono::seconds(2));
  1732. auto res = cli.Get("/");
  1733. ASSERT_TRUE(!res);
  1734. EXPECT_EQ(Error::Connection, res.error());
  1735. }
  1736. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1737. auto host = "httpcan.org/";
  1738. #ifdef CPPHTTPLIB_SSL_ENABLED
  1739. SSLClient cli(host);
  1740. #else
  1741. Client cli(host);
  1742. #endif
  1743. cli.set_connection_timeout(std::chrono::seconds(2));
  1744. auto res = cli.Get("/");
  1745. ASSERT_TRUE(!res);
  1746. stringstream s;
  1747. s << "error code: " << res.error();
  1748. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1749. }
  1750. TEST(ConnectionErrorTest, InvalidPort) {
  1751. auto host = "localhost";
  1752. auto port = 44380;
  1753. #ifdef CPPHTTPLIB_SSL_ENABLED
  1754. SSLClient cli(host, port);
  1755. #else
  1756. Client cli(host, port);
  1757. #endif
  1758. cli.set_connection_timeout(std::chrono::seconds(2));
  1759. auto res = cli.Get("/");
  1760. ASSERT_TRUE(!res);
  1761. EXPECT_TRUE(Error::Connection == res.error() ||
  1762. Error::ConnectionTimeout == res.error());
  1763. }
  1764. TEST(ConnectionErrorTest, Timeout_Online) {
  1765. auto host = "google.com";
  1766. #ifdef CPPHTTPLIB_SSL_ENABLED
  1767. auto port = 44380;
  1768. SSLClient cli(host, port);
  1769. #else
  1770. auto port = 8080;
  1771. Client cli(host, port);
  1772. #endif
  1773. cli.set_connection_timeout(std::chrono::seconds(2));
  1774. // only probe one address type so that the error reason
  1775. // correlates to the timed-out IPv4, not the unsupported
  1776. // IPv6 connection attempt
  1777. cli.set_address_family(AF_INET);
  1778. auto res = cli.Get("/");
  1779. ASSERT_TRUE(!res);
  1780. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1781. }
  1782. TEST(CancelTest, NoCancel_Online) {
  1783. auto host = "httpbingo.org";
  1784. auto path = std::string{"/range/32"};
  1785. #ifdef CPPHTTPLIB_SSL_ENABLED
  1786. auto port = 443;
  1787. SSLClient cli(host, port);
  1788. #else
  1789. auto port = 80;
  1790. Client cli(host, port);
  1791. #endif
  1792. cli.set_connection_timeout(std::chrono::seconds(5));
  1793. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1795. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1796. EXPECT_EQ(StatusCode::OK_200, res->status);
  1797. }
  1798. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1799. // Use /bytes with a large payload so that the DownloadProgress callback
  1800. // (which only fires for Content-Length responses) is invoked before the
  1801. // entire body is received, giving cancellation a chance to fire.
  1802. auto host = "httpbingo.org";
  1803. auto path = std::string{"/bytes/524288"};
  1804. #ifdef CPPHTTPLIB_SSL_ENABLED
  1805. auto port = 443;
  1806. SSLClient cli(host, port);
  1807. #else
  1808. auto port = 80;
  1809. Client cli(host, port);
  1810. #endif
  1811. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1812. cli.set_connection_timeout(std::chrono::seconds(5));
  1813. ASSERT_TRUE(!res);
  1814. EXPECT_EQ(Error::Canceled, res.error());
  1815. }
  1816. TEST(CancelTest, WithCancelLargePayload_Online) {
  1817. auto host = "httpbingo.org";
  1818. auto path = std::string{"/bytes/524288"};
  1819. #ifdef CPPHTTPLIB_SSL_ENABLED
  1820. auto port = 443;
  1821. SSLClient cli(host, port);
  1822. #else
  1823. auto port = 80;
  1824. Client cli(host, port);
  1825. #endif
  1826. cli.set_connection_timeout(std::chrono::seconds(5));
  1827. uint32_t count = 0;
  1828. auto res =
  1829. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1830. ASSERT_TRUE(!res);
  1831. EXPECT_EQ(Error::Canceled, res.error());
  1832. }
  1833. TEST(CancelTest, NoCancelPost) {
  1834. Server svr;
  1835. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1836. res.set_content("Hello World!", "text/plain");
  1837. });
  1838. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1839. auto se = detail::scope_exit([&] {
  1840. svr.stop();
  1841. thread.join();
  1842. ASSERT_FALSE(svr.is_running());
  1843. });
  1844. svr.wait_until_ready();
  1845. Client cli(HOST, PORT);
  1846. cli.set_connection_timeout(std::chrono::seconds(5));
  1847. auto res =
  1848. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1849. "application/json", [](uint64_t, uint64_t) { return true; });
  1850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1851. EXPECT_EQ("Hello World!", res->body);
  1852. EXPECT_EQ(StatusCode::OK_200, res->status);
  1853. }
  1854. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1855. Server svr;
  1856. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1857. res.set_content("Hello World!", "text/plain");
  1858. });
  1859. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1860. auto se = detail::scope_exit([&] {
  1861. svr.stop();
  1862. thread.join();
  1863. ASSERT_FALSE(svr.is_running());
  1864. });
  1865. svr.wait_until_ready();
  1866. Client cli(HOST, PORT);
  1867. cli.set_connection_timeout(std::chrono::seconds(5));
  1868. auto res =
  1869. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1870. "application/json", [](uint64_t, uint64_t) { return false; });
  1871. ASSERT_TRUE(!res);
  1872. EXPECT_EQ(Error::Canceled, res.error());
  1873. }
  1874. TEST(CancelTest, WithCancelLargePayloadPost) {
  1875. Server svr;
  1876. svr.set_payload_max_length(200 * 1024 * 1024);
  1877. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1878. res.set_content(LARGE_DATA, "text/plain");
  1879. });
  1880. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1881. auto se = detail::scope_exit([&] {
  1882. svr.stop();
  1883. thread.join();
  1884. ASSERT_FALSE(svr.is_running());
  1885. });
  1886. svr.wait_until_ready();
  1887. Client cli(HOST, PORT);
  1888. cli.set_payload_max_length(200 * 1024 * 1024);
  1889. cli.set_connection_timeout(std::chrono::seconds(5));
  1890. auto res =
  1891. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1892. "application/json", [](uint64_t, uint64_t) { return false; });
  1893. ASSERT_TRUE(!res);
  1894. EXPECT_EQ(Error::Canceled, res.error());
  1895. }
  1896. TEST(CancelTest, NoCancelPut) {
  1897. Server svr;
  1898. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1899. res.set_content("Hello World!", "text/plain");
  1900. });
  1901. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1902. auto se = detail::scope_exit([&] {
  1903. svr.stop();
  1904. thread.join();
  1905. ASSERT_FALSE(svr.is_running());
  1906. });
  1907. svr.wait_until_ready();
  1908. Client cli(HOST, PORT);
  1909. cli.set_connection_timeout(std::chrono::seconds(5));
  1910. auto res =
  1911. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1912. "application/json", [](uint64_t, uint64_t) { return true; });
  1913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1914. EXPECT_EQ("Hello World!", res->body);
  1915. EXPECT_EQ(StatusCode::OK_200, res->status);
  1916. }
  1917. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1918. Server svr;
  1919. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1920. res.set_content("Hello World!", "text/plain");
  1921. });
  1922. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1923. auto se = detail::scope_exit([&] {
  1924. svr.stop();
  1925. thread.join();
  1926. ASSERT_FALSE(svr.is_running());
  1927. });
  1928. svr.wait_until_ready();
  1929. Client cli(HOST, PORT);
  1930. cli.set_connection_timeout(std::chrono::seconds(5));
  1931. auto res =
  1932. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1933. "application/json", [](uint64_t, uint64_t) { return false; });
  1934. ASSERT_TRUE(!res);
  1935. EXPECT_EQ(Error::Canceled, res.error());
  1936. }
  1937. TEST(CancelTest, WithCancelLargePayloadPut) {
  1938. Server svr;
  1939. svr.set_payload_max_length(200 * 1024 * 1024);
  1940. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1941. res.set_content(LARGE_DATA, "text/plain");
  1942. });
  1943. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1944. auto se = detail::scope_exit([&] {
  1945. svr.stop();
  1946. thread.join();
  1947. ASSERT_FALSE(svr.is_running());
  1948. });
  1949. svr.wait_until_ready();
  1950. Client cli(HOST, PORT);
  1951. cli.set_payload_max_length(200 * 1024 * 1024);
  1952. cli.set_connection_timeout(std::chrono::seconds(5));
  1953. auto res =
  1954. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1955. "application/json", [](uint64_t, uint64_t) { return false; });
  1956. ASSERT_TRUE(!res);
  1957. EXPECT_EQ(Error::Canceled, res.error());
  1958. }
  1959. TEST(CancelTest, NoCancelPatch) {
  1960. Server svr;
  1961. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1962. res.set_content("Hello World!", "text/plain");
  1963. });
  1964. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1965. auto se = detail::scope_exit([&] {
  1966. svr.stop();
  1967. thread.join();
  1968. ASSERT_FALSE(svr.is_running());
  1969. });
  1970. svr.wait_until_ready();
  1971. Client cli(HOST, PORT);
  1972. cli.set_connection_timeout(std::chrono::seconds(5));
  1973. auto res =
  1974. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1975. "application/json", [](uint64_t, uint64_t) { return true; });
  1976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1977. EXPECT_EQ("Hello World!", res->body);
  1978. EXPECT_EQ(StatusCode::OK_200, res->status);
  1979. }
  1980. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1981. Server svr;
  1982. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1983. res.set_content("Hello World!", "text/plain");
  1984. });
  1985. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1986. auto se = detail::scope_exit([&] {
  1987. svr.stop();
  1988. thread.join();
  1989. ASSERT_FALSE(svr.is_running());
  1990. });
  1991. svr.wait_until_ready();
  1992. Client cli(HOST, PORT);
  1993. cli.set_connection_timeout(std::chrono::seconds(5));
  1994. auto res =
  1995. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1996. "application/json", [](uint64_t, uint64_t) { return false; });
  1997. ASSERT_TRUE(!res);
  1998. EXPECT_EQ(Error::Canceled, res.error());
  1999. }
  2000. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2001. Server svr;
  2002. svr.set_payload_max_length(200 * 1024 * 1024);
  2003. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2004. res.set_content(LARGE_DATA, "text/plain");
  2005. });
  2006. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2007. auto se = detail::scope_exit([&] {
  2008. svr.stop();
  2009. thread.join();
  2010. ASSERT_FALSE(svr.is_running());
  2011. });
  2012. svr.wait_until_ready();
  2013. Client cli(HOST, PORT);
  2014. cli.set_payload_max_length(200 * 1024 * 1024);
  2015. cli.set_connection_timeout(std::chrono::seconds(5));
  2016. auto res =
  2017. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2018. "application/json", [](uint64_t, uint64_t) { return false; });
  2019. ASSERT_TRUE(!res);
  2020. EXPECT_EQ(Error::Canceled, res.error());
  2021. }
  2022. TEST(CancelTest, NoCancelDelete) {
  2023. Server svr;
  2024. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2025. res.set_content("Hello World!", "text/plain");
  2026. });
  2027. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2028. auto se = detail::scope_exit([&] {
  2029. svr.stop();
  2030. thread.join();
  2031. ASSERT_FALSE(svr.is_running());
  2032. });
  2033. svr.wait_until_ready();
  2034. Client cli(HOST, PORT);
  2035. cli.set_connection_timeout(std::chrono::seconds(5));
  2036. auto res =
  2037. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2038. "application/json", [](uint64_t, uint64_t) { return true; });
  2039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2040. EXPECT_EQ("Hello World!", res->body);
  2041. EXPECT_EQ(StatusCode::OK_200, res->status);
  2042. }
  2043. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2044. Server svr;
  2045. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2046. res.set_content("Hello World!", "text/plain");
  2047. });
  2048. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2049. auto se = detail::scope_exit([&] {
  2050. svr.stop();
  2051. thread.join();
  2052. ASSERT_FALSE(svr.is_running());
  2053. });
  2054. svr.wait_until_ready();
  2055. Client cli(HOST, PORT);
  2056. cli.set_connection_timeout(std::chrono::seconds(5));
  2057. auto res =
  2058. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2059. "application/json", [](uint64_t, uint64_t) { return false; });
  2060. ASSERT_TRUE(!res);
  2061. EXPECT_EQ(Error::Canceled, res.error());
  2062. }
  2063. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2064. Server svr;
  2065. svr.set_payload_max_length(200 * 1024 * 1024);
  2066. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2067. res.set_content(LARGE_DATA, "text/plain");
  2068. });
  2069. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2070. auto se = detail::scope_exit([&] {
  2071. svr.stop();
  2072. thread.join();
  2073. ASSERT_FALSE(svr.is_running());
  2074. });
  2075. svr.wait_until_ready();
  2076. Client cli(HOST, PORT);
  2077. cli.set_payload_max_length(200 * 1024 * 1024);
  2078. cli.set_connection_timeout(std::chrono::seconds(5));
  2079. auto res =
  2080. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2081. "application/json", [](uint64_t, uint64_t) { return false; });
  2082. ASSERT_TRUE(!res);
  2083. EXPECT_EQ(Error::Canceled, res.error());
  2084. }
  2085. static std::string remove_whitespace(const std::string &input) {
  2086. std::string output;
  2087. output.reserve(input.size());
  2088. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2089. [](unsigned char c) { return !std::isspace(c); });
  2090. return output;
  2091. }
  2092. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2093. auto host = "httpbingo.org";
  2094. auto path = std::string{"/basic-auth/hello/world"};
  2095. #ifdef CPPHTTPLIB_SSL_ENABLED
  2096. auto port = 443;
  2097. SSLClient cli(host, port);
  2098. #else
  2099. auto port = 80;
  2100. Client cli(host, port);
  2101. #endif
  2102. {
  2103. auto res = cli.Get(path);
  2104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2105. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2106. }
  2107. {
  2108. auto res = cli.Get(
  2109. path, Headers{make_basic_authentication_header("hello", "world")});
  2110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2111. auto body = remove_whitespace(res->body);
  2112. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2113. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2114. EXPECT_EQ(StatusCode::OK_200, res->status);
  2115. }
  2116. {
  2117. cli.set_basic_auth("hello", "world");
  2118. auto res = cli.Get(path);
  2119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2120. auto body = remove_whitespace(res->body);
  2121. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2122. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2123. EXPECT_EQ(StatusCode::OK_200, res->status);
  2124. }
  2125. {
  2126. cli.set_basic_auth("hello", "bad");
  2127. auto res = cli.Get(path);
  2128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2129. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2130. }
  2131. {
  2132. cli.set_basic_auth("bad", "world");
  2133. auto res = cli.Get(path);
  2134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2135. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2136. }
  2137. }
  2138. #ifdef CPPHTTPLIB_SSL_ENABLED
  2139. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2140. auto host = "httpbingo.org";
  2141. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2142. auto paths = std::vector<std::string>{
  2143. "/digest-auth/auth/hello/world/MD5",
  2144. "/digest-auth/auth/hello/world/SHA-256",
  2145. };
  2146. auto port = 443;
  2147. SSLClient cli(host, port);
  2148. {
  2149. auto res = cli.Get(unauth_path);
  2150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2151. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2152. }
  2153. {
  2154. cli.set_digest_auth("hello", "world");
  2155. for (const auto &path : paths) {
  2156. auto res = cli.Get(path.c_str());
  2157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2158. auto body = remove_whitespace(res->body);
  2159. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2160. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2161. EXPECT_EQ(StatusCode::OK_200, res->status);
  2162. }
  2163. cli.set_digest_auth("hello", "bad");
  2164. for (const auto &path : paths) {
  2165. auto res = cli.Get(path.c_str());
  2166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2167. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2168. }
  2169. }
  2170. }
  2171. #endif
  2172. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2173. auto host = "google.com";
  2174. auto another_host = "example.com";
  2175. auto wrong_ip = "0.0.0.0";
  2176. #ifdef CPPHTTPLIB_SSL_ENABLED
  2177. SSLClient cli(host);
  2178. #else
  2179. Client cli(host);
  2180. #endif
  2181. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2182. auto res = cli.Get("/");
  2183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2184. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2185. }
  2186. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2187. auto host = "google.com";
  2188. auto wrong_ip = "0.0.0.0";
  2189. #ifdef CPPHTTPLIB_SSL_ENABLED
  2190. SSLClient cli(host);
  2191. #else
  2192. Client cli(host);
  2193. #endif
  2194. cli.set_hostname_addr_map({{host, wrong_ip}});
  2195. auto res = cli.Get("/");
  2196. ASSERT_TRUE(!res);
  2197. EXPECT_EQ(Error::Connection, res.error());
  2198. }
  2199. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2200. // A mapped value that is not an IP literal must be resolved. "localhost"
  2201. // resolves from the hosts file, so this test needs no external DNS.
  2202. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2203. auto host = "target.invalid";
  2204. Server svr;
  2205. std::string received_host;
  2206. svr.Get("/hi", [&](const Request &req, Response &res) {
  2207. received_host = req.get_header_value("Host");
  2208. res.set_content("Hello World!", "text/plain");
  2209. });
  2210. auto port = svr.bind_to_any_port(HOST);
  2211. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2212. auto se = detail::scope_exit([&] {
  2213. svr.stop();
  2214. thread.join();
  2215. ASSERT_FALSE(svr.is_running());
  2216. });
  2217. svr.wait_until_ready();
  2218. Client cli(host, port);
  2219. cli.set_hostname_addr_map({{host, HOST}});
  2220. auto res = cli.Get("/hi");
  2221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2222. EXPECT_EQ(StatusCode::OK_200, res->status);
  2223. // The mapping only redirects the connection; the identity stays host_.
  2224. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2225. }
  2226. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2227. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2228. auto host = "target.invalid";
  2229. Server svr;
  2230. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2231. res.set_content("Hello World!", "text/plain");
  2232. });
  2233. auto port = svr.bind_to_any_port("127.0.0.1");
  2234. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2235. auto se = detail::scope_exit([&] {
  2236. svr.stop();
  2237. thread.join();
  2238. ASSERT_FALSE(svr.is_running());
  2239. });
  2240. svr.wait_until_ready();
  2241. Client cli(host, port);
  2242. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2243. auto res = cli.Get("/hi");
  2244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2245. EXPECT_EQ(StatusCode::OK_200, res->status);
  2246. }
  2247. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2248. // An empty mapped value must leave host_ as the connection target. Without
  2249. // that guard the empty value would become the host argument, getaddrinfo
  2250. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2251. // loopback - silently connecting somewhere the caller never asked for.
  2252. // The server listens on loopback, so such a fallback would succeed and is
  2253. // therefore observable as a failure of this test.
  2254. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2255. Server svr;
  2256. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2257. res.set_content("Hello World!", "text/plain");
  2258. });
  2259. auto port = svr.bind_to_any_port(HOST);
  2260. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2261. auto se = detail::scope_exit([&] {
  2262. svr.stop();
  2263. thread.join();
  2264. ASSERT_FALSE(svr.is_running());
  2265. });
  2266. svr.wait_until_ready();
  2267. Client cli(blackhole, port);
  2268. cli.set_hostname_addr_map({{blackhole, ""}});
  2269. cli.set_connection_timeout(1);
  2270. auto res = cli.Get("/hi");
  2271. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2272. }
  2273. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2274. auto host = "httpbingo.org";
  2275. auto path = std::string{"/absolute-redirect/3"};
  2276. #ifdef CPPHTTPLIB_SSL_ENABLED
  2277. SSLClient cli(host);
  2278. #else
  2279. Client cli(host);
  2280. #endif
  2281. cli.set_follow_location(true);
  2282. auto res = cli.Get(path);
  2283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2284. EXPECT_EQ(StatusCode::OK_200, res->status);
  2285. }
  2286. TEST(RedirectTest, Redirect_Online) {
  2287. auto host = "httpbingo.org";
  2288. auto path = std::string{"/redirect/3"};
  2289. #ifdef CPPHTTPLIB_SSL_ENABLED
  2290. SSLClient cli(host);
  2291. #else
  2292. Client cli(host);
  2293. #endif
  2294. cli.set_follow_location(true);
  2295. auto res = cli.Get(path);
  2296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2297. EXPECT_EQ(StatusCode::OK_200, res->status);
  2298. }
  2299. TEST(RelativeRedirectTest, Redirect_Online) {
  2300. auto host = "httpbingo.org";
  2301. auto path = std::string{"/relative-redirect/3"};
  2302. #ifdef CPPHTTPLIB_SSL_ENABLED
  2303. SSLClient cli(host);
  2304. #else
  2305. Client cli(host);
  2306. #endif
  2307. cli.set_follow_location(true);
  2308. auto res = cli.Get(path);
  2309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2310. EXPECT_EQ(StatusCode::OK_200, res->status);
  2311. }
  2312. TEST(TooManyRedirectTest, Redirect_Online) {
  2313. auto host = "httpbingo.org";
  2314. auto path = std::string{"/redirect/21"};
  2315. #ifdef CPPHTTPLIB_SSL_ENABLED
  2316. SSLClient cli(host);
  2317. #else
  2318. Client cli(host);
  2319. #endif
  2320. cli.set_follow_location(true);
  2321. auto res = cli.Get(path);
  2322. ASSERT_TRUE(!res);
  2323. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2324. }
  2325. #ifdef CPPHTTPLIB_SSL_ENABLED
  2326. TEST(YahooRedirectTest, Redirect_Online) {
  2327. Client cli("yahoo.com");
  2328. auto res = cli.Get("/");
  2329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2330. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2331. cli.set_follow_location(true);
  2332. res = cli.Get("/");
  2333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2334. EXPECT_EQ(StatusCode::OK_200, res->status);
  2335. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2336. }
  2337. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2338. #define REDIR_HOST "httpbingo.org"
  2339. #define REDIR_PATH "/redirect-to"
  2340. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2341. SSLClient cli(REDIR_HOST);
  2342. cli.set_follow_location(true);
  2343. auto res =
  2344. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2346. EXPECT_EQ(StatusCode::OK_200, res->status);
  2347. }
  2348. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2349. SSLClient cli(REDIR_HOST);
  2350. cli.set_follow_location(true);
  2351. Params params;
  2352. params.emplace("url", "http://example.com");
  2353. params.emplace("status_code", "302");
  2354. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2356. EXPECT_EQ(StatusCode::OK_200, res->status);
  2357. }
  2358. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2359. SSLClient cli(REDIR_HOST);
  2360. cli.set_follow_location(true);
  2361. Params params;
  2362. params.emplace("url", "http://example.com");
  2363. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2365. EXPECT_EQ(StatusCode::OK_200, res->status);
  2366. }
  2367. TEST(UrlWithSpace, Redirect_Online) {
  2368. SSLClient cli("edge.forgecdn.net");
  2369. cli.set_follow_location(true);
  2370. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2372. EXPECT_EQ(StatusCode::OK_200, res->status);
  2373. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2374. }
  2375. #endif
  2376. #if !defined(_WIN32) && !defined(_WIN64)
  2377. TEST(ReceiveSignals, Signal) {
  2378. auto setupSignalHandlers = []() {
  2379. struct sigaction act;
  2380. sigemptyset(&act.sa_mask);
  2381. act.sa_flags = SA_SIGINFO;
  2382. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2383. switch (sig) {
  2384. case SIGINT:
  2385. default: break;
  2386. }
  2387. };
  2388. ::sigaction(SIGINT, &act, nullptr);
  2389. };
  2390. Server svr;
  2391. int port = 0;
  2392. auto thread = std::thread([&]() {
  2393. setupSignalHandlers();
  2394. port = svr.bind_to_any_port(HOST);
  2395. svr.listen_after_bind();
  2396. });
  2397. auto se = detail::scope_exit([&] {
  2398. svr.stop();
  2399. thread.join();
  2400. ASSERT_FALSE(svr.is_running());
  2401. });
  2402. svr.wait_until_ready();
  2403. ASSERT_TRUE(svr.is_running());
  2404. pthread_kill(thread.native_handle(), SIGINT);
  2405. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2406. ASSERT_TRUE(svr.is_running());
  2407. }
  2408. #endif
  2409. TEST(RedirectToDifferentPort, Redirect) {
  2410. Server svr1;
  2411. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2412. res.set_content("Hello World!", "text/plain");
  2413. });
  2414. int svr1_port = 0;
  2415. auto thread1 = std::thread([&]() {
  2416. svr1_port = svr1.bind_to_any_port(HOST);
  2417. svr1.listen_after_bind();
  2418. });
  2419. Server svr2;
  2420. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2421. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2422. });
  2423. int svr2_port = 0;
  2424. auto thread2 = std::thread([&]() {
  2425. svr2_port = svr2.bind_to_any_port(HOST);
  2426. svr2.listen_after_bind();
  2427. });
  2428. auto se = detail::scope_exit([&] {
  2429. svr2.stop();
  2430. thread2.join();
  2431. svr1.stop();
  2432. thread1.join();
  2433. ASSERT_FALSE(svr2.is_running());
  2434. ASSERT_FALSE(svr1.is_running());
  2435. });
  2436. svr1.wait_until_ready();
  2437. svr2.wait_until_ready();
  2438. Client cli("localhost", svr2_port);
  2439. cli.set_follow_location(true);
  2440. auto res = cli.Get("/2");
  2441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2442. EXPECT_EQ(StatusCode::OK_200, res->status);
  2443. EXPECT_EQ("Hello World!", res->body);
  2444. }
  2445. static void
  2446. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2447. Server svr1;
  2448. std::string captured_authorization;
  2449. svr1.Get("/target", [&](const Request &req, Response &res) {
  2450. captured_authorization = req.get_header_value("Authorization");
  2451. res.set_content("OK", "text/plain");
  2452. });
  2453. int svr1_port = 0;
  2454. auto thread1 = std::thread([&]() {
  2455. svr1_port = svr1.bind_to_any_port(HOST);
  2456. svr1.listen_after_bind();
  2457. });
  2458. Server svr2;
  2459. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2460. res.set_redirect(
  2461. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2462. });
  2463. int svr2_port = 0;
  2464. auto thread2 = std::thread([&]() {
  2465. svr2_port = svr2.bind_to_any_port(HOST);
  2466. svr2.listen_after_bind();
  2467. });
  2468. auto se = detail::scope_exit([&] {
  2469. svr2.stop();
  2470. thread2.join();
  2471. svr1.stop();
  2472. thread1.join();
  2473. ASSERT_FALSE(svr2.is_running());
  2474. ASSERT_FALSE(svr1.is_running());
  2475. });
  2476. svr1.wait_until_ready();
  2477. svr2.wait_until_ready();
  2478. Client cli("localhost", svr2_port);
  2479. cli.set_follow_location(true);
  2480. set_auth(cli);
  2481. auto res = cli.Get("/redir");
  2482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2483. EXPECT_EQ(StatusCode::OK_200, res->status);
  2484. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2485. EXPECT_TRUE(captured_authorization.empty());
  2486. }
  2487. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2488. TestDoNotForwardCredentialsOnRedirect(
  2489. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2490. }
  2491. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2492. TestDoNotForwardCredentialsOnRedirect(
  2493. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2494. }
  2495. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2496. Server svr1;
  2497. std::string captured_cookie;
  2498. bool target_hit = false;
  2499. svr1.Get("/target", [&](const Request &req, Response &res) {
  2500. captured_cookie = req.get_header_value("Cookie");
  2501. target_hit = true;
  2502. res.set_content("OK", "text/plain");
  2503. });
  2504. int svr1_port = 0;
  2505. auto thread1 = std::thread([&]() {
  2506. svr1_port = svr1.bind_to_any_port(HOST);
  2507. svr1.listen_after_bind();
  2508. });
  2509. Server svr2;
  2510. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2511. res.set_redirect(
  2512. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2513. });
  2514. int svr2_port = 0;
  2515. auto thread2 = std::thread([&]() {
  2516. svr2_port = svr2.bind_to_any_port(HOST);
  2517. svr2.listen_after_bind();
  2518. });
  2519. auto se = detail::scope_exit([&] {
  2520. svr2.stop();
  2521. thread2.join();
  2522. svr1.stop();
  2523. thread1.join();
  2524. ASSERT_FALSE(svr2.is_running());
  2525. ASSERT_FALSE(svr1.is_running());
  2526. });
  2527. svr1.wait_until_ready();
  2528. svr2.wait_until_ready();
  2529. Client cli("localhost", svr2_port);
  2530. cli.set_follow_location(true);
  2531. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2532. auto res = cli.Get("/redir", headers);
  2533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2534. EXPECT_EQ(StatusCode::OK_200, res->status);
  2535. EXPECT_TRUE(target_hit);
  2536. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2537. EXPECT_TRUE(captured_cookie.empty());
  2538. }
  2539. TEST(RedirectToSamePort, ForwardCookie) {
  2540. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2541. // header so that ordinary session flows keep working.
  2542. Server svr;
  2543. std::string captured_cookie;
  2544. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2545. res.set_redirect("/target", 302);
  2546. });
  2547. svr.Get("/target", [&](const Request &req, Response &res) {
  2548. captured_cookie = req.get_header_value("Cookie");
  2549. res.set_content("OK", "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(HOST, port);
  2560. cli.set_follow_location(true);
  2561. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2562. auto res = cli.Get("/redir", headers);
  2563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2564. EXPECT_EQ(StatusCode::OK_200, res->status);
  2565. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2566. }
  2567. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2568. Server svr;
  2569. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2570. // Port number that overflows int — should not crash
  2571. res.set_redirect("http://localhost:99999999999999999999/target");
  2572. });
  2573. auto port = svr.bind_to_any_port(HOST);
  2574. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2575. auto se = detail::scope_exit([&] {
  2576. svr.stop();
  2577. thread.join();
  2578. ASSERT_FALSE(svr.is_running());
  2579. });
  2580. svr.wait_until_ready();
  2581. Client cli(HOST, port);
  2582. cli.set_follow_location(true);
  2583. auto res = cli.Get("/redir");
  2584. // Should fail gracefully, not crash (no valid response due to bad port)
  2585. EXPECT_FALSE(res);
  2586. }
  2587. TEST(RedirectFromPageWithContent, Redirect) {
  2588. Server svr;
  2589. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2590. res.set_content("___", "text/plain");
  2591. res.set_redirect("/2");
  2592. });
  2593. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2594. res.set_content("Hello World!", "text/plain");
  2595. });
  2596. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2597. auto se = detail::scope_exit([&] {
  2598. svr.stop();
  2599. th.join();
  2600. ASSERT_FALSE(svr.is_running());
  2601. });
  2602. svr.wait_until_ready();
  2603. {
  2604. Client cli("localhost", PORT);
  2605. cli.set_follow_location(true);
  2606. std::string body;
  2607. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2608. body.append(data, data_length);
  2609. return true;
  2610. });
  2611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2612. EXPECT_EQ(StatusCode::OK_200, res->status);
  2613. EXPECT_EQ("Hello World!", body);
  2614. }
  2615. {
  2616. Client cli("localhost", PORT);
  2617. std::string body;
  2618. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2619. body.append(data, data_length);
  2620. return true;
  2621. });
  2622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2623. EXPECT_EQ(StatusCode::Found_302, res->status);
  2624. EXPECT_EQ("___", body);
  2625. }
  2626. }
  2627. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2628. Server svr;
  2629. auto port_str = std::to_string(PORT);
  2630. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2631. auto expected_host = "[::1]:" + port_str;
  2632. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2633. res.set_content("___", "text/plain");
  2634. // res.set_redirect("/2");
  2635. res.set_redirect(redirect_url);
  2636. });
  2637. svr.Get("/2", [&](const Request &req, Response &res) {
  2638. auto host_header = req.headers.find("Host");
  2639. ASSERT_TRUE(host_header != req.headers.end());
  2640. EXPECT_EQ(expected_host, host_header->second);
  2641. res.set_content("Hello World!", "text/plain");
  2642. });
  2643. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2644. auto se = detail::scope_exit([&] {
  2645. svr.stop();
  2646. th.join();
  2647. ASSERT_FALSE(svr.is_running());
  2648. });
  2649. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2650. // actually starts anything, so the condition !svr.is_running() will
  2651. // always remain true, and the loop never stops.
  2652. // This basically counts how many milliseconds have passed since the
  2653. // call to svr.listen(), and if after 5 seconds nothing started yet
  2654. // aborts the test.
  2655. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2656. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2657. ASSERT_LT(milliseconds, 5000U);
  2658. }
  2659. {
  2660. Client cli("::1", PORT);
  2661. cli.set_follow_location(true);
  2662. std::string body;
  2663. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2664. body.append(data, data_length);
  2665. return true;
  2666. });
  2667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2668. EXPECT_EQ(StatusCode::OK_200, res->status);
  2669. EXPECT_EQ("Hello World!", body);
  2670. }
  2671. {
  2672. Client cli("::1", PORT);
  2673. std::string body;
  2674. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2675. body.append(data, data_length);
  2676. return true;
  2677. });
  2678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2679. EXPECT_EQ(StatusCode::Found_302, res->status);
  2680. EXPECT_EQ("___", body);
  2681. }
  2682. }
  2683. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2684. Server svr;
  2685. svr.Get("/foo", [](const Request &req, Response &res) {
  2686. auto a = req.params.find("a");
  2687. if (a != req.params.end()) {
  2688. res.set_content((*a).second, "text/plain");
  2689. res.status = StatusCode::OK_200;
  2690. } else {
  2691. res.status = StatusCode::BadRequest_400;
  2692. }
  2693. });
  2694. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2695. auto se = detail::scope_exit([&] {
  2696. svr.stop();
  2697. thread.join();
  2698. ASSERT_FALSE(svr.is_running());
  2699. });
  2700. svr.wait_until_ready();
  2701. {
  2702. Client cli(HOST, PORT);
  2703. cli.set_path_encode(false);
  2704. auto res = cli.Get("/foo?a=explicitly+encoded");
  2705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2706. EXPECT_EQ(StatusCode::OK_200, res->status);
  2707. // This expects it back with a space, as the `+` won't have been
  2708. // url-encoded, and server-side the params get decoded turning `+`
  2709. // into spaces.
  2710. EXPECT_EQ("explicitly encoded", res->body);
  2711. }
  2712. }
  2713. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2714. // When path encoding is disabled the client must transmit the supplied
  2715. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2716. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2717. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2718. // than a space (0x20). Assert on the raw wire target to catch this.
  2719. Server svr;
  2720. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2721. svr.Get("/foo", [&](const Request &req, Response &res) {
  2722. EXPECT_EQ(expected_target, req.target);
  2723. res.status = StatusCode::OK_200;
  2724. });
  2725. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2726. auto se = detail::scope_exit([&] {
  2727. svr.stop();
  2728. thread.join();
  2729. ASSERT_FALSE(svr.is_running());
  2730. });
  2731. svr.wait_until_ready();
  2732. {
  2733. Client cli(HOST, PORT);
  2734. cli.set_path_encode(false);
  2735. auto res = cli.Get(expected_target.c_str());
  2736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2737. EXPECT_EQ(StatusCode::OK_200, res->status);
  2738. }
  2739. }
  2740. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  2741. // `open_stream()` used to skip the path encoding that the buffered send
  2742. // path applies, so the same `path` produced different bytes in the request
  2743. // line depending on which API was used. Assert the two agree.
  2744. Server svr;
  2745. std::string target;
  2746. svr.Get(".*", [&](const Request &req, Response &res) {
  2747. target = req.target;
  2748. res.status = StatusCode::OK_200;
  2749. });
  2750. auto port = svr.bind_to_any_port(HOST);
  2751. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2752. auto se = detail::scope_exit([&] {
  2753. svr.stop();
  2754. thread.join();
  2755. ASSERT_FALSE(svr.is_running());
  2756. });
  2757. svr.wait_until_ready();
  2758. struct {
  2759. const char *path;
  2760. const char *expected;
  2761. } cases[] = {
  2762. {"/a b?x=1", "/a%20b?x=1"},
  2763. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  2764. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  2765. };
  2766. for (const auto &c : cases) {
  2767. Client cli(HOST, port);
  2768. target.clear();
  2769. auto res = cli.Get(c.path);
  2770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2771. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  2772. auto buffered_target = target;
  2773. target.clear();
  2774. auto handle = cli.open_stream("GET", c.path);
  2775. EXPECT_TRUE(handle.is_valid())
  2776. << "streaming path: " << c.path << ", " << to_string(handle.error);
  2777. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  2778. }
  2779. }
  2780. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  2781. // The `set_path_encode(false)` contract — transmit the supplied target
  2782. // verbatim — must hold for the streaming API too.
  2783. Server svr;
  2784. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2785. std::string target;
  2786. svr.Get("/foo", [&](const Request &req, Response &res) {
  2787. target = req.target;
  2788. res.status = StatusCode::OK_200;
  2789. });
  2790. auto port = svr.bind_to_any_port(HOST);
  2791. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2792. auto se = detail::scope_exit([&] {
  2793. svr.stop();
  2794. thread.join();
  2795. ASSERT_FALSE(svr.is_running());
  2796. });
  2797. svr.wait_until_ready();
  2798. {
  2799. Client cli(HOST, port);
  2800. cli.set_path_encode(false);
  2801. auto handle = cli.open_stream("GET", expected_target);
  2802. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2803. EXPECT_EQ(expected_target, target);
  2804. }
  2805. }
  2806. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  2807. // With path encoding enabled a CR/LF in the target is percent-encoded
  2808. // rather than rejected, matching the buffered send path. The CR/LF guard in
  2809. // write_request_line still backstops `set_path_encode(false)`, which is
  2810. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  2811. Server svr;
  2812. // Captured before routing: the decoded path contains a newline, which a
  2813. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  2814. std::string target;
  2815. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  2816. target = req.target;
  2817. res.status = StatusCode::OK_200;
  2818. return Server::HandlerResponse::Handled;
  2819. });
  2820. auto port = svr.bind_to_any_port(HOST);
  2821. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2822. auto se = detail::scope_exit([&] {
  2823. svr.stop();
  2824. thread.join();
  2825. ASSERT_FALSE(svr.is_running());
  2826. });
  2827. svr.wait_until_ready();
  2828. {
  2829. Client cli(HOST, port);
  2830. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  2831. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2832. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  2833. }
  2834. }
  2835. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  2836. // Nothing may reach the wire: a raw CR/LF target would split the request
  2837. // line and inject headers.
  2838. Server svr;
  2839. // Pre-routing so that "not called" means nothing reached the server at all,
  2840. // rather than merely failing to match a handler pattern.
  2841. auto handler_called = false;
  2842. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  2843. handler_called = true;
  2844. res.status = StatusCode::OK_200;
  2845. return Server::HandlerResponse::Handled;
  2846. });
  2847. auto port = svr.bind_to_any_port(HOST);
  2848. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2849. auto se = detail::scope_exit([&] {
  2850. svr.stop();
  2851. thread.join();
  2852. ASSERT_FALSE(svr.is_running());
  2853. });
  2854. svr.wait_until_ready();
  2855. {
  2856. Client cli(HOST, port);
  2857. cli.set_path_encode(false);
  2858. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  2859. EXPECT_FALSE(handle.is_valid());
  2860. EXPECT_EQ(Error::Write, handle.error);
  2861. EXPECT_FALSE(handler_called);
  2862. }
  2863. }
  2864. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  2865. // Which of the two branches runs is decided by whether the query component
  2866. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  2867. // an empty query and must still fall back to building one from
  2868. // `req.params`, while a non-empty query must win over `req.params`.
  2869. Server svr;
  2870. std::string target;
  2871. svr.Get("/foo", [&](const Request &req, Response &res) {
  2872. target = req.target;
  2873. res.status = StatusCode::OK_200;
  2874. });
  2875. auto port = svr.bind_to_any_port(HOST);
  2876. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2877. auto se = detail::scope_exit([&] {
  2878. svr.stop();
  2879. thread.join();
  2880. ASSERT_FALSE(svr.is_running());
  2881. });
  2882. svr.wait_until_ready();
  2883. {
  2884. // Trailing `?` -> empty query component -> `req.params` is used.
  2885. Client cli(HOST, port);
  2886. Request req;
  2887. req.method = "GET";
  2888. req.path = "/foo?";
  2889. req.params.emplace("a", "1");
  2890. target.clear();
  2891. auto res = cli.send(req);
  2892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2893. EXPECT_EQ("/foo?a=1", target);
  2894. }
  2895. {
  2896. // Non-empty query in `req.path` -> `req.params` is not appended.
  2897. Client cli(HOST, port);
  2898. Request req;
  2899. req.method = "GET";
  2900. req.path = "/foo?b=2";
  2901. req.params.emplace("a", "1");
  2902. target.clear();
  2903. auto res = cli.send(req);
  2904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2905. EXPECT_EQ("/foo?b=2", target);
  2906. }
  2907. }
  2908. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2909. Server svr;
  2910. svr.Get("/", [](const Request &req, Response &) {
  2911. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2912. });
  2913. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2914. auto se = detail::scope_exit([&] {
  2915. svr.stop();
  2916. thread.join();
  2917. ASSERT_FALSE(svr.is_running());
  2918. });
  2919. svr.wait_until_ready();
  2920. {
  2921. Client cli(HOST, PORT);
  2922. cli.set_path_encode(false);
  2923. auto res = cli.Get("/?something=%0A");
  2924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2925. EXPECT_EQ(StatusCode::OK_200, res->status);
  2926. }
  2927. }
  2928. TEST(BindServerTest, BindDualStack) {
  2929. Server svr;
  2930. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2931. res.set_content("Hello World!", "text/plain");
  2932. });
  2933. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2934. auto se = detail::scope_exit([&] {
  2935. svr.stop();
  2936. thread.join();
  2937. ASSERT_FALSE(svr.is_running());
  2938. });
  2939. svr.wait_until_ready();
  2940. {
  2941. Client cli("127.0.0.1", PORT);
  2942. auto res = cli.Get("/1");
  2943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2944. EXPECT_EQ(StatusCode::OK_200, res->status);
  2945. EXPECT_EQ("Hello World!", res->body);
  2946. }
  2947. {
  2948. Client cli("::1", PORT);
  2949. auto res = cli.Get("/1");
  2950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2951. EXPECT_EQ(StatusCode::OK_200, res->status);
  2952. EXPECT_EQ("Hello World!", res->body);
  2953. }
  2954. }
  2955. TEST(BindServerTest, BindAndListenSeparately) {
  2956. Server svr;
  2957. int port = svr.bind_to_any_port("0.0.0.0");
  2958. ASSERT_TRUE(svr.is_valid());
  2959. ASSERT_TRUE(port > 0);
  2960. svr.stop();
  2961. }
  2962. // Reports whether anything is still listening on a loopback port. A plain
  2963. // connect() is used instead of a Client request because a socket left bound by
  2964. // mistake accepts the connection into its backlog and never answers, which
  2965. // would hang the test instead of failing it.
  2966. static bool is_loopback_port_accepting(int port) {
  2967. sockaddr_in addr{};
  2968. addr.sin_family = AF_INET;
  2969. addr.sin_port = htons(static_cast<uint16_t>(port));
  2970. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  2971. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  2972. EXPECT_NE(sock, INVALID_SOCKET);
  2973. if (sock == INVALID_SOCKET) { return false; }
  2974. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  2975. static_cast<socklen_t>(sizeof(addr)));
  2976. detail::close_socket(sock);
  2977. return ret == 0;
  2978. }
  2979. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  2980. Server svr;
  2981. auto port = svr.bind_to_any_port("127.0.0.1");
  2982. ASSERT_TRUE(port > 0);
  2983. svr.stop();
  2984. // bind_to_any_port() already called listen(2), so until stop() closed the
  2985. // descriptor the port kept accepting connections into the backlog. ASSERT
  2986. // rather than EXPECT: with the socket still open, the listen_after_bind()
  2987. // below blocks forever in the accept loop.
  2988. ASSERT_FALSE(is_loopback_port_accepting(port));
  2989. // Nothing is left to accept on, so listen_after_bind() must report failure
  2990. // instead of returning success without ever serving.
  2991. EXPECT_FALSE(svr.listen_after_bind());
  2992. // The failed listen marks the server decommissioned, so a waiter returns
  2993. // instead of spinning forever.
  2994. svr.wait_until_ready();
  2995. }
  2996. #ifdef CPPHTTPLIB_SSL_ENABLED
  2997. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2998. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2999. CLIENT_CA_CERT_DIR);
  3000. int port = svr.bind_to_any_port("0.0.0.0");
  3001. ASSERT_TRUE(svr.is_valid());
  3002. ASSERT_TRUE(port > 0);
  3003. svr.stop();
  3004. }
  3005. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3006. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3007. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3008. int port = svr.bind_to_any_port("0.0.0.0");
  3009. ASSERT_TRUE(svr.is_valid());
  3010. ASSERT_TRUE(port > 0);
  3011. svr.stop();
  3012. }
  3013. TEST(BindServerTest, UpdateCertsPem) {
  3014. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3015. int port = svr.bind_to_any_port("0.0.0.0");
  3016. ASSERT_TRUE(svr.is_valid());
  3017. ASSERT_TRUE(port > 0);
  3018. // Read PEM files
  3019. std::string cert_pem, key_pem, ca_pem;
  3020. read_file(SERVER_CERT_FILE, cert_pem);
  3021. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3022. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3023. // Update server certificates using PEM API
  3024. ASSERT_TRUE(
  3025. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3026. ASSERT_TRUE(svr.is_valid());
  3027. svr.stop();
  3028. }
  3029. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3030. // Start server with client CA (enables client auth)
  3031. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3032. ASSERT_TRUE(svr.is_valid());
  3033. bool handler_called = false;
  3034. svr.Get("/test", [&](const Request &req, Response &res) {
  3035. handler_called = true;
  3036. // Verify client certificate is present
  3037. auto cert = req.peer_cert();
  3038. EXPECT_TRUE(static_cast<bool>(cert));
  3039. res.set_content("ok", "text/plain");
  3040. });
  3041. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3042. auto se = detail::scope_exit([&] {
  3043. svr.stop();
  3044. t.join();
  3045. ASSERT_FALSE(svr.is_running());
  3046. });
  3047. svr.wait_until_ready();
  3048. // Read PEM files
  3049. std::string cert_pem, key_pem, ca_pem;
  3050. read_file(SERVER_CERT_FILE, cert_pem);
  3051. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3052. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3053. // Update server certificates and client CA using PEM API while server running
  3054. ASSERT_TRUE(
  3055. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3056. // Connect with client certificate
  3057. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3058. cli.enable_server_certificate_verification(false);
  3059. cli.set_connection_timeout(30);
  3060. auto res = cli.Get("/test");
  3061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3062. ASSERT_EQ(StatusCode::OK_200, res->status);
  3063. ASSERT_TRUE(handler_called);
  3064. EXPECT_EQ("ok", res->body);
  3065. }
  3066. #endif
  3067. TEST(ErrorHandlerTest, ContentLength) {
  3068. Server svr;
  3069. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3070. res.status = StatusCode::OK_200;
  3071. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3072. "text/html"); // <= Content-Length still 13
  3073. });
  3074. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3075. res.set_content("Hello World!\n", "text/plain");
  3076. res.status = 524;
  3077. });
  3078. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3079. auto se = detail::scope_exit([&] {
  3080. svr.stop();
  3081. thread.join();
  3082. ASSERT_FALSE(svr.is_running());
  3083. });
  3084. svr.wait_until_ready();
  3085. {
  3086. Client cli(HOST, PORT);
  3087. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3089. EXPECT_EQ(StatusCode::OK_200, res->status);
  3090. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3091. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3092. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3093. }
  3094. }
  3095. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3096. TEST(ExceptionTest, WithoutExceptionHandler) {
  3097. Server svr;
  3098. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3099. throw std::runtime_error("exception...");
  3100. });
  3101. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3102. throw std::runtime_error("exception\r\n...");
  3103. });
  3104. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3105. auto se = detail::scope_exit([&] {
  3106. svr.stop();
  3107. listen_thread.join();
  3108. ASSERT_FALSE(svr.is_running());
  3109. });
  3110. svr.wait_until_ready();
  3111. Client cli("localhost", PORT);
  3112. {
  3113. auto res = cli.Get("/exception");
  3114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3115. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3116. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3117. }
  3118. {
  3119. auto res = cli.Get("/unknown");
  3120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3121. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3122. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3123. }
  3124. }
  3125. TEST(ExceptionTest, WithExceptionHandler) {
  3126. Server svr;
  3127. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3128. std::exception_ptr ep) {
  3129. EXPECT_FALSE(ep == nullptr);
  3130. try {
  3131. std::rethrow_exception(ep);
  3132. } catch (std::exception &e) {
  3133. EXPECT_EQ("abc", std::string(e.what()));
  3134. } catch (...) {}
  3135. res.status = StatusCode::InternalServerError_500;
  3136. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3137. "text/html"); // <= Content-Length still 13 at this point
  3138. });
  3139. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3140. res.set_content("Hello World!\n", "text/plain");
  3141. throw std::runtime_error("abc");
  3142. });
  3143. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3144. auto se = detail::scope_exit([&] {
  3145. svr.stop();
  3146. thread.join();
  3147. ASSERT_FALSE(svr.is_running());
  3148. });
  3149. svr.wait_until_ready();
  3150. for (size_t i = 0; i < 10; i++) {
  3151. Client cli(HOST, PORT);
  3152. for (size_t j = 0; j < 100; j++) {
  3153. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3155. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3156. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3157. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3158. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3159. }
  3160. cli.set_keep_alive(true);
  3161. for (size_t j = 0; j < 100; j++) {
  3162. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3164. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3165. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3166. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3167. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3168. }
  3169. }
  3170. }
  3171. TEST(ExceptionTest, AndErrorHandler) {
  3172. Server svr;
  3173. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3174. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3175. });
  3176. svr.set_exception_handler(
  3177. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3178. EXPECT_FALSE(ep == nullptr);
  3179. try {
  3180. std::rethrow_exception(ep);
  3181. } catch (std::exception &e) {
  3182. res.set_content(e.what(), "text/html");
  3183. } catch (...) {}
  3184. res.status = StatusCode::InternalServerError_500;
  3185. });
  3186. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3187. throw std::runtime_error("EXCEPTION");
  3188. });
  3189. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3190. res.set_content("ERROR", "text/html");
  3191. res.status = StatusCode::InternalServerError_500;
  3192. });
  3193. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3194. auto se = detail::scope_exit([&] {
  3195. svr.stop();
  3196. thread.join();
  3197. ASSERT_FALSE(svr.is_running());
  3198. });
  3199. svr.wait_until_ready();
  3200. Client cli(HOST, PORT);
  3201. {
  3202. auto res = cli.Get("/exception");
  3203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3204. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3205. EXPECT_EQ("EXCEPTION", res->body);
  3206. }
  3207. {
  3208. auto res = cli.Get("/error");
  3209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3210. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3211. EXPECT_EQ("ERROR", res->body);
  3212. }
  3213. {
  3214. auto res = cli.Get("/invalid");
  3215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3216. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3217. EXPECT_EQ("NOT_FOUND", res->body);
  3218. }
  3219. }
  3220. #endif
  3221. TEST(NoContentTest, ContentLength) {
  3222. Server svr;
  3223. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3224. res.status = StatusCode::NoContent_204;
  3225. });
  3226. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3227. auto se = detail::scope_exit([&] {
  3228. svr.stop();
  3229. thread.join();
  3230. ASSERT_FALSE(svr.is_running());
  3231. });
  3232. svr.wait_until_ready();
  3233. {
  3234. Client cli(HOST, PORT);
  3235. auto res = cli.Get("/hi");
  3236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3237. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3238. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3239. }
  3240. }
  3241. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3242. #ifdef CPPHTTPLIB_SSL_ENABLED
  3243. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3244. ASSERT_TRUE(svr.is_valid());
  3245. #else
  3246. Server svr;
  3247. #endif
  3248. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3249. if (req.path == "/routing_handler") {
  3250. res.set_header("PRE_ROUTING", "on");
  3251. res.set_content("Routing Handler", "text/plain");
  3252. return httplib::Server::HandlerResponse::Handled;
  3253. }
  3254. return httplib::Server::HandlerResponse::Unhandled;
  3255. });
  3256. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3257. res.set_content("Error", "text/html");
  3258. });
  3259. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3260. if (req.path == "/routing_handler") {
  3261. res.set_header("POST_ROUTING", "on");
  3262. }
  3263. });
  3264. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3265. res.set_content("Hello World!\n", "text/plain");
  3266. });
  3267. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3268. auto se = detail::scope_exit([&] {
  3269. svr.stop();
  3270. thread.join();
  3271. ASSERT_FALSE(svr.is_running());
  3272. });
  3273. svr.wait_until_ready();
  3274. {
  3275. #ifdef CPPHTTPLIB_SSL_ENABLED
  3276. SSLClient cli(HOST, PORT);
  3277. cli.enable_server_certificate_verification(false);
  3278. #else
  3279. Client cli(HOST, PORT);
  3280. #endif
  3281. auto res = cli.Get("/routing_handler");
  3282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3283. EXPECT_EQ(StatusCode::OK_200, res->status);
  3284. EXPECT_EQ("Routing Handler", res->body);
  3285. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3286. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3287. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3288. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3289. }
  3290. {
  3291. #ifdef CPPHTTPLIB_SSL_ENABLED
  3292. SSLClient cli(HOST, PORT);
  3293. cli.enable_server_certificate_verification(false);
  3294. #else
  3295. Client cli(HOST, PORT);
  3296. #endif
  3297. auto res = cli.Get("/hi");
  3298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3299. EXPECT_EQ(StatusCode::OK_200, res->status);
  3300. EXPECT_EQ("Hello World!\n", res->body);
  3301. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3302. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3303. }
  3304. {
  3305. #ifdef CPPHTTPLIB_SSL_ENABLED
  3306. SSLClient cli(HOST, PORT);
  3307. cli.enable_server_certificate_verification(false);
  3308. #else
  3309. Client cli(HOST, PORT);
  3310. #endif
  3311. auto res = cli.Get("/aaa");
  3312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3313. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3314. EXPECT_EQ("Error", res->body);
  3315. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3316. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3317. }
  3318. }
  3319. TEST(RequestHandlerTest, PreRequestHandler) {
  3320. auto route_path = "/user/:user";
  3321. Server svr;
  3322. svr.Get("/hi", [](const Request &, Response &res) {
  3323. res.set_content("hi", "text/plain");
  3324. });
  3325. svr.Get(route_path, [](const Request &req, Response &res) {
  3326. res.set_content(req.path_params.at("user"), "text/plain");
  3327. });
  3328. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3329. if (req.matched_route == route_path) {
  3330. auto user = req.path_params.at("user");
  3331. if (user != "john") {
  3332. res.status = StatusCode::Forbidden_403;
  3333. res.set_content("error", "text/html");
  3334. return Server::HandlerResponse::Handled;
  3335. }
  3336. }
  3337. return Server::HandlerResponse::Unhandled;
  3338. });
  3339. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3340. auto se = detail::scope_exit([&] {
  3341. svr.stop();
  3342. thread.join();
  3343. ASSERT_FALSE(svr.is_running());
  3344. });
  3345. svr.wait_until_ready();
  3346. Client cli(HOST, PORT);
  3347. {
  3348. auto res = cli.Get("/hi");
  3349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3350. EXPECT_EQ(StatusCode::OK_200, res->status);
  3351. EXPECT_EQ("hi", res->body);
  3352. }
  3353. {
  3354. auto res = cli.Get("/user/john");
  3355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3356. EXPECT_EQ(StatusCode::OK_200, res->status);
  3357. EXPECT_EQ("john", res->body);
  3358. }
  3359. {
  3360. auto res = cli.Get("/user/invalid-user");
  3361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3362. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3363. EXPECT_EQ("error", res->body);
  3364. }
  3365. }
  3366. // The pre-request handler must run before the request body is read, so a
  3367. // rejected request never forces the server to buffer a (potentially large)
  3368. // body. Here the posted body is larger than the payload limit: if the body
  3369. // were read first the server would answer 413, but because the pre-request
  3370. // handler runs first it answers 403 and the body is never read.
  3371. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3372. Server svr;
  3373. svr.set_payload_max_length(8);
  3374. auto handler_ran = false;
  3375. svr.Post("/reject", [&](const Request &req, Response &res) {
  3376. handler_ran = true;
  3377. res.set_content(req.body, "text/plain");
  3378. });
  3379. svr.Post("/accept", [](const Request &req, Response &res) {
  3380. res.set_content(req.body, "text/plain");
  3381. });
  3382. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3383. if (req.matched_route == "/reject") {
  3384. res.status = StatusCode::Forbidden_403;
  3385. res.set_content("denied", "text/plain");
  3386. return Server::HandlerResponse::Handled;
  3387. }
  3388. return Server::HandlerResponse::Unhandled;
  3389. });
  3390. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3391. auto se = detail::scope_exit([&] {
  3392. svr.stop();
  3393. thread.join();
  3394. ASSERT_FALSE(svr.is_running());
  3395. });
  3396. svr.wait_until_ready();
  3397. Client cli(HOST, PORT);
  3398. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3399. // rejects with 403 before the body is read, so 413 is never reached.
  3400. {
  3401. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3403. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3404. EXPECT_EQ("denied", res->body);
  3405. EXPECT_FALSE(handler_ran);
  3406. }
  3407. // An approved route still reads the body and enforces the payload limit.
  3408. {
  3409. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3411. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3412. }
  3413. }
  3414. TEST(UserDataTest, BasicOperations) {
  3415. httplib::UserData ud;
  3416. // Initially empty
  3417. EXPECT_FALSE(ud.has("key"));
  3418. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3419. // set and get
  3420. ud.set("key", 42);
  3421. EXPECT_TRUE(ud.has("key"));
  3422. auto *p = ud.get<int>("key");
  3423. ASSERT_NE(nullptr, p);
  3424. EXPECT_EQ(42, *p);
  3425. // Type mismatch → nullptr
  3426. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3427. // Overwrite with different type
  3428. ud.set("key", std::string("hello"));
  3429. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3430. auto *s = ud.get<std::string>("key");
  3431. ASSERT_NE(nullptr, s);
  3432. EXPECT_EQ("hello", *s);
  3433. // erase
  3434. ud.erase("key");
  3435. EXPECT_FALSE(ud.has("key"));
  3436. // clear
  3437. ud.set("a", 1);
  3438. ud.set("b", 2);
  3439. ud.clear();
  3440. EXPECT_FALSE(ud.has("a"));
  3441. EXPECT_FALSE(ud.has("b"));
  3442. }
  3443. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3444. struct AuthCtx {
  3445. std::string user_id;
  3446. };
  3447. Server svr;
  3448. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3449. res.user_data.set("auth", AuthCtx{"alice"});
  3450. return Server::HandlerResponse::Unhandled;
  3451. });
  3452. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3453. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3454. ASSERT_NE(nullptr, ctx);
  3455. res.set_content("Hello " + ctx->user_id, "text/plain");
  3456. });
  3457. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3458. auto se = detail::scope_exit([&] {
  3459. svr.stop();
  3460. thread.join();
  3461. ASSERT_FALSE(svr.is_running());
  3462. });
  3463. svr.wait_until_ready();
  3464. Client cli(HOST, PORT);
  3465. auto res = cli.Get("/me");
  3466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3467. EXPECT_EQ(StatusCode::OK_200, res->status);
  3468. EXPECT_EQ("Hello alice", res->body);
  3469. }
  3470. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3471. struct RoleCtx {
  3472. std::string role;
  3473. };
  3474. Server svr;
  3475. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3476. res.user_data.set("role", RoleCtx{"admin"});
  3477. return Server::HandlerResponse::Unhandled;
  3478. });
  3479. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3480. auto *ctx = res.user_data.get<RoleCtx>("role");
  3481. ASSERT_NE(nullptr, ctx);
  3482. res.set_content(ctx->role, "text/plain");
  3483. });
  3484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3485. auto se = detail::scope_exit([&] {
  3486. svr.stop();
  3487. thread.join();
  3488. ASSERT_FALSE(svr.is_running());
  3489. });
  3490. svr.wait_until_ready();
  3491. Client cli(HOST, PORT);
  3492. auto res = cli.Get("/role");
  3493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3494. EXPECT_EQ(StatusCode::OK_200, res->status);
  3495. EXPECT_EQ("admin", res->body);
  3496. }
  3497. TEST(InvalidFormatTest, StatusCode) {
  3498. Server svr;
  3499. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3500. res.set_content("Hello World!\n", "text/plain");
  3501. res.status = 9999; // Status should be a three-digit code...
  3502. });
  3503. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3504. auto se = detail::scope_exit([&] {
  3505. svr.stop();
  3506. thread.join();
  3507. ASSERT_FALSE(svr.is_running());
  3508. });
  3509. svr.wait_until_ready();
  3510. {
  3511. Client cli(HOST, PORT);
  3512. auto res = cli.Get("/hi");
  3513. ASSERT_FALSE(res);
  3514. }
  3515. }
  3516. TEST(URLFragmentTest, WithFragment) {
  3517. Server svr;
  3518. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3519. EXPECT_TRUE(req.target == "/hi");
  3520. });
  3521. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3522. auto se = detail::scope_exit([&] {
  3523. svr.stop();
  3524. thread.join();
  3525. ASSERT_FALSE(svr.is_running());
  3526. });
  3527. svr.wait_until_ready();
  3528. {
  3529. Client cli(HOST, PORT);
  3530. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3531. EXPECT_TRUE(res);
  3532. EXPECT_EQ(StatusCode::OK_200, res->status);
  3533. res = cli.Get("/hi%23key1=val1=key2=val2");
  3534. EXPECT_TRUE(res);
  3535. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3536. }
  3537. }
  3538. TEST(HeaderWriter, SetHeaderWriter) {
  3539. Server svr;
  3540. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3541. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3542. return detail::write_headers(strm, hdrs);
  3543. });
  3544. svr.Get("/hi", [](const Request &req, Response &res) {
  3545. auto it = req.headers.find("CustomClientHeader");
  3546. EXPECT_TRUE(it != req.headers.end());
  3547. EXPECT_EQ(it->second, "CustomClientValue");
  3548. res.set_content("Hello World!\n", "text/plain");
  3549. });
  3550. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3551. auto se = detail::scope_exit([&] {
  3552. svr.stop();
  3553. thread.join();
  3554. ASSERT_FALSE(svr.is_running());
  3555. });
  3556. svr.wait_until_ready();
  3557. {
  3558. Client cli(HOST, PORT);
  3559. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3560. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3561. return detail::write_headers(strm, hdrs);
  3562. });
  3563. auto res = cli.Get("/hi");
  3564. EXPECT_TRUE(res);
  3565. EXPECT_EQ(StatusCode::OK_200, res->status);
  3566. auto it = res->headers.find("CustomServerHeader");
  3567. EXPECT_TRUE(it != res->headers.end());
  3568. EXPECT_EQ(it->second, "CustomServerValue");
  3569. }
  3570. }
  3571. class ServerTest : public ::testing::Test {
  3572. protected:
  3573. ServerTest()
  3574. : cli_(HOST, PORT)
  3575. #ifdef CPPHTTPLIB_SSL_ENABLED
  3576. ,
  3577. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3578. #endif
  3579. {
  3580. #ifdef CPPHTTPLIB_SSL_ENABLED
  3581. cli_.enable_server_certificate_verification(false);
  3582. #endif
  3583. // Allow LARGE_DATA (100MB) responses
  3584. cli_.set_payload_max_length(200 * 1024 * 1024);
  3585. }
  3586. virtual void SetUp() {
  3587. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3588. svr_.set_payload_max_length(200 * 1024 * 1024);
  3589. svr_.set_mount_point("/", "./www");
  3590. svr_.set_mount_point("/mount", "./www2");
  3591. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3592. svr_.Get("/hi",
  3593. [&](const Request & /*req*/, Response &res) {
  3594. res.set_content("Hello World!", "text/plain");
  3595. })
  3596. .Get("/file_content",
  3597. [&](const Request & /*req*/, Response &res) {
  3598. res.set_file_content("./www/dir/test.html");
  3599. })
  3600. .Get("/file_content_with_content_type",
  3601. [&](const Request & /*req*/, Response &res) {
  3602. res.set_file_content("./www/file", "text/plain");
  3603. })
  3604. .Get("/invalid_file_content",
  3605. [&](const Request & /*req*/, Response &res) {
  3606. res.set_file_content("./www/dir/invalid_file_path");
  3607. })
  3608. .Get("/http_response_splitting",
  3609. [&](const Request & /*req*/, Response &res) {
  3610. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3611. EXPECT_EQ(0U, res.headers.size());
  3612. EXPECT_FALSE(res.has_header("a"));
  3613. res.set_header("a", "1\nSet-Cookie: a=1");
  3614. EXPECT_EQ(0U, res.headers.size());
  3615. EXPECT_FALSE(res.has_header("a"));
  3616. res.set_header("a", "1\rSet-Cookie: a=1");
  3617. EXPECT_EQ(0U, res.headers.size());
  3618. EXPECT_FALSE(res.has_header("a"));
  3619. res.set_header("a\r\nb", "0");
  3620. EXPECT_EQ(0U, res.headers.size());
  3621. EXPECT_FALSE(res.has_header("a"));
  3622. res.set_header("a\rb", "0");
  3623. EXPECT_EQ(0U, res.headers.size());
  3624. EXPECT_FALSE(res.has_header("a"));
  3625. res.set_header("a\nb", "0");
  3626. EXPECT_EQ(0U, res.headers.size());
  3627. EXPECT_FALSE(res.has_header("a"));
  3628. res.set_redirect("1\r\nSet-Cookie: a=1");
  3629. EXPECT_EQ(0U, res.headers.size());
  3630. EXPECT_FALSE(res.has_header("Location"));
  3631. })
  3632. .Get("/slow",
  3633. [&](const Request & /*req*/, Response &res) {
  3634. std::this_thread::sleep_for(std::chrono::seconds(4));
  3635. res.set_content("slow", "text/plain");
  3636. })
  3637. #if 0
  3638. .Post("/slowpost",
  3639. [&](const Request & /*req*/, Response &res) {
  3640. std::this_thread::sleep_for(std::chrono::seconds(2));
  3641. res.set_content("slow", "text/plain");
  3642. })
  3643. #endif
  3644. .Get("/remote_addr",
  3645. [&](const Request &req, Response &res) {
  3646. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3647. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3648. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3649. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3650. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3651. #endif
  3652. res.set_content(req.remote_addr, "text/plain");
  3653. })
  3654. .Get("/local_addr",
  3655. [&](const Request &req, Response &res) {
  3656. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3657. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3658. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3659. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3660. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3661. #endif
  3662. auto local_addr = req.local_addr;
  3663. auto local_port = std::to_string(req.local_port);
  3664. res.set_content(local_addr.append(":").append(local_port),
  3665. "text/plain");
  3666. })
  3667. .Get("/endwith%",
  3668. [&](const Request & /*req*/, Response &res) {
  3669. res.set_content("Hello World!", "text/plain");
  3670. })
  3671. .Get("/a\\+\\+b",
  3672. [&](const Request &req, Response &res) {
  3673. ASSERT_TRUE(req.has_param("a +b"));
  3674. auto val = req.get_param_value("a +b");
  3675. res.set_content(val, "text/plain");
  3676. })
  3677. .Get("/", [&](const Request & /*req*/,
  3678. Response &res) { res.set_redirect("/hi"); })
  3679. .Post("/1",
  3680. [](const Request & /*req*/, Response &res) {
  3681. res.set_redirect("/2", StatusCode::SeeOther_303);
  3682. })
  3683. .Get("/2",
  3684. [](const Request & /*req*/, Response &res) {
  3685. res.set_content("redirected.", "text/plain");
  3686. res.status = StatusCode::OK_200;
  3687. })
  3688. .Post("/person",
  3689. [&](const Request &req, Response &res) {
  3690. if (req.has_param("name") && req.has_param("note")) {
  3691. persons_[req.get_param_value("name")] =
  3692. req.get_param_value("note");
  3693. } else {
  3694. res.status = StatusCode::BadRequest_400;
  3695. }
  3696. })
  3697. .Put("/person",
  3698. [&](const Request &req, Response &res) {
  3699. if (req.has_param("name") && req.has_param("note")) {
  3700. persons_[req.get_param_value("name")] =
  3701. req.get_param_value("note");
  3702. } else {
  3703. res.status = StatusCode::BadRequest_400;
  3704. }
  3705. })
  3706. .Get("/person/(.*)",
  3707. [&](const Request &req, Response &res) {
  3708. string name = req.matches[1];
  3709. if (persons_.find(name) != persons_.end()) {
  3710. auto note = persons_[name];
  3711. res.set_content(note, "text/plain");
  3712. } else {
  3713. res.status = StatusCode::NotFound_404;
  3714. }
  3715. })
  3716. .Delete("/person",
  3717. [&](const Request &req, Response &res) {
  3718. if (req.has_param("name")) {
  3719. string name = req.get_param_value("name");
  3720. if (persons_.find(name) != persons_.end()) {
  3721. persons_.erase(name);
  3722. res.set_content("DELETED", "text/plain");
  3723. } else {
  3724. res.status = StatusCode::NotFound_404;
  3725. }
  3726. } else {
  3727. res.status = StatusCode::BadRequest_400;
  3728. }
  3729. })
  3730. .Post("/x-www-form-urlencoded-json",
  3731. [&](const Request &req, Response &res) {
  3732. auto json = req.get_param_value("json");
  3733. ASSERT_EQ(JSON_DATA, json);
  3734. res.set_content(json, "appliation/json");
  3735. res.status = StatusCode::OK_200;
  3736. })
  3737. .Get("/streamed-chunked",
  3738. [&](const Request & /*req*/, Response &res) {
  3739. res.set_chunked_content_provider(
  3740. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3741. sink.os << "123";
  3742. sink.os << "456";
  3743. sink.os << "789";
  3744. sink.done();
  3745. return true;
  3746. });
  3747. })
  3748. .Get("/streamed-chunked-with-prohibited-trailer",
  3749. [&](const Request & /*req*/, Response &res) {
  3750. auto i = new int(0);
  3751. // Declare both a prohibited trailer (Content-Length) and an
  3752. // allowed one
  3753. res.set_header("Trailer", "Content-Length, X-Allowed");
  3754. res.set_chunked_content_provider(
  3755. "text/plain",
  3756. [i](size_t /*offset*/, DataSink &sink) {
  3757. switch (*i) {
  3758. case 0: sink.os << "123"; break;
  3759. case 1: sink.os << "456"; break;
  3760. case 2: sink.os << "789"; break;
  3761. case 3: {
  3762. sink.done_with_trailer(
  3763. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3764. } break;
  3765. }
  3766. (*i)++;
  3767. return true;
  3768. },
  3769. [i](bool success) {
  3770. EXPECT_TRUE(success);
  3771. delete i;
  3772. });
  3773. })
  3774. .Get("/streamed-chunked2",
  3775. [&](const Request & /*req*/, Response &res) {
  3776. auto i = new int(0);
  3777. res.set_chunked_content_provider(
  3778. "text/plain",
  3779. [i](size_t /*offset*/, DataSink &sink) {
  3780. switch (*i) {
  3781. case 0: sink.os << "123"; break;
  3782. case 1: sink.os << "456"; break;
  3783. case 2: sink.os << "789"; break;
  3784. case 3: sink.done(); break;
  3785. }
  3786. (*i)++;
  3787. return true;
  3788. },
  3789. [i](bool success) {
  3790. EXPECT_TRUE(success);
  3791. delete i;
  3792. });
  3793. })
  3794. .Get("/streamed-chunked-with-trailer",
  3795. [&](const Request & /*req*/, Response &res) {
  3796. auto i = new int(0);
  3797. res.set_header("Trailer", "Dummy1, Dummy2");
  3798. res.set_chunked_content_provider(
  3799. "text/plain",
  3800. [i](size_t /*offset*/, DataSink &sink) {
  3801. switch (*i) {
  3802. case 0: sink.os << "123"; break;
  3803. case 1: sink.os << "456"; break;
  3804. case 2: sink.os << "789"; break;
  3805. case 3: {
  3806. sink.done_with_trailer(
  3807. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3808. } break;
  3809. }
  3810. (*i)++;
  3811. return true;
  3812. },
  3813. [i](bool success) {
  3814. EXPECT_TRUE(success);
  3815. delete i;
  3816. });
  3817. })
  3818. .Get("/streamed",
  3819. [&](const Request & /*req*/, Response &res) {
  3820. res.set_content_provider(
  3821. 6, "text/plain",
  3822. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3823. sink.os << (offset < 3 ? "a" : "b");
  3824. return true;
  3825. });
  3826. })
  3827. .Get("/streamed-without-length",
  3828. [&](const Request & /*req*/, Response &res) {
  3829. auto data = new std::string("abcdefg");
  3830. res.set_content_provider(
  3831. "text/plain",
  3832. [data](size_t offset, DataSink &sink) {
  3833. if (offset < data->size()) {
  3834. sink.os << data->substr(offset);
  3835. }
  3836. sink.done();
  3837. return true;
  3838. },
  3839. [data](bool success) {
  3840. EXPECT_TRUE(success);
  3841. delete data;
  3842. });
  3843. })
  3844. .Get("/streamed-with-range",
  3845. [&](const Request &req, Response &res) {
  3846. auto data = new std::string("abcdefg");
  3847. // An explicit status keeps the server from picking the 206 it
  3848. // would otherwise choose for a ranged request, so the response
  3849. // is not a partial representation.
  3850. auto status = req.get_param_value("status");
  3851. if (status == "200") {
  3852. res.status = StatusCode::OK_200;
  3853. } else if (status == "403") {
  3854. res.status = StatusCode::Forbidden_403;
  3855. }
  3856. res.set_content_provider(
  3857. data->size(), "text/plain",
  3858. [data](size_t offset, size_t length, DataSink &sink) {
  3859. size_t DATA_CHUNK_SIZE = 4;
  3860. const auto &d = *data;
  3861. auto out_len =
  3862. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3863. auto ret =
  3864. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3865. EXPECT_TRUE(ret);
  3866. return true;
  3867. },
  3868. [data, &req](bool success) {
  3869. EXPECT_EQ(success, !req.has_param("error"));
  3870. delete data;
  3871. });
  3872. })
  3873. .Get("/streamed-cancel",
  3874. [&](const Request & /*req*/, Response &res) {
  3875. res.set_content_provider(
  3876. size_t(-1), "text/plain",
  3877. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3878. sink.os << "data_chunk";
  3879. return true;
  3880. });
  3881. })
  3882. .Get("/regex-with-delimiter",
  3883. [&](const Request &req, Response & /*res*/) {
  3884. ASSERT_TRUE(req.has_param("key"));
  3885. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3886. })
  3887. .Get("/with-range",
  3888. [&](const Request & /*req*/, Response &res) {
  3889. res.set_content("abcdefg", "text/plain");
  3890. })
  3891. .Get("/test-start-time",
  3892. [&](const Request &req, Response & /*res*/) {
  3893. EXPECT_NE(req.start_time_,
  3894. std::chrono::steady_clock::time_point::min());
  3895. })
  3896. .Get("/with-range-customized-response",
  3897. [&](const Request & /*req*/, Response &res) {
  3898. res.status = StatusCode::BadRequest_400;
  3899. res.set_content(JSON_DATA, "application/json");
  3900. })
  3901. .Post("/chunked",
  3902. [&](const Request &req, Response & /*res*/) {
  3903. EXPECT_EQ(req.body, "dechunked post body");
  3904. })
  3905. .Post("/large-chunked",
  3906. [&](const Request &req, Response & /*res*/) {
  3907. std::string expected(6 * 30 * 1024u, 'a');
  3908. EXPECT_EQ(req.body, expected);
  3909. })
  3910. .Post("/multipart",
  3911. [&](const Request &req, Response & /*res*/) {
  3912. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3913. req.form.get_field_count("text2") +
  3914. req.form.get_field_count("file3") +
  3915. req.form.get_field_count("file4"));
  3916. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3917. req.form.get_file_count("file2"));
  3918. ASSERT_TRUE(!req.form.has_file("???"));
  3919. ASSERT_TRUE(!req.form.has_field("???"));
  3920. ASSERT_TRUE(req.body.empty());
  3921. {
  3922. const auto &text = req.form.get_field("text1");
  3923. EXPECT_EQ("text default", text);
  3924. }
  3925. {
  3926. const auto &text = req.form.get_field("text2");
  3927. EXPECT_EQ("aωb", text);
  3928. }
  3929. {
  3930. const auto &file = req.form.get_file("file1");
  3931. EXPECT_EQ("hello.txt", file.filename);
  3932. EXPECT_EQ("text/plain", file.content_type);
  3933. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3934. }
  3935. {
  3936. const auto &file = req.form.get_file("file2");
  3937. EXPECT_EQ("world.json", file.filename);
  3938. EXPECT_EQ("application/json", file.content_type);
  3939. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3940. }
  3941. {
  3942. const auto &text = req.form.get_field("file3");
  3943. EXPECT_EQ(0u, text.size());
  3944. }
  3945. {
  3946. const auto &text = req.form.get_field("file4");
  3947. EXPECT_EQ(0u, text.size());
  3948. }
  3949. })
  3950. .Post("/multipart/multi_file_values",
  3951. [&](const Request &req, Response & /*res*/) {
  3952. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3953. req.form.get_field_count("multi_text1"));
  3954. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3955. ASSERT_TRUE(!req.form.has_file("???"));
  3956. ASSERT_TRUE(!req.form.has_field("???"));
  3957. ASSERT_TRUE(req.body.empty());
  3958. {
  3959. const auto &text = req.form.get_field("text");
  3960. EXPECT_EQ("default text", text);
  3961. }
  3962. {
  3963. const auto &text1_values = req.form.get_fields("multi_text1");
  3964. EXPECT_EQ(2u, text1_values.size());
  3965. EXPECT_EQ("aaaaa", text1_values[0]);
  3966. EXPECT_EQ("bbbbb", text1_values[1]);
  3967. }
  3968. {
  3969. const auto &file1_values = req.form.get_files("multi_file1");
  3970. EXPECT_EQ(2u, file1_values.size());
  3971. auto file1 = file1_values[0];
  3972. EXPECT_EQ(file1.filename, "hello.txt");
  3973. EXPECT_EQ(file1.content_type, "text/plain");
  3974. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3975. auto file2 = file1_values[1];
  3976. EXPECT_EQ(file2.filename, "world.json");
  3977. EXPECT_EQ(file2.content_type, "application/json");
  3978. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3979. }
  3980. })
  3981. .Post("/empty",
  3982. [&](const Request &req, Response &res) {
  3983. EXPECT_EQ(req.body, "");
  3984. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3985. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3986. res.set_content("empty", "text/plain");
  3987. })
  3988. .Post("/empty-no-content-type",
  3989. [&](const Request &req, Response &res) {
  3990. EXPECT_EQ(req.body, "");
  3991. EXPECT_FALSE(req.has_header("Content-Type"));
  3992. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3993. res.set_content("empty-no-content-type", "text/plain");
  3994. })
  3995. .Post("/path-only",
  3996. [&](const Request &req, Response &res) {
  3997. EXPECT_EQ(req.body, "");
  3998. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3999. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4000. res.set_content("path-only", "text/plain");
  4001. })
  4002. .Post("/path-headers-only",
  4003. [&](const Request &req, Response &res) {
  4004. EXPECT_EQ(req.body, "");
  4005. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4006. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4007. EXPECT_EQ("world", req.get_header_value("hello"));
  4008. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4009. res.set_content("path-headers-only", "text/plain");
  4010. })
  4011. .Post("/post-large",
  4012. [&](const Request &req, Response &res) {
  4013. EXPECT_EQ(req.body, LARGE_DATA);
  4014. res.set_content(req.body, "text/plain");
  4015. })
  4016. .Post("/post-loopback",
  4017. [&](const Request &, Response &res,
  4018. ContentReader const &content_reader) {
  4019. std::string body;
  4020. content_reader([&](const char *data, size_t data_length) {
  4021. body.append(data, data_length);
  4022. return true;
  4023. });
  4024. res.set_content(body, "text/plain");
  4025. })
  4026. .Put("/put-loopback",
  4027. [&](const Request &, Response &res,
  4028. ContentReader const &content_reader) {
  4029. std::string body;
  4030. content_reader([&](const char *data, size_t data_length) {
  4031. body.append(data, data_length);
  4032. return true;
  4033. });
  4034. res.set_content(body, "text/plain");
  4035. })
  4036. .Patch("/patch-loopback",
  4037. [&](const Request &, Response &res,
  4038. ContentReader const &content_reader) {
  4039. std::string body;
  4040. content_reader([&](const char *data, size_t data_length) {
  4041. body.append(data, data_length);
  4042. return true;
  4043. });
  4044. res.set_content(body, "text/plain");
  4045. })
  4046. .Put("/empty-no-content-type",
  4047. [&](const Request &req, Response &res) {
  4048. EXPECT_EQ(req.body, "");
  4049. EXPECT_FALSE(req.has_header("Content-Type"));
  4050. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4051. res.set_content("empty-no-content-type", "text/plain");
  4052. })
  4053. .Put("/put",
  4054. [&](const Request &req, Response &res) {
  4055. EXPECT_EQ(req.body, "PUT");
  4056. res.set_content(req.body, "text/plain");
  4057. })
  4058. .Put("/put-large",
  4059. [&](const Request &req, Response &res) {
  4060. EXPECT_EQ(req.body, LARGE_DATA);
  4061. res.set_content(req.body, "text/plain");
  4062. })
  4063. .Patch("/patch",
  4064. [&](const Request &req, Response &res) {
  4065. EXPECT_EQ(req.body, "PATCH");
  4066. res.set_content(req.body, "text/plain");
  4067. })
  4068. .Delete("/delete",
  4069. [&](const Request & /*req*/, Response &res) {
  4070. res.set_content("DELETE", "text/plain");
  4071. })
  4072. .Delete("/delete-body",
  4073. [&](const Request &req, Response &res) {
  4074. EXPECT_EQ(req.body, "content");
  4075. res.set_content(req.body, "text/plain");
  4076. })
  4077. .Options(R"(\*)",
  4078. [&](const Request & /*req*/, Response &res) {
  4079. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4080. })
  4081. .Get("/request-target",
  4082. [&](const Request &req, Response & /*res*/) {
  4083. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4084. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4085. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4086. })
  4087. .Get("/long-query-value",
  4088. [&](const Request &req, Response & /*res*/) {
  4089. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4090. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4091. })
  4092. .Get("/too-long-query-value",
  4093. [&](const Request &req, Response & /*res*/) {
  4094. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4095. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4096. })
  4097. .Get("/array-param",
  4098. [&](const Request &req, Response & /*res*/) {
  4099. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4100. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4101. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4102. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4103. })
  4104. .Get("/array-param-values",
  4105. [&](const Request &req, Response & /*res*/) {
  4106. auto values = req.get_param_values("array");
  4107. EXPECT_EQ(3u, values.size());
  4108. EXPECT_EQ("value1", values[0]);
  4109. EXPECT_EQ("value2", values[1]);
  4110. EXPECT_EQ("value3", values[2]);
  4111. auto empty = req.get_param_values("nonexistent");
  4112. EXPECT_TRUE(empty.empty());
  4113. })
  4114. .Post("/validate-no-multiple-headers",
  4115. [&](const Request &req, Response & /*res*/) {
  4116. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4117. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4118. })
  4119. .Post("/content_receiver",
  4120. [&](const Request &req, Response &res,
  4121. const ContentReader &content_reader) {
  4122. if (req.is_multipart_form_data()) {
  4123. std::vector<FormData> items;
  4124. content_reader(
  4125. [&](const FormData &file) {
  4126. items.push_back(file);
  4127. return true;
  4128. },
  4129. [&](const char *data, size_t data_length) {
  4130. items.back().content.append(data, data_length);
  4131. return true;
  4132. });
  4133. EXPECT_EQ(5u, items.size());
  4134. {
  4135. const auto &file = get_file_value(items, "text1");
  4136. EXPECT_TRUE(file.filename.empty());
  4137. EXPECT_EQ("text default", file.content);
  4138. }
  4139. {
  4140. const auto &file = get_file_value(items, "text2");
  4141. EXPECT_TRUE(file.filename.empty());
  4142. EXPECT_EQ("aωb", file.content);
  4143. }
  4144. {
  4145. const auto &file = get_file_value(items, "file1");
  4146. EXPECT_EQ("hello.txt", file.filename);
  4147. EXPECT_EQ("text/plain", file.content_type);
  4148. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4149. }
  4150. {
  4151. const auto &file = get_file_value(items, "file2");
  4152. EXPECT_EQ("world.json", file.filename);
  4153. EXPECT_EQ("application/json", file.content_type);
  4154. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4155. }
  4156. {
  4157. const auto &file = get_file_value(items, "file3");
  4158. EXPECT_TRUE(file.filename.empty());
  4159. EXPECT_EQ("application/octet-stream", file.content_type);
  4160. EXPECT_EQ(0u, file.content.size());
  4161. }
  4162. } else {
  4163. std::string body;
  4164. content_reader([&](const char *data, size_t data_length) {
  4165. EXPECT_EQ(7U, data_length);
  4166. body.append(data, data_length);
  4167. return true;
  4168. });
  4169. EXPECT_EQ(body, "content");
  4170. res.set_content(body, "text/plain");
  4171. }
  4172. })
  4173. .Put("/content_receiver",
  4174. [&](const Request & /*req*/, Response &res,
  4175. const ContentReader &content_reader) {
  4176. std::string body;
  4177. content_reader([&](const char *data, size_t data_length) {
  4178. body.append(data, data_length);
  4179. return true;
  4180. });
  4181. EXPECT_EQ(body, "content");
  4182. res.set_content(body, "text/plain");
  4183. })
  4184. .Patch("/content_receiver",
  4185. [&](const Request & /*req*/, Response &res,
  4186. const ContentReader &content_reader) {
  4187. std::string body;
  4188. content_reader([&](const char *data, size_t data_length) {
  4189. body.append(data, data_length);
  4190. return true;
  4191. });
  4192. EXPECT_EQ(body, "content");
  4193. res.set_content(body, "text/plain");
  4194. })
  4195. .Post("/query-string-and-body",
  4196. [&](const Request &req, Response & /*res*/) {
  4197. ASSERT_TRUE(req.has_param("key"));
  4198. EXPECT_EQ(req.get_param_value("key"), "value");
  4199. EXPECT_EQ(req.body, "content");
  4200. })
  4201. .Get("/last-request",
  4202. [&](const Request &req, Response & /*res*/) {
  4203. EXPECT_EQ("close", req.get_header_value("Connection"));
  4204. })
  4205. .Get(R"(/redirect/(\d+))",
  4206. [&](const Request &req, Response &res) {
  4207. auto num = std::stoi(req.matches[1]) + 1;
  4208. std::string url = "/redirect/" + std::to_string(num);
  4209. res.set_redirect(url);
  4210. })
  4211. .Post("/binary",
  4212. [&](const Request &req, Response &res) {
  4213. EXPECT_EQ(4U, req.body.size());
  4214. EXPECT_EQ("application/octet-stream",
  4215. req.get_header_value("Content-Type"));
  4216. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4217. res.set_content(req.body, "application/octet-stream");
  4218. })
  4219. .Put("/binary",
  4220. [&](const Request &req, Response &res) {
  4221. EXPECT_EQ(4U, req.body.size());
  4222. EXPECT_EQ("application/octet-stream",
  4223. req.get_header_value("Content-Type"));
  4224. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4225. res.set_content(req.body, "application/octet-stream");
  4226. })
  4227. .Patch("/binary",
  4228. [&](const Request &req, Response &res) {
  4229. EXPECT_EQ(4U, req.body.size());
  4230. EXPECT_EQ("application/octet-stream",
  4231. req.get_header_value("Content-Type"));
  4232. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4233. res.set_content(req.body, "application/octet-stream");
  4234. })
  4235. .Delete("/binary",
  4236. [&](const Request &req, Response &res) {
  4237. EXPECT_EQ(4U, req.body.size());
  4238. EXPECT_EQ("application/octet-stream",
  4239. req.get_header_value("Content-Type"));
  4240. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4241. res.set_content(req.body, "application/octet-stream");
  4242. })
  4243. .Get("/issue1772",
  4244. [&](const Request & /*req*/, Response &res) {
  4245. res.status = 401;
  4246. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4247. })
  4248. .Delete("/issue609",
  4249. [](const httplib::Request &, httplib::Response &res,
  4250. const httplib::ContentReader &) {
  4251. res.set_content("ok", "text/plain");
  4252. })
  4253. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4254. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4255. .Get("/compress",
  4256. [&](const Request & /*req*/, Response &res) {
  4257. res.set_content(
  4258. "12345678901234567890123456789012345678901234567890123456789"
  4259. "01234567890123456789012345678901234567890",
  4260. "text/plain");
  4261. })
  4262. .Get("/compress-with-charset",
  4263. [&](const Request & /*req*/, Response &res) {
  4264. res.set_content(
  4265. "12345678901234567890123456789012345678901234567890123456789"
  4266. "01234567890123456789012345678901234567890",
  4267. "application/json; charset=utf-8");
  4268. })
  4269. .Get("/nocompress",
  4270. [&](const Request & /*req*/, Response &res) {
  4271. res.set_content(
  4272. "12345678901234567890123456789012345678901234567890123456789"
  4273. "01234567890123456789012345678901234567890",
  4274. "application/octet-stream");
  4275. })
  4276. .Post("/compress-multipart",
  4277. [&](const Request &req, Response & /*res*/) {
  4278. EXPECT_EQ(2u, req.form.fields.size());
  4279. ASSERT_TRUE(!req.form.has_field("???"));
  4280. {
  4281. const auto &text = req.form.get_field("key1");
  4282. EXPECT_EQ("test", text);
  4283. }
  4284. {
  4285. const auto &text = req.form.get_field("key2");
  4286. EXPECT_EQ("--abcdefg123", text);
  4287. }
  4288. })
  4289. #endif
  4290. ;
  4291. persons_["john"] = "programmer";
  4292. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4293. svr_.wait_until_ready();
  4294. }
  4295. virtual void TearDown() {
  4296. svr_.stop();
  4297. if (!request_threads_.empty()) {
  4298. std::this_thread::sleep_for(std::chrono::seconds(1));
  4299. for (auto &t : request_threads_) {
  4300. t.join();
  4301. }
  4302. }
  4303. t_.join();
  4304. }
  4305. map<string, string> persons_;
  4306. #ifdef CPPHTTPLIB_SSL_ENABLED
  4307. SSLClient cli_;
  4308. SSLServer svr_;
  4309. #else
  4310. Client cli_;
  4311. Server svr_;
  4312. #endif
  4313. thread t_;
  4314. std::vector<thread> request_threads_;
  4315. };
  4316. TEST_F(ServerTest, GetMethod200) {
  4317. auto res = cli_.Get("/hi");
  4318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4319. EXPECT_EQ("HTTP/1.1", res->version);
  4320. EXPECT_EQ(StatusCode::OK_200, res->status);
  4321. EXPECT_EQ("OK", res->reason);
  4322. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4323. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4324. EXPECT_EQ("Hello World!", res->body);
  4325. }
  4326. TEST_F(ServerTest, GetEmptyFile) {
  4327. auto res = cli_.Get("/empty_file");
  4328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4329. EXPECT_EQ(StatusCode::OK_200, res->status);
  4330. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4331. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4332. EXPECT_EQ("", res->body);
  4333. }
  4334. TEST_F(ServerTest, GetFileContent) {
  4335. auto res = cli_.Get("/file_content");
  4336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4337. EXPECT_EQ(StatusCode::OK_200, res->status);
  4338. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4339. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4340. EXPECT_EQ("test.html", res->body);
  4341. }
  4342. TEST_F(ServerTest, GetFileContentWithRange) {
  4343. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4345. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4346. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4347. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4348. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4349. EXPECT_EQ("est", res->body);
  4350. }
  4351. TEST_F(ServerTest, GetFileContentWithContentType) {
  4352. auto res = cli_.Get("/file_content_with_content_type");
  4353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4354. EXPECT_EQ(StatusCode::OK_200, res->status);
  4355. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4356. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4357. EXPECT_EQ("file\n", res->body);
  4358. }
  4359. TEST_F(ServerTest, GetInvalidFileContent) {
  4360. auto res = cli_.Get("/invalid_file_content");
  4361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4362. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4363. }
  4364. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4365. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4367. EXPECT_EQ("HTTP/1.1", res->version);
  4368. EXPECT_EQ(StatusCode::OK_200, res->status);
  4369. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4370. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4371. EXPECT_EQ("Hello World!", res->body);
  4372. }
  4373. TEST_F(ServerTest, GetMethod302) {
  4374. auto res = cli_.Get("/");
  4375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4376. EXPECT_EQ(StatusCode::Found_302, res->status);
  4377. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4378. }
  4379. TEST_F(ServerTest, GetMethod302Redirect) {
  4380. cli_.set_follow_location(true);
  4381. auto res = cli_.Get("/");
  4382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4383. EXPECT_EQ(StatusCode::OK_200, res->status);
  4384. EXPECT_EQ("Hello World!", res->body);
  4385. EXPECT_EQ("/hi", res->location);
  4386. }
  4387. TEST_F(ServerTest, GetMethod404) {
  4388. auto res = cli_.Get("/invalid");
  4389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4390. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4391. }
  4392. TEST_F(ServerTest, HeadMethod200) {
  4393. auto res = cli_.Head("/hi");
  4394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4395. EXPECT_EQ(StatusCode::OK_200, res->status);
  4396. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4397. EXPECT_TRUE(res->body.empty());
  4398. }
  4399. TEST_F(ServerTest, HeadMethod200Static) {
  4400. auto res = cli_.Head("/mount/dir/index.html");
  4401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4402. EXPECT_EQ(StatusCode::OK_200, res->status);
  4403. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4404. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4405. EXPECT_TRUE(res->body.empty());
  4406. }
  4407. TEST_F(ServerTest, HeadMethod404) {
  4408. auto res = cli_.Head("/invalid");
  4409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4410. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4411. EXPECT_TRUE(res->body.empty());
  4412. }
  4413. TEST_F(ServerTest, GetMethodPersonJohn) {
  4414. auto res = cli_.Get("/person/john");
  4415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4416. EXPECT_EQ(StatusCode::OK_200, res->status);
  4417. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4418. EXPECT_EQ("programmer", res->body);
  4419. }
  4420. TEST_F(ServerTest, PostMethod1) {
  4421. auto res = cli_.Get("/person/john1");
  4422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4423. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4424. res = cli_.Post("/person", "name=john1&note=coder",
  4425. "application/x-www-form-urlencoded");
  4426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4427. ASSERT_EQ(StatusCode::OK_200, res->status);
  4428. res = cli_.Get("/person/john1");
  4429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4430. ASSERT_EQ(StatusCode::OK_200, res->status);
  4431. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4432. ASSERT_EQ("coder", res->body);
  4433. }
  4434. TEST_F(ServerTest, PostMethod2) {
  4435. auto res = cli_.Get("/person/john2");
  4436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4437. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4438. Params params;
  4439. params.emplace("name", "john2");
  4440. params.emplace("note", "coder");
  4441. res = cli_.Post("/person", params);
  4442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4443. ASSERT_EQ(StatusCode::OK_200, res->status);
  4444. res = cli_.Get("/person/john2");
  4445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4446. ASSERT_EQ(StatusCode::OK_200, res->status);
  4447. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4448. ASSERT_EQ("coder", res->body);
  4449. }
  4450. TEST_F(ServerTest, PutMethod3) {
  4451. auto res = cli_.Get("/person/john3");
  4452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4453. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4454. Params params;
  4455. params.emplace("name", "john3");
  4456. params.emplace("note", "coder");
  4457. res = cli_.Put("/person", params);
  4458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4459. ASSERT_EQ(StatusCode::OK_200, res->status);
  4460. res = cli_.Get("/person/john3");
  4461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4462. ASSERT_EQ(StatusCode::OK_200, res->status);
  4463. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4464. ASSERT_EQ("coder", res->body);
  4465. }
  4466. TEST_F(ServerTest, DeleteMethod1) {
  4467. auto res = cli_.Get("/person/john4");
  4468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4469. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4470. Params params;
  4471. params.emplace("name", "john4");
  4472. params.emplace("note", "coder");
  4473. res = cli_.Post("/person", params);
  4474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4475. ASSERT_EQ(StatusCode::OK_200, res->status);
  4476. res = cli_.Get("/person/john4");
  4477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4478. ASSERT_EQ(StatusCode::OK_200, res->status);
  4479. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4480. ASSERT_EQ("coder", res->body);
  4481. Params delete_params;
  4482. delete_params.emplace("name", "john4");
  4483. res = cli_.Delete("/person", delete_params);
  4484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4485. ASSERT_EQ(StatusCode::OK_200, res->status);
  4486. ASSERT_EQ("DELETED", res->body);
  4487. res = cli_.Get("/person/john4");
  4488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4489. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4490. }
  4491. TEST_F(ServerTest, DeleteMethod2) {
  4492. auto res = cli_.Get("/person/john5");
  4493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4494. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4495. Params params;
  4496. params.emplace("name", "john5");
  4497. params.emplace("note", "developer");
  4498. res = cli_.Post("/person", params);
  4499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4500. ASSERT_EQ(StatusCode::OK_200, res->status);
  4501. res = cli_.Get("/person/john5");
  4502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4503. ASSERT_EQ(StatusCode::OK_200, res->status);
  4504. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4505. ASSERT_EQ("developer", res->body);
  4506. Params delete_params;
  4507. delete_params.emplace("name", "john5");
  4508. Headers headers;
  4509. headers.emplace("Custom-Header", "test-value");
  4510. res = cli_.Delete("/person", headers, delete_params);
  4511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4512. ASSERT_EQ(StatusCode::OK_200, res->status);
  4513. ASSERT_EQ("DELETED", res->body);
  4514. res = cli_.Get("/person/john5");
  4515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4516. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4517. }
  4518. TEST_F(ServerTest, DeleteMethod3) {
  4519. auto res = cli_.Get("/person/john6");
  4520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4521. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4522. Params params;
  4523. params.emplace("name", "john6");
  4524. params.emplace("note", "tester");
  4525. res = cli_.Post("/person", params);
  4526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4527. ASSERT_EQ(StatusCode::OK_200, res->status);
  4528. res = cli_.Get("/person/john6");
  4529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4530. ASSERT_EQ(StatusCode::OK_200, res->status);
  4531. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4532. ASSERT_EQ("tester", res->body);
  4533. Params delete_params;
  4534. delete_params.emplace("name", "john6");
  4535. Headers headers;
  4536. headers.emplace("Custom-Header", "test-value");
  4537. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4539. ASSERT_EQ(StatusCode::OK_200, res->status);
  4540. ASSERT_EQ("DELETED", res->body);
  4541. res = cli_.Get("/person/john6");
  4542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4543. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4544. }
  4545. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4546. Params params;
  4547. params.emplace("json", JSON_DATA);
  4548. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4550. ASSERT_EQ(StatusCode::OK_200, res->status);
  4551. ASSERT_EQ(JSON_DATA, res->body);
  4552. }
  4553. TEST_F(ServerTest, PostEmptyContent) {
  4554. auto res = cli_.Post("/empty", "", "text/plain");
  4555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4556. ASSERT_EQ(StatusCode::OK_200, res->status);
  4557. ASSERT_EQ("empty", res->body);
  4558. }
  4559. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4560. auto res = cli_.Post("/empty-no-content-type");
  4561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4562. ASSERT_EQ(StatusCode::OK_200, res->status);
  4563. ASSERT_EQ("empty-no-content-type", res->body);
  4564. }
  4565. TEST_F(ServerTest, PostPathOnly) {
  4566. auto res = cli_.Post("/path-only");
  4567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4568. ASSERT_EQ(StatusCode::OK_200, res->status);
  4569. ASSERT_EQ("path-only", res->body);
  4570. }
  4571. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4572. auto res = cli_.Post("/path-headers-only",
  4573. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4575. ASSERT_EQ(StatusCode::OK_200, res->status);
  4576. ASSERT_EQ("path-headers-only", res->body);
  4577. }
  4578. TEST_F(ServerTest, PostLarge) {
  4579. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4581. ASSERT_EQ(StatusCode::OK_200, res->status);
  4582. EXPECT_EQ(LARGE_DATA, res->body);
  4583. }
  4584. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4585. auto res = cli_.Put("/empty-no-content-type");
  4586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4587. ASSERT_EQ(StatusCode::OK_200, res->status);
  4588. ASSERT_EQ("empty-no-content-type", res->body);
  4589. }
  4590. TEST_F(ServerTest, GetMethodDir) {
  4591. auto res = cli_.Get("/dir/");
  4592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4593. EXPECT_EQ(StatusCode::OK_200, res->status);
  4594. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4595. auto body = R"(<html>
  4596. <head>
  4597. </head>
  4598. <body>
  4599. <a href="/dir/test.html">Test</a>
  4600. <a href="/hi">hi</a>
  4601. </body>
  4602. </html>
  4603. )";
  4604. EXPECT_EQ(body, res->body);
  4605. }
  4606. TEST_F(ServerTest, GetMethodDirTest) {
  4607. auto res = cli_.Get("/dir/test.html");
  4608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4609. EXPECT_EQ(StatusCode::OK_200, res->status);
  4610. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4611. EXPECT_EQ("test.html", res->body);
  4612. }
  4613. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4614. auto res = cli_.Get("/dir/../dir/test.html");
  4615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4616. EXPECT_EQ(StatusCode::OK_200, res->status);
  4617. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4618. EXPECT_EQ("test.html", res->body);
  4619. }
  4620. TEST_F(ServerTest, GetMethodInvalidPath) {
  4621. auto res = cli_.Get("/dir/../test.html");
  4622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4623. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4624. }
  4625. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4626. auto res = cli_.Get("/../www/dir/test.html");
  4627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4628. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4629. }
  4630. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4631. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4633. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4634. }
  4635. TEST_F(ServerTest, GetMethodDirMountTest) {
  4636. auto res = cli_.Get("/mount/dir/test.html");
  4637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4638. EXPECT_EQ(StatusCode::OK_200, res->status);
  4639. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4640. EXPECT_EQ("test.html", res->body);
  4641. }
  4642. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4643. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4645. EXPECT_EQ(StatusCode::OK_200, res->status);
  4646. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4647. EXPECT_EQ("test.html", res->body);
  4648. }
  4649. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4650. auto res = cli_.Get("/mount/dir/../test.html");
  4651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4652. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4653. }
  4654. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4655. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4657. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4658. }
  4659. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4660. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4662. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4663. }
  4664. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4665. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4667. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4668. }
  4669. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4670. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4672. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4673. }
  4674. TEST_F(ServerTest, PostMethod303) {
  4675. auto res = cli_.Post("/1", "body", "text/plain");
  4676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4677. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4678. EXPECT_EQ("/2", res->get_header_value("Location"));
  4679. }
  4680. TEST_F(ServerTest, PostMethod303Redirect) {
  4681. cli_.set_follow_location(true);
  4682. auto res = cli_.Post("/1", "body", "text/plain");
  4683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4684. EXPECT_EQ(StatusCode::OK_200, res->status);
  4685. EXPECT_EQ("redirected.", res->body);
  4686. EXPECT_EQ("/2", res->location);
  4687. }
  4688. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4689. auto res = cli_.Get("/dir/test.abcde");
  4690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4691. EXPECT_EQ(StatusCode::OK_200, res->status);
  4692. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4693. EXPECT_EQ("abcde", res->body);
  4694. }
  4695. TEST_F(ServerTest, StaticFileRange) {
  4696. auto res =
  4697. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4699. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4700. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4701. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4702. EXPECT_EQ(true, res->has_header("Content-Range"));
  4703. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4704. EXPECT_EQ(std::string("cd"), res->body);
  4705. }
  4706. TEST_F(ServerTest, StaticFileRanges) {
  4707. auto res = cli_.Get("/dir/test.abcde",
  4708. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4710. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4711. EXPECT_TRUE(
  4712. res->get_header_value("Content-Type")
  4713. .find(
  4714. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4715. 0);
  4716. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4717. }
  4718. TEST_F(ServerTest, StaticFileRangeHead) {
  4719. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4721. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4722. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4723. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4724. EXPECT_EQ(true, res->has_header("Content-Range"));
  4725. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4726. }
  4727. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4728. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4730. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4731. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4732. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4733. EXPECT_EQ(true, res->has_header("Content-Range"));
  4734. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4735. res->get_header_value("Content-Range"));
  4736. EXPECT_EQ("LAST\n", res->body);
  4737. }
  4738. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4739. auto res =
  4740. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4742. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4743. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4744. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4745. EXPECT_EQ(true, res->has_header("Content-Range"));
  4746. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4747. }
  4748. TEST_F(ServerTest, StaticFileBigFile) {
  4749. auto res = cli_.Get("/dir/1MB.txt");
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. EXPECT_EQ(StatusCode::OK_200, res->status);
  4752. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4753. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4754. }
  4755. TEST_F(ServerTest, InvalidBaseDirMount) {
  4756. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4757. }
  4758. TEST_F(ServerTest, Binary) {
  4759. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4760. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4761. "application/octet-stream");
  4762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4763. ASSERT_EQ(StatusCode::OK_200, res->status);
  4764. ASSERT_EQ(4U, res->body.size());
  4765. res = cli_.Put("/binary", binary.data(), binary.size(),
  4766. "application/octet-stream");
  4767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4768. ASSERT_EQ(StatusCode::OK_200, res->status);
  4769. ASSERT_EQ(4U, res->body.size());
  4770. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4771. "application/octet-stream");
  4772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4773. ASSERT_EQ(StatusCode::OK_200, res->status);
  4774. ASSERT_EQ(4U, res->body.size());
  4775. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4776. "application/octet-stream");
  4777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4778. ASSERT_EQ(StatusCode::OK_200, res->status);
  4779. ASSERT_EQ(4U, res->body.size());
  4780. }
  4781. TEST_F(ServerTest, BinaryString) {
  4782. auto binary = std::string("\x00\x01\x02\x03", 4);
  4783. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4785. ASSERT_EQ(StatusCode::OK_200, res->status);
  4786. ASSERT_EQ(4U, res->body.size());
  4787. res = cli_.Put("/binary", binary, "application/octet-stream");
  4788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4789. ASSERT_EQ(StatusCode::OK_200, res->status);
  4790. ASSERT_EQ(4U, res->body.size());
  4791. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4793. ASSERT_EQ(StatusCode::OK_200, res->status);
  4794. ASSERT_EQ(4U, res->body.size());
  4795. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4797. ASSERT_EQ(StatusCode::OK_200, res->status);
  4798. ASSERT_EQ(4U, res->body.size());
  4799. }
  4800. TEST_F(ServerTest, EmptyRequest) {
  4801. auto res = cli_.Get("");
  4802. ASSERT_TRUE(!res);
  4803. EXPECT_EQ(Error::Connection, res.error());
  4804. }
  4805. TEST_F(ServerTest, LongRequest) {
  4806. std::string request;
  4807. for (size_t i = 0; i < 545; i++) {
  4808. request += "/TooLongRequest";
  4809. }
  4810. request += "OK";
  4811. auto res = cli_.Get(request.c_str());
  4812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4813. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4814. }
  4815. TEST_F(ServerTest, TooLongRequest) {
  4816. std::string request;
  4817. for (size_t i = 0; i < 546; i++) {
  4818. request += "/TooLongRequest";
  4819. }
  4820. request += "_NG";
  4821. auto start = std::chrono::high_resolution_clock::now();
  4822. cli_.set_keep_alive(true);
  4823. auto res = cli_.Get(request.c_str());
  4824. auto end = std::chrono::high_resolution_clock::now();
  4825. auto elapsed =
  4826. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4827. .count();
  4828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4829. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4830. EXPECT_LE(elapsed, 1000);
  4831. EXPECT_EQ("close", res->get_header_value("Connection"));
  4832. EXPECT_FALSE(cli_.is_socket_open());
  4833. }
  4834. TEST_F(ServerTest, AlmostTooLongRequest) {
  4835. // test for #2046 - URI length check shouldn't include other content on req
  4836. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4837. // leading /, space, HTTP/1.1)
  4838. std::string request =
  4839. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4840. auto res = cli_.Get(request.c_str());
  4841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4842. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4843. }
  4844. TEST_F(ServerTest, LongHeader) {
  4845. Request req;
  4846. req.method = "GET";
  4847. req.path = "/hi";
  4848. std::string host_and_port;
  4849. host_and_port += HOST;
  4850. host_and_port += ":";
  4851. host_and_port += std::to_string(PORT);
  4852. req.headers.emplace("Host", host_and_port.c_str());
  4853. req.headers.emplace("Accept", "*/*");
  4854. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4855. req.headers.emplace(
  4856. "Header-Name",
  4857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4858. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4859. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4874. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4875. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4876. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4877. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4878. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4879. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4880. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4881. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4882. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4883. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4884. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4885. "@@@@@@@@@@@@@@@@");
  4886. auto res = std::make_shared<Response>();
  4887. auto error = Error::Success;
  4888. auto ret = cli_.send(req, *res, error);
  4889. ASSERT_TRUE(ret);
  4890. EXPECT_EQ(StatusCode::OK_200, res->status);
  4891. }
  4892. TEST_F(ServerTest, LongQueryValue) {
  4893. auto start = std::chrono::high_resolution_clock::now();
  4894. cli_.set_keep_alive(true);
  4895. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4896. auto end = std::chrono::high_resolution_clock::now();
  4897. auto elapsed =
  4898. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4899. .count();
  4900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4901. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4902. EXPECT_LE(elapsed, 1000);
  4903. EXPECT_EQ("close", res->get_header_value("Connection"));
  4904. EXPECT_FALSE(cli_.is_socket_open());
  4905. }
  4906. TEST_F(ServerTest, TooLongQueryValue) {
  4907. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4908. ASSERT_FALSE(res);
  4909. EXPECT_EQ(Error::Read, res.error());
  4910. }
  4911. TEST_F(ServerTest, TooLongHeader) {
  4912. Request req;
  4913. req.method = "GET";
  4914. req.path = "/hi";
  4915. std::string host_and_port;
  4916. host_and_port += HOST;
  4917. host_and_port += ":";
  4918. host_and_port += std::to_string(PORT);
  4919. req.headers.emplace("Host", host_and_port.c_str());
  4920. req.headers.emplace("Accept", "*/*");
  4921. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4922. req.headers.emplace(
  4923. "Header-Name",
  4924. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4925. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4926. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4927. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4928. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4929. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4930. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4949. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4950. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4951. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4952. "@@@@@@@@@@@@@@@@@");
  4953. auto res = std::make_shared<Response>();
  4954. auto error = Error::Success;
  4955. auto ret = cli_.send(req, *res, error);
  4956. ASSERT_TRUE(ret);
  4957. EXPECT_EQ(StatusCode::OK_200, res->status);
  4958. }
  4959. TEST_F(ServerTest, HeaderCountAtLimit) {
  4960. // Test with headers just under the 100 limit
  4961. httplib::Headers headers;
  4962. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4963. // This should keep us just under the 100 header limit
  4964. for (int i = 0; i < 95; i++) {
  4965. std::string name = "X-Test-Header-" + std::to_string(i);
  4966. std::string value = "value" + std::to_string(i);
  4967. headers.emplace(name, value);
  4968. }
  4969. // This should work fine as we're under the limit
  4970. auto res = cli_.Get("/hi", headers);
  4971. EXPECT_TRUE(res);
  4972. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4973. }
  4974. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4975. // Test with many headers to exceed the 100 limit
  4976. httplib::Headers headers;
  4977. // Add 150 headers to definitely exceed the 100 limit
  4978. for (int i = 0; i < 150; i++) {
  4979. std::string name = "X-Test-Header-" + std::to_string(i);
  4980. std::string value = "value" + std::to_string(i);
  4981. headers.emplace(name, value);
  4982. }
  4983. // This should fail due to exceeding header count limit
  4984. cli_.set_keep_alive(true);
  4985. auto res = cli_.Get("/hi", headers);
  4986. // The server should respond with 400 Bad Request
  4987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4988. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4989. EXPECT_EQ("close", res->get_header_value("Connection"));
  4990. EXPECT_FALSE(cli_.is_socket_open());
  4991. }
  4992. TEST_F(ServerTest, PercentEncoding) {
  4993. auto res = cli_.Get("/e%6edwith%");
  4994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4995. EXPECT_EQ(StatusCode::OK_200, res->status);
  4996. }
  4997. TEST_F(ServerTest, PercentEncodingUnicode) {
  4998. auto res = cli_.Get("/e%u006edwith%");
  4999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5000. EXPECT_EQ(StatusCode::OK_200, res->status);
  5001. }
  5002. TEST_F(ServerTest, InvalidPercentEncoding) {
  5003. auto res = cli_.Get("/%endwith%");
  5004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5005. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5006. }
  5007. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5008. auto res = cli_.Get("/%uendwith%");
  5009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5010. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5011. }
  5012. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5013. auto res = cli_.Get("/hello?aaa=bbb%");
  5014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5015. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5016. }
  5017. TEST_F(ServerTest, PlusSignEncoding) {
  5018. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5020. EXPECT_EQ(StatusCode::OK_200, res->status);
  5021. EXPECT_EQ("a +b", res->body);
  5022. }
  5023. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5024. // This test simulates a potential DoS attack using many headers
  5025. // to verify our security fix prevents memory exhaustion
  5026. httplib::Headers attack_headers;
  5027. // Attempt to add many headers like an attacker would (200 headers to far
  5028. // exceed limit)
  5029. for (int i = 0; i < 200; i++) {
  5030. std::string name = "X-Attack-Header-" + std::to_string(i);
  5031. std::string value = "attack_payload_" + std::to_string(i);
  5032. attack_headers.emplace(name, value);
  5033. }
  5034. // Try to POST with excessive headers
  5035. cli_.set_keep_alive(true);
  5036. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5037. // Should either fail or return 400 Bad Request due to security limit
  5038. if (res) {
  5039. // If we get a response, it should be 400 Bad Request
  5040. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5041. EXPECT_EQ("close", res->get_header_value("Connection"));
  5042. }
  5043. EXPECT_FALSE(cli_.is_socket_open());
  5044. }
  5045. TEST_F(ServerTest, MultipartFormData) {
  5046. UploadFormDataItems items = {
  5047. {"text1", "text default", "", ""},
  5048. {"text2", "aωb", "", ""},
  5049. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5050. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5051. {"file3", "", "", "application/octet-stream"},
  5052. {"file4", "", "", " application/json tmp-string "}};
  5053. auto res = cli_.Post("/multipart", items);
  5054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5055. EXPECT_EQ(StatusCode::OK_200, res->status);
  5056. }
  5057. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5058. UploadFormDataItems items = {
  5059. {"text", "default text", "", ""},
  5060. {"multi_text1", "aaaaa", "", ""},
  5061. {"multi_text1", "bbbbb", "", ""},
  5062. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5063. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5064. "application/json"},
  5065. };
  5066. auto res = cli_.Post("/multipart/multi_file_values", items);
  5067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5068. EXPECT_EQ(StatusCode::OK_200, res->status);
  5069. }
  5070. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5071. auto res = cli_.Get("/hi");
  5072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5073. EXPECT_EQ(StatusCode::OK_200, res->status);
  5074. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5075. EXPECT_EQ("Hello World!", res->body);
  5076. }
  5077. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5078. Request req;
  5079. req.method = "POST";
  5080. req.path = "/chunked";
  5081. std::string host_and_port;
  5082. host_and_port += HOST;
  5083. host_and_port += ":";
  5084. host_and_port += std::to_string(PORT);
  5085. req.headers.emplace("Host", host_and_port.c_str());
  5086. req.headers.emplace("Accept", "*/*");
  5087. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5088. req.headers.emplace("Content-Type", "text/plain");
  5089. req.headers.emplace("Content-Length", "0");
  5090. req.headers.emplace(
  5091. "Transfer-Encoding",
  5092. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5093. // Client does not chunk, so make a chunked body manually.
  5094. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5095. auto res = std::make_shared<Response>();
  5096. auto error = Error::Success;
  5097. auto ret = cli_.send(req, *res, error);
  5098. ASSERT_TRUE(ret);
  5099. EXPECT_EQ(StatusCode::OK_200, res->status);
  5100. }
  5101. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5102. // rather than treat them as valid lengths.
  5103. template <typename ClientT>
  5104. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5105. Request req;
  5106. req.method = "POST";
  5107. req.path = "/chunked";
  5108. std::string host_and_port;
  5109. host_and_port += HOST;
  5110. host_and_port += ":";
  5111. host_and_port += std::to_string(PORT);
  5112. req.headers.emplace("Host", host_and_port.c_str());
  5113. req.headers.emplace("Content-Length", "0");
  5114. req.headers.emplace("Transfer-Encoding", "chunked");
  5115. req.body = body;
  5116. auto res = std::make_shared<Response>();
  5117. auto error = Error::Success;
  5118. ASSERT_TRUE(cli.send(req, *res, error));
  5119. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5120. }
  5121. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5122. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5123. }
  5124. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5125. expect_chunked_body_rejected(
  5126. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5127. }
  5128. TEST_F(ServerTest, GetStreamed2) {
  5129. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5131. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5132. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5133. EXPECT_EQ(true, res->has_header("Content-Range"));
  5134. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5135. EXPECT_EQ(std::string("ab"), res->body);
  5136. }
  5137. TEST_F(ServerTest, GetStreamed) {
  5138. auto res = cli_.Get("/streamed");
  5139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5140. EXPECT_EQ(StatusCode::OK_200, res->status);
  5141. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5142. EXPECT_EQ(std::string("aaabbb"), res->body);
  5143. }
  5144. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5145. auto res = cli_.Get("/streamed-without-length",
  5146. Headers{make_range_header({{0, -1}})});
  5147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5148. EXPECT_EQ(StatusCode::OK_200, res->status);
  5149. EXPECT_EQ(false, res->has_header("Content-Length"));
  5150. EXPECT_EQ(false, res->has_header("Content-Range"));
  5151. EXPECT_EQ(std::string("abcdefg"), res->body);
  5152. }
  5153. TEST_F(ServerTest, GetStreamedWithRange1) {
  5154. auto res =
  5155. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5157. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5158. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5159. EXPECT_EQ(true, res->has_header("Content-Range"));
  5160. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5161. EXPECT_EQ(std::string("def"), res->body);
  5162. }
  5163. TEST_F(ServerTest, GetStreamedWithRange2) {
  5164. auto res =
  5165. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5167. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5168. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5169. EXPECT_EQ(true, res->has_header("Content-Range"));
  5170. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5171. EXPECT_EQ(std::string("bcdefg"), res->body);
  5172. }
  5173. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5174. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5177. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5178. EXPECT_EQ(true, res->has_header("Content-Range"));
  5179. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5180. EXPECT_EQ(std::string("efg"), res->body);
  5181. }
  5182. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5183. auto res =
  5184. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5186. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5187. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5188. EXPECT_EQ(false, res->has_header("Content-Range"));
  5189. EXPECT_EQ(0U, res->body.size());
  5190. }
  5191. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5192. // Only a 206 is served as a partial representation. Under any other status
  5193. // `apply_ranges()` reported the full content length, so the body must match
  5194. // that header, and the content provider must never be asked for an offset
  5195. // outside the representation.
  5196. auto check = [&](int status, const char *range) {
  5197. auto path =
  5198. std::string("/streamed-with-range?status=") + std::to_string(status);
  5199. auto ctx = path + " Range: " + range;
  5200. auto res = cli_.Get(path, Headers{{"Range", range}});
  5201. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5202. EXPECT_EQ(status, res->status) << ctx;
  5203. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5204. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5205. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5206. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5207. };
  5208. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5209. check(403, "bytes=3-5");
  5210. // The offset is far past the representation.
  5211. check(403, "bytes=100000-100200");
  5212. // `first_pos` is still -1 here, and the bounds asserts in
  5213. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5214. check(403, "bytes=-3");
  5215. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5216. // multipart branch would have written one that is empty.
  5217. check(403, "bytes=1-2, 4-5");
  5218. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5219. // covers the whole representation.
  5220. check(200, "bytes=3-5");
  5221. check(200, "bytes=1-2, 4-5");
  5222. }
  5223. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5224. auto res =
  5225. cli_.Get("/streamed-with-range",
  5226. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5227. "92233720368547758079223372036854775807"}});
  5228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5229. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5230. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5231. EXPECT_EQ(false, res->has_header("Content-Range"));
  5232. EXPECT_EQ(0U, res->body.size());
  5233. }
  5234. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5235. auto res = cli_.Get(
  5236. "/with-range",
  5237. Headers{{"Range",
  5238. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5239. {"Accept-Encoding", ""}});
  5240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5241. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5242. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5243. EXPECT_EQ(true, res->has_header("Content-Range"));
  5244. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5245. EXPECT_EQ(std::string("abcdefg"), res->body);
  5246. }
  5247. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5248. auto res = cli_.Get("/with-range", Headers{
  5249. {"Range", "bytes=0-"},
  5250. {"Accept-Encoding", ""},
  5251. });
  5252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5253. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5254. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5255. EXPECT_EQ(true, res->has_header("Content-Range"));
  5256. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5257. EXPECT_EQ(std::string("abcdefg"), res->body);
  5258. }
  5259. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5260. auto res = cli_.Get("/streamed-with-range",
  5261. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5263. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5264. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5265. EXPECT_EQ(false, res->has_header("Content-Range"));
  5266. EXPECT_EQ(267U, res->body.size());
  5267. // Check that both range contents are present
  5268. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5269. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5270. // Check that Content-Range headers are present for both ranges
  5271. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5272. std::string::npos);
  5273. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5274. std::string::npos);
  5275. }
  5276. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5277. Ranges ranges;
  5278. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5279. ranges.emplace_back(0, -1);
  5280. }
  5281. auto res = cli_.Get("/streamed-with-range?error",
  5282. Headers{{make_range_header(ranges)}});
  5283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5284. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5285. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5286. EXPECT_EQ(false, res->has_header("Content-Range"));
  5287. EXPECT_EQ(0U, res->body.size());
  5288. }
  5289. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5290. auto res = cli_.Get("/streamed-with-range",
  5291. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5293. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5294. EXPECT_EQ(5U, res->body.size());
  5295. // Check that overlapping ranges are coalesced into a single range
  5296. EXPECT_EQ("bcdef", res->body);
  5297. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5298. // Should be single range, not multipart
  5299. EXPECT_TRUE(res->has_header("Content-Range"));
  5300. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5301. }
  5302. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5303. auto res = cli_.Get("/streamed-with-range",
  5304. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5306. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5307. EXPECT_EQ(268U, res->body.size());
  5308. // Check that both range contents are present
  5309. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5310. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5311. // Check that Content-Range headers are present for both ranges
  5312. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5313. std::string::npos);
  5314. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5315. std::string::npos);
  5316. }
  5317. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5318. auto res = cli_.Get("/streamed-with-range",
  5319. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5321. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5322. EXPECT_EQ(269U, res->body.size());
  5323. // Check that both duplicate range contents are present
  5324. size_t first_abc = res->body.find("abc\r\n");
  5325. EXPECT_TRUE(first_abc != std::string::npos);
  5326. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5327. EXPECT_TRUE(second_abc != std::string::npos);
  5328. // Check that Content-Range headers are present for both ranges
  5329. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5330. EXPECT_TRUE(first_range != std::string::npos);
  5331. size_t second_range =
  5332. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5333. EXPECT_TRUE(second_range != std::string::npos);
  5334. }
  5335. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5336. auto res =
  5337. cli_.Get("/streamed-with-range?error",
  5338. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5340. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5341. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5342. EXPECT_EQ(false, res->has_header("Content-Range"));
  5343. EXPECT_EQ(0U, res->body.size());
  5344. }
  5345. TEST_F(ServerTest, GetStreamedEndless) {
  5346. uint64_t offset = 0;
  5347. auto res = cli_.Get("/streamed-cancel",
  5348. [&](const char * /*data*/, uint64_t data_length) {
  5349. if (offset < 100) {
  5350. offset += data_length;
  5351. return true;
  5352. }
  5353. return false;
  5354. });
  5355. ASSERT_TRUE(!res);
  5356. EXPECT_EQ(Error::Canceled, res.error());
  5357. }
  5358. TEST_F(ServerTest, ClientStop) {
  5359. std::atomic_size_t count{4};
  5360. std::vector<std::thread> threads;
  5361. for (auto i = count.load(); i != 0; --i) {
  5362. threads.emplace_back([&]() {
  5363. auto res = cli_.Get("/streamed-cancel",
  5364. [&](const char *, uint64_t) { return true; });
  5365. --count;
  5366. ASSERT_TRUE(!res);
  5367. EXPECT_TRUE(res.error() == Error::Canceled ||
  5368. res.error() == Error::Read || res.error() == Error::Write);
  5369. });
  5370. }
  5371. std::this_thread::sleep_for(std::chrono::seconds(2));
  5372. while (count != 0) {
  5373. cli_.stop();
  5374. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5375. }
  5376. for (auto &t : threads) {
  5377. t.join();
  5378. }
  5379. }
  5380. TEST_F(ServerTest, GetWithRange1) {
  5381. auto res = cli_.Get("/with-range", Headers{
  5382. make_range_header({{3, 5}}),
  5383. {"Accept-Encoding", ""},
  5384. });
  5385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5386. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5387. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5388. EXPECT_EQ(true, res->has_header("Content-Range"));
  5389. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5390. EXPECT_EQ(std::string("def"), res->body);
  5391. }
  5392. TEST_F(ServerTest, GetWithRange2) {
  5393. auto res = cli_.Get("/with-range", Headers{
  5394. make_range_header({{1, -1}}),
  5395. {"Accept-Encoding", ""},
  5396. });
  5397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5398. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5399. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5400. EXPECT_EQ(true, res->has_header("Content-Range"));
  5401. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5402. EXPECT_EQ(std::string("bcdefg"), res->body);
  5403. }
  5404. TEST_F(ServerTest, GetWithRange3) {
  5405. auto res = cli_.Get("/with-range", Headers{
  5406. make_range_header({{0, 0}}),
  5407. {"Accept-Encoding", ""},
  5408. });
  5409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5410. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5411. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5412. EXPECT_EQ(true, res->has_header("Content-Range"));
  5413. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5414. EXPECT_EQ(std::string("a"), res->body);
  5415. }
  5416. TEST_F(ServerTest, GetWithRange4) {
  5417. auto res = cli_.Get("/with-range", Headers{
  5418. make_range_header({{-1, 2}}),
  5419. {"Accept-Encoding", ""},
  5420. });
  5421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5422. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5423. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5424. EXPECT_EQ(true, res->has_header("Content-Range"));
  5425. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5426. EXPECT_EQ(std::string("fg"), res->body);
  5427. }
  5428. TEST_F(ServerTest, GetWithRange5) {
  5429. auto res = cli_.Get("/with-range", Headers{
  5430. make_range_header({{0, 5}}),
  5431. {"Accept-Encoding", ""},
  5432. });
  5433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5434. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5435. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5436. EXPECT_EQ(true, res->has_header("Content-Range"));
  5437. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5438. EXPECT_EQ(std::string("abcdef"), res->body);
  5439. }
  5440. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5441. auto res =
  5442. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5444. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5445. }
  5446. TEST_F(ServerTest, GetWithRangeMultipart) {
  5447. auto res =
  5448. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5450. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5451. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5452. EXPECT_EQ(false, res->has_header("Content-Range"));
  5453. EXPECT_EQ(267U, res->body.size());
  5454. }
  5455. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5456. auto res = cli_.Get("/with-range",
  5457. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5460. }
  5461. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5462. auto res = cli_.Get("/with-range-customized-response",
  5463. Headers{{make_range_header({{1, 2}})}});
  5464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5465. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5466. EXPECT_EQ(true, res->has_header("Content-Length"));
  5467. EXPECT_EQ(false, res->has_header("Content-Range"));
  5468. EXPECT_EQ(JSON_DATA, res->body);
  5469. }
  5470. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5471. auto res = cli_.Get("/with-range-customized-response",
  5472. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5474. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5475. EXPECT_EQ(true, res->has_header("Content-Length"));
  5476. EXPECT_EQ(false, res->has_header("Content-Range"));
  5477. EXPECT_EQ(JSON_DATA, res->body);
  5478. }
  5479. TEST_F(ServerTest, Issue1772) {
  5480. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5482. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5483. }
  5484. TEST_F(ServerTest, Issue609) {
  5485. auto res = cli_.Delete("/issue609");
  5486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5487. EXPECT_EQ(StatusCode::OK_200, res->status);
  5488. EXPECT_EQ(std::string("ok"), res->body);
  5489. }
  5490. TEST_F(ServerTest, GetStreamedChunked) {
  5491. auto res = cli_.Get("/streamed-chunked");
  5492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5493. EXPECT_EQ(StatusCode::OK_200, res->status);
  5494. EXPECT_EQ(std::string("123456789"), res->body);
  5495. }
  5496. TEST_F(ServerTest, GetStreamedChunked2) {
  5497. auto res = cli_.Get("/streamed-chunked2");
  5498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5499. EXPECT_EQ(StatusCode::OK_200, res->status);
  5500. EXPECT_EQ(std::string("123456789"), res->body);
  5501. }
  5502. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5503. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5505. EXPECT_EQ(StatusCode::OK_200, res->status);
  5506. EXPECT_EQ(std::string("123456789"), res->body);
  5507. EXPECT_TRUE(res->has_header("Trailer"));
  5508. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5509. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5510. // Trailers are now stored separately from headers (security fix)
  5511. EXPECT_EQ(2U, res->trailers.size());
  5512. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5513. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5514. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5515. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5516. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5517. // Verify trailers are NOT in headers (security verification)
  5518. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5519. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5520. }
  5521. TEST_F(ServerTest, LargeChunkedPost) {
  5522. Request req;
  5523. req.method = "POST";
  5524. req.path = "/large-chunked";
  5525. std::string host_and_port;
  5526. host_and_port += HOST;
  5527. host_and_port += ":";
  5528. host_and_port += std::to_string(PORT);
  5529. req.headers.emplace("Host", host_and_port.c_str());
  5530. req.headers.emplace("Accept", "*/*");
  5531. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5532. req.headers.emplace("Content-Type", "text/plain");
  5533. req.headers.emplace("Content-Length", "0");
  5534. req.headers.emplace("Transfer-Encoding", "chunked");
  5535. std::string long_string(30 * 1024u, 'a');
  5536. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5537. // Attempt to make a large enough post to exceed OS buffers, to test that
  5538. // the server handles short reads if the full chunk data isn't available.
  5539. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5540. auto res = std::make_shared<Response>();
  5541. auto error = Error::Success;
  5542. auto ret = cli_.send(req, *res, error);
  5543. ASSERT_TRUE(ret);
  5544. EXPECT_EQ(StatusCode::OK_200, res->status);
  5545. }
  5546. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5547. auto res = cli_.Get("/remote_addr");
  5548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5549. EXPECT_EQ(StatusCode::OK_200, res->status);
  5550. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5551. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5552. }
  5553. TEST_F(ServerTest, GetMethodLocalAddr) {
  5554. auto res = cli_.Get("/local_addr");
  5555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5556. EXPECT_EQ(StatusCode::OK_200, res->status);
  5557. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5558. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5559. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5560. }
  5561. TEST_F(ServerTest, HTTPResponseSplitting) {
  5562. auto res = cli_.Get("/http_response_splitting");
  5563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5564. EXPECT_EQ(StatusCode::OK_200, res->status);
  5565. }
  5566. TEST_F(ServerTest, SlowRequest) {
  5567. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5568. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5569. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5570. }
  5571. #if 0
  5572. TEST_F(ServerTest, SlowPost) {
  5573. char buffer[64 * 1024];
  5574. memset(buffer, 0x42, sizeof(buffer));
  5575. auto res = cli_.Post(
  5576. "/slowpost", 64 * 1024 * 1024,
  5577. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5578. auto ret = sink.write(buffer, sizeof(buffer));
  5579. EXPECT_TRUE(ret);
  5580. return true;
  5581. },
  5582. "text/plain");
  5583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5584. EXPECT_EQ(StatusCode::OK_200, res->status);
  5585. }
  5586. TEST_F(ServerTest, SlowPostFail) {
  5587. char buffer[64 * 1024];
  5588. memset(buffer, 0x42, sizeof(buffer));
  5589. cli_.set_write_timeout(std::chrono::seconds(0));
  5590. auto res = cli_.Post(
  5591. "/slowpost", 64 * 1024 * 1024,
  5592. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5593. sink.write(buffer, sizeof(buffer));
  5594. return true;
  5595. },
  5596. "text/plain");
  5597. ASSERT_TRUE(!res);
  5598. EXPECT_EQ(Error::Write, res.error());
  5599. }
  5600. #endif
  5601. TEST_F(ServerTest, Put) {
  5602. auto res = cli_.Put("/put", "PUT", "text/plain");
  5603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5604. EXPECT_EQ(StatusCode::OK_200, res->status);
  5605. EXPECT_EQ("PUT", res->body);
  5606. }
  5607. TEST_F(ServerTest, PutWithContentProvider) {
  5608. auto res = cli_.Put(
  5609. "/put", 3,
  5610. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5611. sink.os << "PUT";
  5612. return true;
  5613. },
  5614. "text/plain");
  5615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5616. EXPECT_EQ(StatusCode::OK_200, res->status);
  5617. EXPECT_EQ("PUT", res->body);
  5618. }
  5619. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5620. auto res = cli_.Post(
  5621. "/post", 42,
  5622. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5623. return false;
  5624. },
  5625. "text/plain");
  5626. ASSERT_TRUE(!res);
  5627. EXPECT_EQ(Error::Canceled, res.error());
  5628. }
  5629. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5630. auto res = cli_.Put(
  5631. "/put",
  5632. [](size_t /*offset*/, DataSink &sink) {
  5633. sink.os << "PUT";
  5634. sink.done();
  5635. return true;
  5636. },
  5637. "text/plain");
  5638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5639. EXPECT_EQ(StatusCode::OK_200, res->status);
  5640. EXPECT_EQ("PUT", res->body);
  5641. }
  5642. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5643. auto res = cli_.Post(
  5644. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5645. "text/plain");
  5646. ASSERT_TRUE(!res);
  5647. EXPECT_EQ(Error::Canceled, res.error());
  5648. }
  5649. TEST_F(ServerTest, PostLoopBack) {
  5650. std::string body;
  5651. auto res = cli_.Post(
  5652. "/post-loopback", 9,
  5653. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5654. EXPECT_EQ(9u, length);
  5655. sink.write("123", 3);
  5656. sink.write("456", 3);
  5657. sink.write("789", 3);
  5658. return true;
  5659. },
  5660. "text/plain",
  5661. [&body](const char *data, size_t data_length) {
  5662. body.append(data, data_length);
  5663. return true;
  5664. });
  5665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5666. EXPECT_EQ(StatusCode::OK_200, res->status);
  5667. EXPECT_EQ("123456789", body);
  5668. }
  5669. TEST_F(ServerTest, PutLoopBack) {
  5670. std::string body;
  5671. auto res = cli_.Put(
  5672. "/put-loopback", 9,
  5673. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5674. EXPECT_EQ(9u, length);
  5675. sink.write("123", 3);
  5676. sink.write("456", 3);
  5677. sink.write("789", 3);
  5678. return true;
  5679. },
  5680. "text/plain",
  5681. [&body](const char *data, size_t data_length) {
  5682. body.append(data, data_length);
  5683. return true;
  5684. });
  5685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5686. EXPECT_EQ(StatusCode::OK_200, res->status);
  5687. EXPECT_EQ("123456789", body);
  5688. }
  5689. TEST_F(ServerTest, PatchLoopBack) {
  5690. std::string body;
  5691. auto res = cli_.Patch(
  5692. "/patch-loopback", 9,
  5693. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5694. EXPECT_EQ(9u, length);
  5695. sink.write("123", 3);
  5696. sink.write("456", 3);
  5697. sink.write("789", 3);
  5698. return true;
  5699. },
  5700. "text/plain",
  5701. [&body](const char *data, size_t data_length) {
  5702. body.append(data, data_length);
  5703. return true;
  5704. });
  5705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5706. EXPECT_EQ(StatusCode::OK_200, res->status);
  5707. EXPECT_EQ("123456789", body);
  5708. }
  5709. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5710. std::string body;
  5711. auto res = cli_.Post(
  5712. "/post-loopback",
  5713. [](size_t /*offset*/, DataSink &sink) {
  5714. sink.write("123", 3);
  5715. sink.write("456", 3);
  5716. sink.write("789", 3);
  5717. sink.done();
  5718. return true;
  5719. },
  5720. "text/plain",
  5721. [&body](const char *data, size_t data_length) {
  5722. body.append(data, data_length);
  5723. return true;
  5724. });
  5725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5726. EXPECT_EQ(StatusCode::OK_200, res->status);
  5727. EXPECT_EQ("123456789", body);
  5728. }
  5729. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5730. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5731. cli_.set_compress(true);
  5732. auto res = cli_.Put(
  5733. "/put", 3,
  5734. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5735. sink.os << "PUT";
  5736. return true;
  5737. },
  5738. "text/plain");
  5739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5740. EXPECT_EQ(StatusCode::OK_200, res->status);
  5741. EXPECT_EQ("PUT", res->body);
  5742. }
  5743. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5744. cli_.set_compress(true);
  5745. auto res = cli_.Post(
  5746. "/post", 42,
  5747. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5748. return false;
  5749. },
  5750. "text/plain");
  5751. ASSERT_TRUE(!res);
  5752. EXPECT_EQ(Error::Canceled, res.error());
  5753. }
  5754. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5755. cli_.set_compress(true);
  5756. auto res = cli_.Put(
  5757. "/put",
  5758. [](size_t /*offset*/, DataSink &sink) {
  5759. sink.os << "PUT";
  5760. sink.done();
  5761. return true;
  5762. },
  5763. "text/plain");
  5764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5765. EXPECT_EQ(StatusCode::OK_200, res->status);
  5766. EXPECT_EQ("PUT", res->body);
  5767. }
  5768. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5769. cli_.set_compress(true);
  5770. auto res = cli_.Post(
  5771. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5772. "text/plain");
  5773. ASSERT_TRUE(!res);
  5774. EXPECT_EQ(Error::Canceled, res.error());
  5775. }
  5776. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5777. cli_.set_compress(true);
  5778. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5780. EXPECT_EQ(StatusCode::OK_200, res->status);
  5781. EXPECT_EQ(LARGE_DATA, res->body);
  5782. }
  5783. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5784. #ifdef CPPHTTPLIB_SSL_ENABLED
  5785. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5786. Client cli(s.c_str());
  5787. cli.enable_server_certificate_verification(false);
  5788. #else
  5789. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5790. Client cli(s.c_str());
  5791. #endif
  5792. cli.set_compress(true);
  5793. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5795. EXPECT_EQ(StatusCode::OK_200, res->status);
  5796. EXPECT_EQ(LARGE_DATA, res->body);
  5797. // The compressed size should be less than a 10th of the original. May vary
  5798. // depending on the zlib library.
  5799. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5800. static_cast<uint64_t>(10 * 1024 * 1024));
  5801. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5802. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5803. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5804. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5805. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5806. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5807. #endif
  5808. }
  5809. TEST_F(ServerTest, PutContentWithDeflate) {
  5810. cli_.set_compress(false);
  5811. Headers headers;
  5812. headers.emplace("Content-Encoding", "deflate");
  5813. // PUT in deflate format:
  5814. auto res = cli_.Put("/put", headers,
  5815. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5817. EXPECT_EQ(StatusCode::OK_200, res->status);
  5818. EXPECT_EQ("PUT", res->body);
  5819. }
  5820. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5821. Headers headers;
  5822. headers.emplace("Accept-Encoding", "gzip, deflate");
  5823. auto res = cli_.Get("/streamed-chunked", headers);
  5824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5825. EXPECT_EQ(StatusCode::OK_200, res->status);
  5826. EXPECT_EQ(std::string("123456789"), res->body);
  5827. }
  5828. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5829. Headers headers;
  5830. headers.emplace("Accept-Encoding", "gzip, deflate");
  5831. auto res = cli_.Get("/streamed-chunked2", headers);
  5832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5833. EXPECT_EQ(StatusCode::OK_200, res->status);
  5834. EXPECT_EQ(std::string("123456789"), res->body);
  5835. }
  5836. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5837. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5839. EXPECT_EQ(StatusCode::OK_200, res->status);
  5840. }
  5841. TEST(GzipDecompressor, ChunkedDecompression) {
  5842. std::string data;
  5843. for (size_t i = 0; i < 32 * 1024; ++i) {
  5844. data.push_back(static_cast<char>('a' + i % 26));
  5845. }
  5846. std::string compressed_data;
  5847. {
  5848. httplib::detail::gzip_compressor compressor;
  5849. bool result = compressor.compress(
  5850. data.data(), data.size(),
  5851. /*last=*/true,
  5852. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5853. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5854. compressed_data_size);
  5855. return true;
  5856. });
  5857. ASSERT_TRUE(result);
  5858. }
  5859. std::string decompressed_data;
  5860. {
  5861. httplib::detail::gzip_decompressor decompressor;
  5862. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5863. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5864. size_t chunk_size = 130;
  5865. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5866. chunk_begin += chunk_size) {
  5867. size_t current_chunk_size =
  5868. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5869. bool result = decompressor.decompress(
  5870. compressed_data.data() + chunk_begin, current_chunk_size,
  5871. [&](const char *decompressed_data_chunk,
  5872. size_t decompressed_data_chunk_size) {
  5873. decompressed_data.insert(decompressed_data.size(),
  5874. decompressed_data_chunk,
  5875. decompressed_data_chunk_size);
  5876. return true;
  5877. });
  5878. ASSERT_TRUE(result);
  5879. }
  5880. }
  5881. ASSERT_EQ(data, decompressed_data);
  5882. }
  5883. TEST(GzipDecompressor, DeflateDecompression) {
  5884. std::string original_text = "Raw deflate without gzip";
  5885. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5886. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5887. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5888. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5889. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5890. std::string decompressed_data;
  5891. {
  5892. httplib::detail::gzip_decompressor decompressor;
  5893. bool result = decompressor.decompress(
  5894. compressed_data.data(), compressed_data.size(),
  5895. [&](const char *decompressed_data_chunk,
  5896. size_t decompressed_data_chunk_size) {
  5897. decompressed_data.insert(decompressed_data.size(),
  5898. decompressed_data_chunk,
  5899. decompressed_data_chunk_size);
  5900. return true;
  5901. });
  5902. ASSERT_TRUE(result);
  5903. }
  5904. ASSERT_EQ(original_text, decompressed_data);
  5905. }
  5906. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5907. std::string original_text = "Raw deflate without gzip";
  5908. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5909. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5910. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5911. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5912. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5913. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5914. std::string decompressed_data;
  5915. {
  5916. httplib::detail::gzip_decompressor decompressor;
  5917. bool result = decompressor.decompress(
  5918. compressed_data.data(), compressed_data.size(),
  5919. [&](const char *decompressed_data_chunk,
  5920. size_t decompressed_data_chunk_size) {
  5921. decompressed_data.insert(decompressed_data.size(),
  5922. decompressed_data_chunk,
  5923. decompressed_data_chunk_size);
  5924. return true;
  5925. });
  5926. ASSERT_TRUE(result);
  5927. }
  5928. ASSERT_EQ(original_text, decompressed_data);
  5929. }
  5930. #endif
  5931. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5932. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5933. Headers headers;
  5934. headers.emplace("Accept-Encoding", "br");
  5935. auto res = cli_.Get("/streamed-chunked", headers);
  5936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5937. EXPECT_EQ(StatusCode::OK_200, res->status);
  5938. EXPECT_EQ(std::string("123456789"), res->body);
  5939. }
  5940. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5941. Headers headers;
  5942. headers.emplace("Accept-Encoding", "br");
  5943. auto res = cli_.Get("/streamed-chunked2", headers);
  5944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5945. EXPECT_EQ(StatusCode::OK_200, res->status);
  5946. EXPECT_EQ(std::string("123456789"), res->body);
  5947. }
  5948. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5949. cli_.set_compress(true);
  5950. auto res = cli_.Put(
  5951. "/put", 3,
  5952. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5953. sink.os << "PUT";
  5954. return true;
  5955. },
  5956. "text/plain");
  5957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5958. EXPECT_EQ(StatusCode::OK_200, res->status);
  5959. EXPECT_EQ("PUT", res->body);
  5960. }
  5961. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5962. cli_.set_compress(true);
  5963. auto res = cli_.Put(
  5964. "/put",
  5965. [](size_t /*offset*/, DataSink &sink) {
  5966. sink.os << "PUT";
  5967. sink.done();
  5968. return true;
  5969. },
  5970. "text/plain");
  5971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5972. EXPECT_EQ(StatusCode::OK_200, res->status);
  5973. EXPECT_EQ("PUT", res->body);
  5974. }
  5975. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5976. cli_.set_compress(true);
  5977. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5979. EXPECT_EQ(StatusCode::OK_200, res->status);
  5980. EXPECT_EQ(LARGE_DATA, res->body);
  5981. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5982. }
  5983. #endif
  5984. TEST_F(ServerTest, Patch) {
  5985. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5987. EXPECT_EQ(StatusCode::OK_200, res->status);
  5988. EXPECT_EQ("PATCH", res->body);
  5989. }
  5990. TEST_F(ServerTest, Delete) {
  5991. auto res = cli_.Delete("/delete");
  5992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5993. EXPECT_EQ(StatusCode::OK_200, res->status);
  5994. EXPECT_EQ("DELETE", res->body);
  5995. }
  5996. TEST_F(ServerTest, DeleteContentReceiver) {
  5997. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5999. EXPECT_EQ(StatusCode::OK_200, res->status);
  6000. EXPECT_EQ("content", res->body);
  6001. }
  6002. TEST_F(ServerTest, Options) {
  6003. auto res = cli_.Options("*");
  6004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6005. EXPECT_EQ(StatusCode::OK_200, res->status);
  6006. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6007. EXPECT_TRUE(res->body.empty());
  6008. }
  6009. TEST_F(ServerTest, URL) {
  6010. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6012. EXPECT_EQ(StatusCode::OK_200, res->status);
  6013. }
  6014. TEST_F(ServerTest, ArrayParam) {
  6015. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6017. EXPECT_EQ(StatusCode::OK_200, res->status);
  6018. }
  6019. TEST_F(ServerTest, ArrayParamValues) {
  6020. auto res =
  6021. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6023. EXPECT_EQ(StatusCode::OK_200, res->status);
  6024. }
  6025. TEST_F(ServerTest, NoMultipleHeaders) {
  6026. Headers headers = {{"Content-Length", "5"}};
  6027. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6028. "text/plain");
  6029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6030. EXPECT_EQ(StatusCode::OK_200, res->status);
  6031. }
  6032. TEST_F(ServerTest, PostContentReceiver) {
  6033. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6035. ASSERT_EQ(StatusCode::OK_200, res->status);
  6036. ASSERT_EQ("content", res->body);
  6037. }
  6038. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6039. UploadFormDataItems items = {
  6040. {"text1", "text default", "", ""},
  6041. {"text2", "aωb", "", ""},
  6042. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6043. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6044. {"file3", "", "", "application/octet-stream"},
  6045. };
  6046. auto res = cli_.Post("/content_receiver", items);
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. EXPECT_EQ(StatusCode::OK_200, res->status);
  6049. }
  6050. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6051. UploadFormDataItems items = {
  6052. {"text1", "text default", "", ""},
  6053. {"text2", "aωb", "", ""},
  6054. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6055. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6056. {"file3", "", "", "application/octet-stream"},
  6057. };
  6058. auto boundary = std::string("+++++");
  6059. std::string body;
  6060. for (const auto &item : items) {
  6061. body += "--" + boundary + "\r\n";
  6062. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6063. if (!item.filename.empty()) {
  6064. body += "; filename=\"" + item.filename + "\"";
  6065. }
  6066. body += "\r\n";
  6067. if (!item.content_type.empty()) {
  6068. body += "Content-Type: " + item.content_type + "\r\n";
  6069. }
  6070. body += "\r\n";
  6071. body += item.content + "\r\n";
  6072. }
  6073. body += "--" + boundary + "--\r\n";
  6074. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6075. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. EXPECT_EQ(StatusCode::OK_200, res->status);
  6078. }
  6079. TEST(MultipartFormDataTest, FieldEscaping) {
  6080. Server svr;
  6081. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6082. const ContentReader &content_reader) {
  6083. ASSERT_TRUE(req.is_multipart_form_data());
  6084. std::vector<FormData> received;
  6085. content_reader(
  6086. [&](const FormData &file) {
  6087. received.push_back(file);
  6088. return true;
  6089. },
  6090. [&](const char *data, size_t data_length) {
  6091. received.back().content.append(data, data_length);
  6092. return true;
  6093. });
  6094. // '"', CR and LF in names and filenames are escaped following the
  6095. // WHATWG HTML standard, so each part still parses as a single part
  6096. // with no injected headers. Content types get CR/LF escaped too,
  6097. // while '"' (legal there, e.g. quoted charset) is preserved.
  6098. ASSERT_EQ(4U, received.size());
  6099. EXPECT_EQ("na%22me", received[0].name);
  6100. EXPECT_EQ("quoted name", received[0].content);
  6101. EXPECT_EQ("file", received[1].name);
  6102. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6103. received[1].filename);
  6104. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6105. EXPECT_EQ("injected", received[1].content);
  6106. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6107. EXPECT_EQ("my%22file.txt", received[2].filename);
  6108. EXPECT_EQ("cr lf name", received[2].content);
  6109. EXPECT_EQ("typed", received[3].name);
  6110. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6111. received[3].content_type);
  6112. EXPECT_EQ("typed content", received[3].content);
  6113. });
  6114. auto port = svr.bind_to_any_port("localhost");
  6115. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6116. auto se = detail::scope_exit([&] {
  6117. svr.stop();
  6118. t.join();
  6119. ASSERT_FALSE(svr.is_running());
  6120. });
  6121. svr.wait_until_ready();
  6122. Client cli("localhost", port);
  6123. UploadFormDataItems items = {
  6124. {"na\"me", "quoted name", "", ""},
  6125. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6126. "application/octet-stream"},
  6127. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6128. {"typed", "typed content", "",
  6129. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6130. };
  6131. auto res = cli.Post("/post", items);
  6132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6133. EXPECT_EQ(StatusCode::OK_200, res->status);
  6134. }
  6135. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6136. const UploadFormDataItems items = {
  6137. {"name1", "Content 1", "", ""},
  6138. {"name2", "Content 2", "file2.txt", "text/plain"},
  6139. };
  6140. Server svr;
  6141. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6142. const ContentReader &content_reader) {
  6143. ASSERT_TRUE(req.is_multipart_form_data());
  6144. std::vector<FormData> received;
  6145. content_reader(
  6146. [&](const FormData &file) {
  6147. received.push_back(file);
  6148. return true;
  6149. },
  6150. [&](const char *data, size_t data_length) {
  6151. received.back().content.append(data, data_length);
  6152. return true;
  6153. });
  6154. ASSERT_EQ(2U, received.size());
  6155. EXPECT_EQ("name1", received[0].name);
  6156. EXPECT_EQ("Content 1", received[0].content);
  6157. EXPECT_EQ("name2", received[1].name);
  6158. EXPECT_EQ("Content 2", received[1].content);
  6159. EXPECT_EQ("file2.txt", received[1].filename);
  6160. EXPECT_EQ("text/plain", received[1].content_type);
  6161. });
  6162. auto port = svr.bind_to_any_port("localhost");
  6163. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6164. auto se = detail::scope_exit([&] {
  6165. svr.stop();
  6166. t.join();
  6167. ASSERT_FALSE(svr.is_running());
  6168. });
  6169. svr.wait_until_ready();
  6170. Client cli("localhost", port);
  6171. // Whole-body serialization with a generated boundary
  6172. {
  6173. MultipartFormDataWriter writer;
  6174. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6175. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6176. writer.content_type());
  6177. auto body = writer.serialize(items);
  6178. EXPECT_EQ(body.size(), writer.content_length(items));
  6179. auto res = cli.Post("/post", body, writer.content_type());
  6180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6181. EXPECT_EQ(StatusCode::OK_200, res->status);
  6182. }
  6183. // Per-part framing with a custom boundary via a content provider
  6184. {
  6185. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6186. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6187. MultipartFormDataWriter writer("custom-boundary_123");
  6188. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6189. std::string body;
  6190. for (const auto &item : items) {
  6191. body += writer.item_begin(item);
  6192. body += item.content;
  6193. body += MultipartFormDataWriter::item_end();
  6194. }
  6195. body += writer.finish();
  6196. EXPECT_EQ(body.size(), writer.content_length(items));
  6197. auto res = cli.Post(
  6198. "/post", body.size(),
  6199. [&](size_t offset, size_t length, DataSink &sink) {
  6200. sink.write(body.data() + offset, length);
  6201. return true;
  6202. },
  6203. writer.content_type());
  6204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6205. EXPECT_EQ(StatusCode::OK_200, res->status);
  6206. }
  6207. }
  6208. TEST_F(ServerTest, PostContentReceiverGzip) {
  6209. cli_.set_compress(true);
  6210. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6212. ASSERT_EQ(StatusCode::OK_200, res->status);
  6213. ASSERT_EQ("content", res->body);
  6214. }
  6215. TEST_F(ServerTest, PutContentReceiver) {
  6216. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6218. ASSERT_EQ(StatusCode::OK_200, res->status);
  6219. ASSERT_EQ("content", res->body);
  6220. }
  6221. TEST_F(ServerTest, PatchContentReceiver) {
  6222. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. ASSERT_EQ(StatusCode::OK_200, res->status);
  6225. ASSERT_EQ("content", res->body);
  6226. }
  6227. template <typename ClientType>
  6228. void TestWithHeadersAndContentReceiver(
  6229. ClientType &cli,
  6230. std::function<Result(ClientType &, const std::string &, const Headers &,
  6231. const std::string &, const std::string &,
  6232. ContentReceiver, DownloadProgress)>
  6233. request_func) {
  6234. Headers headers;
  6235. headers.emplace("X-Custom-Header", "test-value");
  6236. std::string received_body;
  6237. auto res = request_func(
  6238. cli, "/content_receiver", headers, "content", "application/json",
  6239. [&](const char *data, size_t data_length) {
  6240. received_body.append(data, data_length);
  6241. return true;
  6242. },
  6243. nullptr);
  6244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6245. EXPECT_EQ(StatusCode::OK_200, res->status);
  6246. EXPECT_EQ("content", received_body);
  6247. }
  6248. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6249. #ifdef CPPHTTPLIB_SSL_ENABLED
  6250. using ClientT = SSLClient;
  6251. #else
  6252. using ClientT = Client;
  6253. #endif
  6254. TestWithHeadersAndContentReceiver<ClientT>(
  6255. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6256. const std::string &body, const std::string &content_type,
  6257. ContentReceiver receiver, DownloadProgress progress) {
  6258. return cli.Post(path, headers, body, content_type, receiver, progress);
  6259. });
  6260. }
  6261. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6262. #ifdef CPPHTTPLIB_SSL_ENABLED
  6263. using ClientT = SSLClient;
  6264. #else
  6265. using ClientT = Client;
  6266. #endif
  6267. TestWithHeadersAndContentReceiver<ClientT>(
  6268. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6269. const std::string &body, const std::string &content_type,
  6270. ContentReceiver receiver, DownloadProgress progress) {
  6271. return cli.Put(path, headers, body, content_type, receiver, progress);
  6272. });
  6273. }
  6274. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6275. #ifdef CPPHTTPLIB_SSL_ENABLED
  6276. using ClientT = SSLClient;
  6277. #else
  6278. using ClientT = Client;
  6279. #endif
  6280. TestWithHeadersAndContentReceiver<ClientT>(
  6281. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6282. const std::string &body, const std::string &content_type,
  6283. ContentReceiver receiver, DownloadProgress progress) {
  6284. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6285. });
  6286. }
  6287. template <typename ClientType>
  6288. void TestWithHeadersAndContentReceiverWithProgress(
  6289. ClientType &cli,
  6290. std::function<Result(ClientType &, const std::string &, const Headers &,
  6291. const std::string &, const std::string &,
  6292. ContentReceiver, DownloadProgress)>
  6293. request_func) {
  6294. Headers headers;
  6295. headers.emplace("X-Test-Header", "progress-test");
  6296. std::string received_body;
  6297. auto progress_called = false;
  6298. auto res = request_func(
  6299. cli, "/content_receiver", headers, "content", "text/plain",
  6300. [&](const char *data, size_t data_length) {
  6301. received_body.append(data, data_length);
  6302. return true;
  6303. },
  6304. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6305. progress_called = true;
  6306. return true;
  6307. });
  6308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6309. EXPECT_EQ(StatusCode::OK_200, res->status);
  6310. EXPECT_EQ("content", received_body);
  6311. EXPECT_TRUE(progress_called);
  6312. }
  6313. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6314. #ifdef CPPHTTPLIB_SSL_ENABLED
  6315. using ClientT = SSLClient;
  6316. #else
  6317. using ClientT = Client;
  6318. #endif
  6319. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6320. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6321. const std::string &body, const std::string &content_type,
  6322. ContentReceiver receiver, DownloadProgress progress) {
  6323. return cli.Post(path, headers, body, content_type, receiver, progress);
  6324. });
  6325. }
  6326. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6327. #ifdef CPPHTTPLIB_SSL_ENABLED
  6328. using ClientT = SSLClient;
  6329. #else
  6330. using ClientT = Client;
  6331. #endif
  6332. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6333. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6334. const std::string &body, const std::string &content_type,
  6335. ContentReceiver receiver, DownloadProgress progress) {
  6336. return cli.Put(path, headers, body, content_type, receiver, progress);
  6337. });
  6338. }
  6339. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6340. #ifdef CPPHTTPLIB_SSL_ENABLED
  6341. using ClientT = SSLClient;
  6342. #else
  6343. using ClientT = Client;
  6344. #endif
  6345. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6346. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6347. const std::string &body, const std::string &content_type,
  6348. ContentReceiver receiver, DownloadProgress progress) {
  6349. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6350. });
  6351. }
  6352. template <typename ClientType>
  6353. void TestWithHeadersAndContentReceiverError(
  6354. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6355. const Headers &, const std::string &,
  6356. const std::string &, ContentReceiver)>
  6357. request_func) {
  6358. Headers headers;
  6359. headers.emplace("X-Error-Test", "true");
  6360. std::string received_body;
  6361. auto receiver_failed = false;
  6362. auto res =
  6363. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6364. [&](const char *data, size_t data_length) {
  6365. received_body.append(data, data_length);
  6366. receiver_failed = true;
  6367. return false;
  6368. });
  6369. ASSERT_FALSE(res);
  6370. EXPECT_TRUE(receiver_failed);
  6371. }
  6372. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6373. #ifdef CPPHTTPLIB_SSL_ENABLED
  6374. using ClientT = SSLClient;
  6375. #else
  6376. using ClientT = Client;
  6377. #endif
  6378. TestWithHeadersAndContentReceiverError<ClientT>(
  6379. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6380. const std::string &body, const std::string &content_type,
  6381. ContentReceiver receiver) {
  6382. return cli.Post(path, headers, body, content_type, receiver);
  6383. });
  6384. }
  6385. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6386. #ifdef CPPHTTPLIB_SSL_ENABLED
  6387. using ClientT = SSLClient;
  6388. #else
  6389. using ClientT = Client;
  6390. #endif
  6391. TestWithHeadersAndContentReceiverError<ClientT>(
  6392. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6393. const std::string &body, const std::string &content_type,
  6394. ContentReceiver receiver) {
  6395. return cli.Put(path, headers, body, content_type, receiver);
  6396. });
  6397. }
  6398. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6399. #ifdef CPPHTTPLIB_SSL_ENABLED
  6400. using ClientT = SSLClient;
  6401. #else
  6402. using ClientT = Client;
  6403. #endif
  6404. TestWithHeadersAndContentReceiverError<ClientT>(
  6405. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6406. const std::string &body, const std::string &content_type,
  6407. ContentReceiver receiver) {
  6408. return cli.Patch(path, headers, body, content_type, receiver);
  6409. });
  6410. }
  6411. TEST_F(ServerTest, PostQueryStringAndBody) {
  6412. auto res =
  6413. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6415. ASSERT_EQ(StatusCode::OK_200, res->status);
  6416. }
  6417. TEST_F(ServerTest, HTTP2Magic) {
  6418. Request req;
  6419. req.method = "PRI";
  6420. req.path = "*";
  6421. req.body = "SM";
  6422. auto res = std::make_shared<Response>();
  6423. auto error = Error::Success;
  6424. auto ret = cli_.send(req, *res, error);
  6425. ASSERT_TRUE(ret);
  6426. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6427. }
  6428. TEST_F(ServerTest, KeepAlive) {
  6429. auto res = cli_.Get("/hi");
  6430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6431. EXPECT_EQ(StatusCode::OK_200, res->status);
  6432. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6433. EXPECT_EQ("Hello World!", res->body);
  6434. res = cli_.Get("/hi");
  6435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6436. EXPECT_EQ(StatusCode::OK_200, res->status);
  6437. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6438. EXPECT_EQ("Hello World!", res->body);
  6439. res = cli_.Get("/hi");
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6443. EXPECT_EQ("Hello World!", res->body);
  6444. res = cli_.Get("/not-exist");
  6445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6446. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6447. res = cli_.Post("/empty", "", "text/plain");
  6448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6449. EXPECT_EQ(StatusCode::OK_200, res->status);
  6450. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6451. EXPECT_EQ("empty", res->body);
  6452. EXPECT_EQ("close", res->get_header_value("Connection"));
  6453. res = cli_.Post(
  6454. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6455. "text/plain");
  6456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6457. EXPECT_EQ(StatusCode::OK_200, res->status);
  6458. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6459. EXPECT_EQ("empty", res->body);
  6460. cli_.set_keep_alive(false);
  6461. res = cli_.Get("/last-request");
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. EXPECT_EQ(StatusCode::OK_200, res->status);
  6464. EXPECT_EQ("close", res->get_header_value("Connection"));
  6465. }
  6466. TEST_F(ServerTest, TooManyRedirect) {
  6467. cli_.set_follow_location(true);
  6468. auto res = cli_.Get("/redirect/0");
  6469. ASSERT_TRUE(!res);
  6470. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6471. }
  6472. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6473. Request req;
  6474. req.method = "FOOBAR";
  6475. req.path = "/hi";
  6476. cli_.set_keep_alive(true);
  6477. auto res = cli_.send(req);
  6478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6479. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6480. EXPECT_EQ("close", res->get_header_value("Connection"));
  6481. EXPECT_FALSE(cli_.is_socket_open());
  6482. }
  6483. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6484. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6485. TEST_F(ServerTest, Gzip) {
  6486. Headers headers;
  6487. headers.emplace("Accept-Encoding", "gzip, deflate");
  6488. auto res = cli_.Get("/compress", headers);
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6491. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6492. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6493. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6494. "7890123456789012345678901234567890",
  6495. res->body);
  6496. EXPECT_EQ(StatusCode::OK_200, res->status);
  6497. }
  6498. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6499. Headers headers;
  6500. headers.emplace("Accept-Encoding", "gzip, deflate");
  6501. auto res = cli_.Get("/compress-with-charset", headers);
  6502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6503. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6504. EXPECT_EQ("application/json; charset=utf-8",
  6505. res->get_header_value("Content-Type"));
  6506. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6507. "7890123456789012345678901234567890",
  6508. res->body);
  6509. EXPECT_EQ(StatusCode::OK_200, res->status);
  6510. }
  6511. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6512. Headers headers;
  6513. headers.emplace("Accept-Encoding", "");
  6514. auto res = cli_.Get("/compress", headers);
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6517. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6518. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6519. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6520. "7890123456789012345678901234567890",
  6521. res->body);
  6522. EXPECT_EQ(StatusCode::OK_200, res->status);
  6523. }
  6524. TEST_F(ServerTest, GzipWithContentReceiver) {
  6525. Headers headers;
  6526. headers.emplace("Accept-Encoding", "gzip, deflate");
  6527. std::string body;
  6528. auto res = cli_.Get("/compress", headers,
  6529. [&](const char *data, uint64_t data_length) {
  6530. EXPECT_EQ(100U, data_length);
  6531. body.append(data, data_length);
  6532. return true;
  6533. });
  6534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6535. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6536. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6537. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6538. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6539. "7890123456789012345678901234567890",
  6540. body);
  6541. EXPECT_EQ(StatusCode::OK_200, res->status);
  6542. }
  6543. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6544. Headers headers;
  6545. headers.emplace("Accept-Encoding", "gzip, deflate");
  6546. cli_.set_decompress(false);
  6547. auto res = cli_.Get("/compress", headers);
  6548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6549. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6550. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6551. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6552. EXPECT_EQ(33U, res->body.size());
  6553. EXPECT_EQ(StatusCode::OK_200, res->status);
  6554. }
  6555. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6556. Headers headers;
  6557. headers.emplace("Accept-Encoding", "");
  6558. std::string body;
  6559. auto res = cli_.Get("/compress", headers,
  6560. [&](const char *data, uint64_t data_length) {
  6561. EXPECT_EQ(100U, data_length);
  6562. body.append(data, data_length);
  6563. return true;
  6564. });
  6565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6566. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6567. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6568. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6569. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6570. "7890123456789012345678901234567890",
  6571. body);
  6572. EXPECT_EQ(StatusCode::OK_200, res->status);
  6573. }
  6574. TEST_F(ServerTest, NoGzip) {
  6575. Headers headers;
  6576. headers.emplace("Accept-Encoding", "gzip, deflate");
  6577. auto res = cli_.Get("/nocompress", headers);
  6578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6579. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6580. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6581. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6582. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6583. "7890123456789012345678901234567890",
  6584. res->body);
  6585. EXPECT_EQ(StatusCode::OK_200, res->status);
  6586. }
  6587. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6588. Headers headers;
  6589. headers.emplace("Accept-Encoding", "gzip, deflate");
  6590. std::string body;
  6591. auto res = cli_.Get("/nocompress", headers,
  6592. [&](const char *data, uint64_t data_length) {
  6593. EXPECT_EQ(100U, data_length);
  6594. body.append(data, data_length);
  6595. return true;
  6596. });
  6597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6598. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6599. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6600. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6601. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6602. "7890123456789012345678901234567890",
  6603. body);
  6604. EXPECT_EQ(StatusCode::OK_200, res->status);
  6605. }
  6606. TEST_F(ServerTest, MultipartFormDataGzip) {
  6607. UploadFormDataItems items = {
  6608. {"key1", "test", "", ""},
  6609. {"key2", "--abcdefg123", "", ""},
  6610. };
  6611. cli_.set_compress(true);
  6612. auto res = cli_.Post("/compress-multipart", items);
  6613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6614. EXPECT_EQ(StatusCode::OK_200, res->status);
  6615. }
  6616. #endif
  6617. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6618. TEST_F(ServerTest, Brotli) {
  6619. Headers headers;
  6620. headers.emplace("Accept-Encoding", "br");
  6621. auto res = cli_.Get("/compress", headers);
  6622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6623. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6624. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6625. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6626. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6627. "7890123456789012345678901234567890",
  6628. res->body);
  6629. EXPECT_EQ(StatusCode::OK_200, res->status);
  6630. }
  6631. #endif
  6632. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6633. TEST_F(ServerTest, Zstd) {
  6634. Headers headers;
  6635. headers.emplace("Accept-Encoding", "zstd");
  6636. auto res = cli_.Get("/compress", headers);
  6637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6638. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6639. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6640. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6641. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6642. "7890123456789012345678901234567890",
  6643. res->body);
  6644. EXPECT_EQ(StatusCode::OK_200, res->status);
  6645. }
  6646. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6647. Headers headers;
  6648. headers.emplace("Accept-Encoding", "");
  6649. auto res = cli_.Get("/compress", headers);
  6650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6651. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6652. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6653. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6654. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6655. "7890123456789012345678901234567890",
  6656. res->body);
  6657. EXPECT_EQ(StatusCode::OK_200, res->status);
  6658. }
  6659. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6660. Headers headers;
  6661. headers.emplace("Accept-Encoding", "zstd");
  6662. std::string body;
  6663. auto res = cli_.Get("/compress", headers,
  6664. [&](const char *data, uint64_t data_length) {
  6665. EXPECT_EQ(100U, data_length);
  6666. body.append(data, data_length);
  6667. return true;
  6668. });
  6669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6670. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6671. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6672. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6673. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6674. "7890123456789012345678901234567890",
  6675. body);
  6676. EXPECT_EQ(StatusCode::OK_200, res->status);
  6677. }
  6678. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6679. Headers headers;
  6680. headers.emplace("Accept-Encoding", "zstd");
  6681. cli_.set_decompress(false);
  6682. auto res = cli_.Get("/compress", headers);
  6683. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6684. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6685. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6686. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6688. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6689. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6690. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6691. EXPECT_EQ(StatusCode::OK_200, res->status);
  6692. ASSERT_EQ(26U, res->body.size());
  6693. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6694. 0);
  6695. }
  6696. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6697. Headers headers;
  6698. headers.emplace("Accept-Encoding", "");
  6699. std::string body;
  6700. auto res = cli_.Get("/compress", headers,
  6701. [&](const char *data, uint64_t data_length) {
  6702. EXPECT_EQ(100U, data_length);
  6703. body.append(data, data_length);
  6704. return true;
  6705. });
  6706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6707. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6708. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6709. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6710. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6711. "7890123456789012345678901234567890",
  6712. body);
  6713. EXPECT_EQ(StatusCode::OK_200, res->status);
  6714. }
  6715. TEST_F(ServerTest, NoZstd) {
  6716. Headers headers;
  6717. headers.emplace("Accept-Encoding", "zstd");
  6718. auto res = cli_.Get("/nocompress", headers);
  6719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6720. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6721. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6722. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6723. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6724. "7890123456789012345678901234567890",
  6725. res->body);
  6726. EXPECT_EQ(StatusCode::OK_200, res->status);
  6727. }
  6728. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6729. Headers headers;
  6730. headers.emplace("Accept-Encoding", "zstd");
  6731. std::string body;
  6732. auto res = cli_.Get("/nocompress", headers,
  6733. [&](const char *data, uint64_t data_length) {
  6734. EXPECT_EQ(100U, data_length);
  6735. body.append(data, data_length);
  6736. return true;
  6737. });
  6738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6739. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6740. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6741. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6742. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6743. "7890123456789012345678901234567890",
  6744. body);
  6745. EXPECT_EQ(StatusCode::OK_200, res->status);
  6746. }
  6747. // TODO: How to enable zstd ??
  6748. TEST_F(ServerTest, MultipartFormDataZstd) {
  6749. UploadFormDataItems items = {
  6750. {"key1", "test", "", ""},
  6751. {"key2", "--abcdefg123", "", ""},
  6752. };
  6753. Headers headers;
  6754. headers.emplace("Accept-Encoding", "zstd");
  6755. cli_.set_compress(true);
  6756. auto res = cli_.Post("/compress-multipart", headers, items);
  6757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6758. EXPECT_EQ(StatusCode::OK_200, res->status);
  6759. }
  6760. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6761. Headers headers;
  6762. headers.emplace("Accept-Encoding", "zstd");
  6763. cli_.set_compress(true);
  6764. auto res = cli_.Put(
  6765. "/put", headers, 3,
  6766. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6767. sink.os << "PUT";
  6768. return true;
  6769. },
  6770. "text/plain");
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::OK_200, res->status);
  6773. EXPECT_EQ("PUT", res->body);
  6774. }
  6775. // Pre-compression logging tests
  6776. TEST_F(ServerTest, PreCompressionLogging) {
  6777. // Test data for compression (matches the actual /compress endpoint content)
  6778. const std::string test_content =
  6779. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6780. "3456789012345678901234567890";
  6781. // Variables to capture logging data
  6782. std::string pre_compression_body;
  6783. std::string pre_compression_content_type;
  6784. std::string pre_compression_content_encoding;
  6785. std::string post_compression_body;
  6786. std::string post_compression_content_type;
  6787. std::string post_compression_content_encoding;
  6788. // Set up pre-compression logger
  6789. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6790. const Response &res) {
  6791. pre_compression_body = res.body;
  6792. pre_compression_content_type = res.get_header_value("Content-Type");
  6793. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6794. });
  6795. // Set up post-compression logger
  6796. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6797. post_compression_body = res.body;
  6798. post_compression_content_type = res.get_header_value("Content-Type");
  6799. post_compression_content_encoding =
  6800. res.get_header_value("Content-Encoding");
  6801. });
  6802. // Test with gzip compression
  6803. Headers headers;
  6804. headers.emplace("Accept-Encoding", "gzip");
  6805. auto res = cli_.Get("/compress", headers);
  6806. // Verify response was compressed
  6807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6808. EXPECT_EQ(StatusCode::OK_200, res->status);
  6809. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6810. // Verify pre-compression logger captured uncompressed content
  6811. EXPECT_EQ(test_content, pre_compression_body);
  6812. EXPECT_EQ("text/plain", pre_compression_content_type);
  6813. EXPECT_TRUE(pre_compression_content_encoding
  6814. .empty()); // No encoding header before compression
  6815. // Verify post-compression logger captured compressed content
  6816. EXPECT_NE(test_content,
  6817. post_compression_body); // Should be different after compression
  6818. EXPECT_EQ("text/plain", post_compression_content_type);
  6819. EXPECT_EQ("gzip", post_compression_content_encoding);
  6820. // Verify compressed content is smaller
  6821. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6822. }
  6823. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6824. const std::string test_content =
  6825. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6826. "3456789012345678901234567890";
  6827. std::string pre_compression_body;
  6828. std::string post_compression_body;
  6829. svr_.set_pre_compression_logger(
  6830. [&](const Request & /*req*/, const Response &res) {
  6831. pre_compression_body = res.body;
  6832. });
  6833. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6834. post_compression_body = res.body;
  6835. });
  6836. Headers headers;
  6837. headers.emplace("Accept-Encoding", "br");
  6838. auto res = cli_.Get("/compress", headers);
  6839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6840. EXPECT_EQ(StatusCode::OK_200, res->status);
  6841. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6842. // Verify pre-compression content is uncompressed
  6843. EXPECT_EQ(test_content, pre_compression_body);
  6844. // Verify post-compression content is compressed
  6845. EXPECT_NE(test_content, post_compression_body);
  6846. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6847. }
  6848. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6849. const std::string test_content =
  6850. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6851. "3456789012345678901234567890";
  6852. std::string pre_compression_body;
  6853. std::string post_compression_body;
  6854. svr_.set_pre_compression_logger(
  6855. [&](const Request & /*req*/, const Response &res) {
  6856. pre_compression_body = res.body;
  6857. });
  6858. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6859. post_compression_body = res.body;
  6860. });
  6861. // Request without compression (use /nocompress endpoint)
  6862. Headers headers;
  6863. auto res = cli_.Get("/nocompress", headers);
  6864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6865. EXPECT_EQ(StatusCode::OK_200, res->status);
  6866. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6867. // Pre-compression logger should not be called when no compression is applied
  6868. EXPECT_TRUE(
  6869. pre_compression_body.empty()); // Pre-compression logger not called
  6870. EXPECT_EQ(
  6871. test_content,
  6872. post_compression_body); // Post-compression logger captures final content
  6873. }
  6874. TEST_F(ServerTest, LoggerSeesContentLength) {
  6875. size_t logged_content_length = 0;
  6876. std::string logged_content_length_header;
  6877. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6878. logged_content_length = res.content_length_;
  6879. logged_content_length_header = res.get_header_value("Content-Length");
  6880. });
  6881. auto res = cli_.Get("/nocompress");
  6882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6883. EXPECT_EQ(StatusCode::OK_200, res->status);
  6884. EXPECT_EQ(res->body.size(), logged_content_length);
  6885. EXPECT_EQ(std::to_string(logged_content_length),
  6886. logged_content_length_header);
  6887. }
  6888. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6889. const std::string test_content =
  6890. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6891. "3456789012345678901234567890";
  6892. std::string pre_compression_body;
  6893. bool pre_logger_called = false;
  6894. // Set only pre-compression logger
  6895. svr_.set_pre_compression_logger(
  6896. [&](const Request & /*req*/, const Response &res) {
  6897. pre_compression_body = res.body;
  6898. pre_logger_called = true;
  6899. });
  6900. Headers headers;
  6901. headers.emplace("Accept-Encoding", "gzip");
  6902. auto res = cli_.Get("/compress", headers);
  6903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6904. EXPECT_EQ(StatusCode::OK_200, res->status);
  6905. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6906. // Verify pre-compression logger was called
  6907. EXPECT_TRUE(pre_logger_called);
  6908. EXPECT_EQ(test_content, pre_compression_body);
  6909. }
  6910. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6911. {
  6912. // Test with Expect: 100-continue header - success case
  6913. // Server returns 100 Continue, client sends body, server returns 200 OK
  6914. Request req;
  6915. req.method = "POST";
  6916. req.path = "/post-large";
  6917. req.set_header("Expect", "100-continue");
  6918. req.body = LARGE_DATA;
  6919. Response res;
  6920. auto error = Error::Success;
  6921. cli_.set_keep_alive(true);
  6922. auto ret = cli_.send(req, res, error);
  6923. EXPECT_TRUE(ret);
  6924. EXPECT_EQ(StatusCode::OK_200, res.status);
  6925. EXPECT_EQ(LARGE_DATA, res.body);
  6926. }
  6927. {
  6928. // Test with Expect: 100-continue header - error case
  6929. // Client should not send the body when server returns an error
  6930. Request req;
  6931. req.method = "POST";
  6932. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6933. req.set_header("Expect", "100-continue");
  6934. req.body = LARGE_DATA;
  6935. Response res;
  6936. auto error = Error::Success;
  6937. auto start = std::chrono::high_resolution_clock::now();
  6938. cli_.set_keep_alive(true);
  6939. auto ret = cli_.send(req, res, error);
  6940. auto end = std::chrono::high_resolution_clock::now();
  6941. auto elapsed =
  6942. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6943. .count();
  6944. // With Expect: 100-continue, request completes successfully but with error
  6945. EXPECT_TRUE(ret);
  6946. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6947. EXPECT_EQ("close", res.get_header_value("Connection"));
  6948. EXPECT_FALSE(cli_.is_socket_open());
  6949. EXPECT_LE(elapsed, 2000);
  6950. }
  6951. {
  6952. // Send an extra GET request to ensure error recovery without hanging
  6953. Request req;
  6954. req.method = "GET";
  6955. req.path = "/hi";
  6956. auto start = std::chrono::high_resolution_clock::now();
  6957. auto res = cli_.send(req);
  6958. auto end = std::chrono::high_resolution_clock::now();
  6959. auto elapsed =
  6960. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6961. .count();
  6962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6963. EXPECT_EQ(StatusCode::OK_200, res->status);
  6964. EXPECT_EQ("Hello World!", res->body);
  6965. EXPECT_LE(elapsed, 500);
  6966. }
  6967. }
  6968. TEST(ZstdDecompressor, ChunkedDecompression) {
  6969. std::string data;
  6970. for (size_t i = 0; i < 32 * 1024; ++i) {
  6971. data.push_back(static_cast<char>('a' + i % 26));
  6972. }
  6973. std::string compressed_data;
  6974. {
  6975. httplib::detail::zstd_compressor compressor;
  6976. bool result = compressor.compress(
  6977. data.data(), data.size(),
  6978. /*last=*/true,
  6979. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6980. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6981. compressed_data_size);
  6982. return true;
  6983. });
  6984. ASSERT_TRUE(result);
  6985. }
  6986. std::string decompressed_data;
  6987. {
  6988. httplib::detail::zstd_decompressor decompressor;
  6989. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6990. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6991. size_t chunk_size = 130;
  6992. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6993. chunk_begin += chunk_size) {
  6994. size_t current_chunk_size =
  6995. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6996. bool result = decompressor.decompress(
  6997. compressed_data.data() + chunk_begin, current_chunk_size,
  6998. [&](const char *decompressed_data_chunk,
  6999. size_t decompressed_data_chunk_size) {
  7000. decompressed_data.insert(decompressed_data.size(),
  7001. decompressed_data_chunk,
  7002. decompressed_data_chunk_size);
  7003. return true;
  7004. });
  7005. ASSERT_TRUE(result);
  7006. }
  7007. }
  7008. ASSERT_EQ(data, decompressed_data);
  7009. }
  7010. TEST(ZstdDecompressor, Decompress) {
  7011. std::string original_text = "Compressed with ZSTD";
  7012. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7013. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7014. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7015. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7016. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7017. std::string decompressed_data;
  7018. {
  7019. httplib::detail::zstd_decompressor decompressor;
  7020. bool result = decompressor.decompress(
  7021. compressed_data.data(), compressed_data.size(),
  7022. [&](const char *decompressed_data_chunk,
  7023. size_t decompressed_data_chunk_size) {
  7024. decompressed_data.insert(decompressed_data.size(),
  7025. decompressed_data_chunk,
  7026. decompressed_data_chunk_size);
  7027. return true;
  7028. });
  7029. ASSERT_TRUE(result);
  7030. }
  7031. ASSERT_EQ(original_text, decompressed_data);
  7032. }
  7033. #endif
  7034. // Sends a raw request to a server listening at HOST:PORT.
  7035. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7036. std::string *resp = nullptr) {
  7037. auto error = Error::Success;
  7038. auto client_sock = detail::create_client_socket(
  7039. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  7040. /*connection_timeout_sec=*/5, 0,
  7041. /*read_timeout_sec=*/5, 0,
  7042. /*write_timeout_sec=*/5, 0, std::string(), error);
  7043. if (client_sock == INVALID_SOCKET) { return false; }
  7044. auto ret = detail::process_client_socket(
  7045. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7046. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7047. if (req.size() !=
  7048. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  7049. return false;
  7050. }
  7051. char buf[512];
  7052. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7053. while (line_reader.getline()) {
  7054. if (resp) { *resp += line_reader.ptr(); }
  7055. }
  7056. return true;
  7057. });
  7058. detail::close_socket(client_sock);
  7059. return ret;
  7060. }
  7061. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7062. Server svr;
  7063. std::string header_value;
  7064. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7065. header_value = req.get_header_value("foo");
  7066. res.set_content("ok", "text/plain");
  7067. });
  7068. thread t = thread([&] { svr.listen(HOST, PORT); });
  7069. auto se = detail::scope_exit([&] {
  7070. svr.stop();
  7071. t.join();
  7072. ASSERT_FALSE(svr.is_running());
  7073. });
  7074. svr.wait_until_ready();
  7075. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7076. // like characters are not treated the same - use vertical tab and escape.
  7077. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7078. "foo: \t \v bar \x1B\t \r\n"
  7079. "Connection: close\r\n"
  7080. "\r\n";
  7081. std::string res;
  7082. ASSERT_TRUE(send_request(5, req, &res));
  7083. EXPECT_EQ(header_value, "");
  7084. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7085. }
  7086. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7087. Server svr;
  7088. std::string received;
  7089. svr.Get("/order", [&](const Request &req, Response &res) {
  7090. received = headers_to_string(req.headers);
  7091. res.set_content("ok", "text/plain");
  7092. });
  7093. thread t = thread([&] { svr.listen(HOST, PORT); });
  7094. auto se = detail::scope_exit([&] {
  7095. svr.stop();
  7096. t.join();
  7097. ASSERT_FALSE(svr.is_running());
  7098. });
  7099. svr.wait_until_ready();
  7100. const std::string req = "GET /order HTTP/1.1\r\n"
  7101. "X-First: 1\r\n"
  7102. "X-Dup: a\r\n"
  7103. "X-Second: 2\r\n"
  7104. "X-Dup: b\r\n"
  7105. "Connection: close\r\n"
  7106. "\r\n";
  7107. std::string res;
  7108. ASSERT_TRUE(send_request(5, req, &res));
  7109. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7110. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7111. }
  7112. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7113. Server svr;
  7114. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7115. res.set_header("Set-Cookie", "first=1");
  7116. res.set_header("X-Between", "y");
  7117. res.set_header("Set-Cookie", "second=2");
  7118. res.set_content("ok", "text/plain");
  7119. });
  7120. thread t = thread([&] { svr.listen(HOST, PORT); });
  7121. auto se = detail::scope_exit([&] {
  7122. svr.stop();
  7123. t.join();
  7124. ASSERT_FALSE(svr.is_running());
  7125. });
  7126. svr.wait_until_ready();
  7127. Client cli(HOST, PORT);
  7128. auto res = cli.Get("/cookies");
  7129. ASSERT_TRUE(res);
  7130. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7131. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7132. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7133. }
  7134. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7135. Server svr;
  7136. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7137. auto i = new int(0);
  7138. res.set_header("Trailer", "X-Safe, X-Reflected");
  7139. res.set_chunked_content_provider(
  7140. "text/plain",
  7141. [i](size_t /*offset*/, DataSink &sink) {
  7142. if (*i == 0) {
  7143. sink.os << "body";
  7144. } else {
  7145. Headers trailer;
  7146. // A valid trailer that must survive.
  7147. trailer.emplace("X-Safe", "safe");
  7148. // Attacker-controlled value carrying CR/LF (response splitting).
  7149. trailer.emplace("X-Reflected",
  7150. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7151. // Attacker-controlled name carrying CR/LF.
  7152. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7153. sink.done_with_trailer(trailer);
  7154. }
  7155. (*i)++;
  7156. return true;
  7157. },
  7158. [i](bool /*success*/) { delete i; });
  7159. });
  7160. thread t = thread([&] { svr.listen(HOST, PORT); });
  7161. auto se = detail::scope_exit([&] {
  7162. svr.stop();
  7163. t.join();
  7164. ASSERT_FALSE(svr.is_running());
  7165. });
  7166. svr.wait_until_ready();
  7167. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7168. "Host: " + HOST +
  7169. "\r\n"
  7170. "Connection: close\r\n"
  7171. "\r\n";
  7172. std::string res;
  7173. ASSERT_TRUE(send_request(5, req, &res));
  7174. // The injected fields must not appear anywhere in the raw response.
  7175. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7176. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7177. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7178. // Invalid trailers are dropped entirely, matching set_header().
  7179. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7180. // The valid trailer still passes through.
  7181. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7182. }
  7183. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7184. Server svr;
  7185. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7186. // res.headers is a public field an application can populate directly,
  7187. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7188. // A valid header that must survive.
  7189. res.headers.emplace("X-Safe", "safe");
  7190. // Attacker-controlled value carrying CR/LF (response splitting).
  7191. res.headers.emplace("X-Reflected",
  7192. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7193. // Attacker-controlled name carrying CR/LF.
  7194. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7195. res.set_content("body", "text/plain");
  7196. });
  7197. thread t = thread([&] { svr.listen(HOST, PORT); });
  7198. auto se = detail::scope_exit([&] {
  7199. svr.stop();
  7200. t.join();
  7201. ASSERT_FALSE(svr.is_running());
  7202. });
  7203. svr.wait_until_ready();
  7204. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7205. "Host: " + HOST +
  7206. "\r\n"
  7207. "Connection: close\r\n"
  7208. "\r\n";
  7209. std::string res;
  7210. ASSERT_TRUE(send_request(5, req, &res));
  7211. // The injected fields must not appear anywhere in the raw response.
  7212. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7213. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7214. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7215. // Invalid headers are dropped entirely, matching set_header().
  7216. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7217. // The valid header still passes through.
  7218. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7219. }
  7220. // Forward declaration: in split builds split.py strips `inline` and moves the
  7221. // definition into httplib.cc, so detail::write_request_line is not visible from
  7222. // the public httplib.h. Re-declaring it here lets the tests link against the
  7223. // symbol in both header-only and split builds.
  7224. namespace httplib {
  7225. namespace detail {
  7226. ssize_t write_request_line(Stream &strm, const std::string &method,
  7227. const std::string &path);
  7228. } // namespace detail
  7229. } // namespace httplib
  7230. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7231. // A well-formed target is written verbatim.
  7232. {
  7233. detail::BufferStream strm;
  7234. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7235. EXPECT_GT(n, 0);
  7236. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7237. }
  7238. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7239. // otherwise it splits the request line and injects a header or a whole
  7240. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7241. // when path encoding is disabled.
  7242. const std::string evil_targets[] = {
  7243. "/a\r\nInjected: pwned",
  7244. "/a\rInjected",
  7245. "/a\nInjected",
  7246. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7247. };
  7248. for (const auto &evil : evil_targets) {
  7249. detail::BufferStream strm;
  7250. auto n = detail::write_request_line(strm, "GET", evil);
  7251. EXPECT_LT(n, 0);
  7252. EXPECT_TRUE(strm.get_buffer().empty());
  7253. }
  7254. }
  7255. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7256. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7257. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7258. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7259. // client must fail cleanly with Error::Write instead of putting a
  7260. // request-line-less, header-injecting request on the wire.
  7261. Server svr;
  7262. svr.Get("/a", [](const Request &, Response &res) {
  7263. res.set_content("ok", "text/plain");
  7264. });
  7265. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7266. auto se = detail::scope_exit([&] {
  7267. svr.stop();
  7268. thread.join();
  7269. ASSERT_FALSE(svr.is_running());
  7270. });
  7271. svr.wait_until_ready();
  7272. {
  7273. Client cli(HOST, PORT);
  7274. cli.set_path_encode(false);
  7275. // The request is rejected before anything is written, so the connection
  7276. // stays silent and the subsequent response read would otherwise block for
  7277. // the full default read timeout. Shorten it -- the assertion is on the
  7278. // error, not the timeout.
  7279. cli.set_read_timeout(1, 0);
  7280. auto res = cli.Get("/a\r\nInjected: pwned");
  7281. EXPECT_FALSE(res);
  7282. EXPECT_EQ(Error::Write, res.error());
  7283. }
  7284. }
  7285. // Sends a raw request and verifies that there isn't a crash or exception.
  7286. static void test_raw_request(const std::string &req,
  7287. std::string *out = nullptr) {
  7288. Server svr;
  7289. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7290. res.set_content("ok", "text/plain");
  7291. });
  7292. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7293. res.set_content("ok", "text/plain");
  7294. });
  7295. svr.Get("/header_field_value_check",
  7296. [&](const Request & /*req*/, Response &res) {
  7297. res.set_content("ok", "text/plain");
  7298. });
  7299. // Server read timeout must be longer than the client read timeout for the
  7300. // bug to reproduce, probably to force the server to process a request
  7301. // without a trailing blank line.
  7302. const time_t client_read_timeout_sec = 1;
  7303. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7304. bool listen_thread_ok = false;
  7305. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7306. auto se = detail::scope_exit([&] {
  7307. svr.stop();
  7308. t.join();
  7309. ASSERT_FALSE(svr.is_running());
  7310. EXPECT_TRUE(listen_thread_ok);
  7311. });
  7312. svr.wait_until_ready();
  7313. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7314. }
  7315. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7316. // A certain header line causes an exception if the header property is parsed
  7317. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7318. test_raw_request(
  7319. "GET /hi HTTP/1.1\r\n"
  7320. " : "
  7321. " "
  7322. " ");
  7323. }
  7324. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7325. // A certain header line causes an exception if the header property *name* is
  7326. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7327. // greedy matcher and requires backtracking when there are a lot of ":"
  7328. // characters.
  7329. // This occurs with libc++ but not libstdc++.
  7330. test_raw_request(
  7331. "GET /hi HTTP/1.1\r\n"
  7332. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7333. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7334. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7335. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7336. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7337. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7338. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7339. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7340. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7341. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7342. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7343. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7344. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7345. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7346. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7347. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7348. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7349. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7350. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7351. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7352. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7353. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7354. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7355. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7356. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7357. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7358. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7359. "&&&%%%");
  7360. }
  7361. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7362. // Make sure this doesn't crash the server.
  7363. // In a previous version of the header line regex, the "\r" rendered the line
  7364. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7365. // a new position where the leading white space ended and the field value
  7366. // began.
  7367. // The crash occurs with libc++ but not libstdc++.
  7368. test_raw_request("GET /hi HTTP/1.1\r\n"
  7369. "a:" +
  7370. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7371. "\r\n"
  7372. "\r\n");
  7373. }
  7374. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7375. std::string out;
  7376. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7377. "Content-Type: text/plain\r\n"
  7378. "Transfer-Encoding: chunked\r\n"
  7379. "\r\n"
  7380. "nothex\r\n",
  7381. &out);
  7382. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7383. }
  7384. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7385. std::string out;
  7386. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7387. "Content-Type: text/plain\r\n"
  7388. "Transfer-Encoding: chunked\r\n"
  7389. "\r\n"
  7390. "3\r\n"
  7391. "xyz\r\n"
  7392. "NaN\r\n",
  7393. &out);
  7394. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7395. }
  7396. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7397. std::string out;
  7398. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7399. "Content-Type: text/plain\r\n"
  7400. "Transfer-Encoding: chunked\r\n"
  7401. "\r\n"
  7402. // Length is too large for 64 bits.
  7403. "1ffffffffffffffff\r\n"
  7404. "xyz\r\n",
  7405. &out);
  7406. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7407. }
  7408. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7409. test_raw_request("GET /hi HTTP/1.1\r\n"
  7410. "Content-Type: text/plain\r\n\r");
  7411. }
  7412. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7413. std::string out;
  7414. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7415. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7416. }
  7417. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7418. Server svr;
  7419. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7420. EXPECT_TRUE(!req.remote_addr.empty());
  7421. });
  7422. thread t = thread([&] { svr.listen(HOST, PORT); });
  7423. auto se = detail::scope_exit([&] {
  7424. svr.stop();
  7425. t.join();
  7426. ASSERT_FALSE(svr.is_running());
  7427. });
  7428. svr.wait_until_ready();
  7429. // Send an invalid request line to trigger Bad Request
  7430. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7431. std::string out;
  7432. ASSERT_TRUE(send_request(5, bad_req, &out));
  7433. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7434. }
  7435. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7436. std::string out;
  7437. std::string request(
  7438. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7439. test_raw_request(request, &out);
  7440. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7441. }
  7442. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7443. std::string out;
  7444. std::string request(
  7445. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7446. test_raw_request(request, &out);
  7447. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7448. }
  7449. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7450. std::string out;
  7451. std::string request(
  7452. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7453. test_raw_request(request, &out);
  7454. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7455. }
  7456. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7457. std::string out;
  7458. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7459. "Test: \r\n\r\n",
  7460. &out);
  7461. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7462. }
  7463. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7464. Server svr;
  7465. std::string x_custom;
  7466. std::string cookie;
  7467. std::string xff;
  7468. std::string x_unicode;
  7469. std::string x_iis;
  7470. svr.Get("/check", [&](const Request &req, Response &res) {
  7471. x_custom = req.get_header_value("X-Custom");
  7472. cookie = req.get_header_value("Cookie");
  7473. xff = req.get_header_value("X-Forwarded-For");
  7474. x_unicode = req.get_header_value("X-Unicode");
  7475. x_iis = req.get_header_value("X-IIS");
  7476. res.set_content("ok", "text/plain");
  7477. });
  7478. thread t = thread([&] { svr.listen(HOST, PORT); });
  7479. auto se = detail::scope_exit([&] {
  7480. svr.stop();
  7481. t.join();
  7482. ASSERT_FALSE(svr.is_running());
  7483. });
  7484. svr.wait_until_ready();
  7485. const std::string req = "GET /check HTTP/1.1\r\n"
  7486. "Host: localhost\r\n"
  7487. "X-Custom: a%0D%0AInjected: b\r\n"
  7488. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7489. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7490. "X-Unicode: %E3%81%82\r\n"
  7491. "X-IIS: %u00E9\r\n"
  7492. "Connection: close\r\n"
  7493. "\r\n";
  7494. std::string res;
  7495. ASSERT_TRUE(send_request(5, req, &res));
  7496. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7497. // Every value must be returned verbatim (wire form), with no decoding.
  7498. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7499. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7500. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7501. EXPECT_EQ("%E3%81%82", x_unicode);
  7502. EXPECT_EQ("%u00E9", x_iis);
  7503. }
  7504. // Applications that previously relied on automatic percent-decoding can
  7505. // reproduce the old behavior by explicitly calling decode_path_component()
  7506. // or, for RFC 3986 conformance, decode_uri_component().
  7507. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7508. Server svr;
  7509. std::string decoded;
  7510. svr.Get("/check", [&](const Request &req, Response &res) {
  7511. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7512. res.set_content("ok", "text/plain");
  7513. });
  7514. thread t = thread([&] { svr.listen(HOST, PORT); });
  7515. auto se = detail::scope_exit([&] {
  7516. svr.stop();
  7517. t.join();
  7518. ASSERT_FALSE(svr.is_running());
  7519. });
  7520. svr.wait_until_ready();
  7521. const std::string req = "GET /check HTTP/1.1\r\n"
  7522. "Host: localhost\r\n"
  7523. "X-Custom: hello%20world\r\n"
  7524. "Connection: close\r\n"
  7525. "\r\n";
  7526. std::string res;
  7527. ASSERT_TRUE(send_request(5, req, &res));
  7528. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7529. EXPECT_EQ("hello world", decoded);
  7530. }
  7531. // Regression test for #2033. Browsers send Referer values that include
  7532. // percent-encoded characters such as %0A inside the URL. Decoding the
  7533. // header value would either trip the post-decode CR/LF/NUL guard (the
  7534. // original bug, returning 400) or, after that guard was relaxed, silently
  7535. // store a literal LF — both unacceptable. The wire form must round-trip.
  7536. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7537. Server svr;
  7538. std::string referer;
  7539. svr.Get("/check", [&](const Request &req, Response &res) {
  7540. referer = req.get_header_value("Referer");
  7541. res.set_content("ok", "text/plain");
  7542. });
  7543. thread t = thread([&] { svr.listen(HOST, PORT); });
  7544. auto se = detail::scope_exit([&] {
  7545. svr.stop();
  7546. t.join();
  7547. ASSERT_FALSE(svr.is_running());
  7548. });
  7549. svr.wait_until_ready();
  7550. const std::string req = "GET /check HTTP/1.1\r\n"
  7551. "Host: localhost\r\n"
  7552. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7553. "Connection: close\r\n"
  7554. "\r\n";
  7555. std::string res;
  7556. ASSERT_TRUE(send_request(5, req, &res));
  7557. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7558. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7559. }
  7560. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7561. Server svr;
  7562. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7563. res.set_header("Cache-Control", "no-cache");
  7564. res.set_chunked_content_provider(
  7565. "text/event-stream", [](size_t offset, DataSink &sink) {
  7566. std::string s = "data:";
  7567. s += std::to_string(offset);
  7568. s += "\n\n";
  7569. auto ret = sink.write(s.data(), s.size());
  7570. EXPECT_TRUE(ret);
  7571. std::this_thread::sleep_for(std::chrono::seconds(1));
  7572. return true;
  7573. });
  7574. });
  7575. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7576. svr.wait_until_ready();
  7577. Client client(HOST, PORT);
  7578. const Headers headers = {{"Accept", "text/event-stream"}};
  7579. auto get_thread = std::thread([&client, &headers]() {
  7580. auto res = client.Get(
  7581. "/events", headers,
  7582. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7583. });
  7584. auto se = detail::scope_exit([&] {
  7585. svr.stop();
  7586. get_thread.join();
  7587. listen_thread.join();
  7588. ASSERT_FALSE(svr.is_running());
  7589. });
  7590. // Give GET time to get a few messages.
  7591. std::this_thread::sleep_for(std::chrono::seconds(2));
  7592. }
  7593. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7594. httplib::Server svr;
  7595. svr.Post("/hi",
  7596. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7597. res.status = StatusCode::OK_200;
  7598. });
  7599. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7600. svr.wait_until_ready();
  7601. Client cli(HOST, PORT);
  7602. auto res = cli.Post("/hi", "data", "text/plain");
  7603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7604. EXPECT_EQ(StatusCode::OK_200, res->status);
  7605. svr.stop();
  7606. thread.join();
  7607. ASSERT_FALSE(svr.is_running());
  7608. res = cli.Post("/hi", "data", "text/plain");
  7609. ASSERT_FALSE(res);
  7610. }
  7611. TEST(ServerStopTest, ListenFailure) {
  7612. Server svr;
  7613. auto t = thread([&]() {
  7614. auto ret = svr.listen("????", PORT);
  7615. EXPECT_FALSE(ret);
  7616. });
  7617. svr.wait_until_ready();
  7618. svr.stop();
  7619. t.join();
  7620. }
  7621. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7622. TEST(ServerStopTest, Decommision) {
  7623. Server svr;
  7624. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7625. for (int i = 0; i < 4; i++) {
  7626. auto is_even = !(i % 2);
  7627. std::thread t{[&] {
  7628. try {
  7629. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7630. if (is_even) {
  7631. throw std::runtime_error("Some thing that happens to go wrong.");
  7632. }
  7633. svr.listen(HOST, PORT);
  7634. } catch (...) { svr.decommission(); }
  7635. }};
  7636. svr.wait_until_ready();
  7637. // Server is up
  7638. {
  7639. Client cli(HOST, PORT);
  7640. auto res = cli.Get("/hi");
  7641. if (is_even) {
  7642. EXPECT_FALSE(res);
  7643. } else {
  7644. EXPECT_TRUE(res);
  7645. EXPECT_EQ("hi...", res->body);
  7646. }
  7647. }
  7648. svr.stop();
  7649. t.join();
  7650. // Server is down...
  7651. {
  7652. Client cli(HOST, PORT);
  7653. auto res = cli.Get("/hi");
  7654. EXPECT_FALSE(res);
  7655. }
  7656. }
  7657. }
  7658. #endif
  7659. // Helper function for string body upload progress tests
  7660. template <typename SetupHandler, typename ClientCall>
  7661. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7662. ClientCall &&client_call,
  7663. const string &body) {
  7664. Server svr;
  7665. setup_handler(svr);
  7666. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7667. auto se = detail::scope_exit([&] {
  7668. svr.stop();
  7669. t.join();
  7670. });
  7671. svr.wait_until_ready();
  7672. Client cli(HOST, PORT);
  7673. vector<uint64_t> progress_values;
  7674. bool progress_called = false;
  7675. auto res =
  7676. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7677. progress_values.push_back(current);
  7678. progress_called = true;
  7679. return true;
  7680. });
  7681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7682. EXPECT_EQ(200, res->status);
  7683. EXPECT_TRUE(progress_called);
  7684. }
  7685. TEST(UploadProgressTest, PostStringBodyBasic) {
  7686. TestStringBodyUploadProgress(
  7687. [](Server &svr) {
  7688. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7689. res.set_content("received", "text/plain");
  7690. });
  7691. },
  7692. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7693. return cli.Post("/test", body, "text/plain", progress_callback);
  7694. },
  7695. "test data for upload progress");
  7696. }
  7697. TEST(UploadProgressTest, PutStringBodyBasic) {
  7698. TestStringBodyUploadProgress(
  7699. [](Server &svr) {
  7700. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7701. res.set_content("put received", "text/plain");
  7702. });
  7703. },
  7704. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7705. return cli.Put("/test", body, "text/plain", progress_callback);
  7706. },
  7707. "put test data for upload progress");
  7708. }
  7709. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7710. TestStringBodyUploadProgress(
  7711. [](Server &svr) {
  7712. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7713. res.set_content("patch received", "text/plain");
  7714. });
  7715. },
  7716. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7717. return cli.Patch("/test", body, "text/plain", progress_callback);
  7718. },
  7719. "patch test data for upload progress");
  7720. }
  7721. // Helper function for content provider upload progress tests
  7722. template <typename SetupHandler, typename ClientCall>
  7723. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7724. ClientCall &&client_call) {
  7725. Server svr;
  7726. setup_handler(svr);
  7727. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7728. auto se = detail::scope_exit([&] {
  7729. svr.stop();
  7730. t.join();
  7731. });
  7732. svr.wait_until_ready();
  7733. Client cli(HOST, PORT);
  7734. vector<uint64_t> progress_values;
  7735. auto res =
  7736. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7737. progress_values.push_back(current);
  7738. return true;
  7739. });
  7740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7741. EXPECT_EQ(200, res->status);
  7742. EXPECT_FALSE(progress_values.empty());
  7743. }
  7744. TEST(UploadProgressTest, PostContentProviderProgress) {
  7745. TestContentProviderUploadProgress(
  7746. [](Server &svr) {
  7747. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7748. res.set_content("provider received", "text/plain");
  7749. });
  7750. },
  7751. [](Client &cli, UploadProgress progress_callback) {
  7752. return cli.Post(
  7753. "/test", 10,
  7754. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7755. sink.os << "test data";
  7756. return true;
  7757. },
  7758. "text/plain", progress_callback);
  7759. });
  7760. }
  7761. // Helper function for multipart upload progress tests
  7762. template <typename SetupHandler, typename ClientCall>
  7763. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7764. ClientCall &&client_call,
  7765. const string &endpoint) {
  7766. Server svr;
  7767. setup_handler(svr);
  7768. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7769. auto se = detail::scope_exit([&] {
  7770. svr.stop();
  7771. t.join();
  7772. });
  7773. svr.wait_until_ready();
  7774. Client cli(HOST, PORT);
  7775. vector<uint64_t> progress_values;
  7776. UploadFormDataItems items = {
  7777. {"field1", "value1", "", ""},
  7778. {"field2", "longer value for progress tracking test", "", ""},
  7779. {"file1", "file content data for upload progress", "test.txt",
  7780. "text/plain"}};
  7781. auto res = client_call(cli, endpoint, items,
  7782. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7783. progress_values.push_back(current);
  7784. return true;
  7785. });
  7786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7787. EXPECT_EQ(200, res->status);
  7788. EXPECT_FALSE(progress_values.empty());
  7789. }
  7790. TEST(UploadProgressTest, PostMultipartProgress) {
  7791. TestMultipartUploadProgress(
  7792. [](Server &svr) {
  7793. svr.Post("/multipart", [](const Request &req, Response &res) {
  7794. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7795. res.set_content("multipart received", "text/plain");
  7796. });
  7797. },
  7798. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7799. UploadProgress progress_callback) {
  7800. return cli.Post(endpoint, items, progress_callback);
  7801. },
  7802. "/multipart");
  7803. }
  7804. // Helper function for basic download progress tests
  7805. template <typename SetupHandler, typename ClientCall>
  7806. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7807. ClientCall &&client_call, const string &endpoint,
  7808. size_t expected_content_size) {
  7809. Server svr;
  7810. setup_handler(svr);
  7811. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7812. auto se = detail::scope_exit([&] {
  7813. svr.stop();
  7814. t.join();
  7815. });
  7816. svr.wait_until_ready();
  7817. Client cli(HOST, PORT);
  7818. vector<uint64_t> progress_values;
  7819. auto res = client_call(cli, endpoint,
  7820. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7821. progress_values.push_back(current);
  7822. return true;
  7823. });
  7824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7825. EXPECT_EQ(200, res->status);
  7826. EXPECT_FALSE(progress_values.empty());
  7827. EXPECT_EQ(expected_content_size, res->body.size());
  7828. }
  7829. TEST(DownloadProgressTest, GetBasic) {
  7830. TestBasicDownloadProgress(
  7831. [](Server &svr) {
  7832. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7833. string content(1000, 'D');
  7834. res.set_content(content, "text/plain");
  7835. });
  7836. },
  7837. [](Client &cli, const string &endpoint,
  7838. DownloadProgress progress_callback) {
  7839. return cli.Get(endpoint, progress_callback);
  7840. },
  7841. "/download", 1000u);
  7842. }
  7843. // Helper function for content receiver download progress tests
  7844. template <typename SetupHandler, typename ClientCall>
  7845. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7846. ClientCall &&client_call,
  7847. const string &endpoint,
  7848. size_t expected_content_size) {
  7849. Server svr;
  7850. setup_handler(svr);
  7851. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7852. auto se = detail::scope_exit([&] {
  7853. svr.stop();
  7854. t.join();
  7855. });
  7856. svr.wait_until_ready();
  7857. Client cli(HOST, PORT);
  7858. vector<uint64_t> progress_values;
  7859. string received_body;
  7860. auto res = client_call(
  7861. cli, endpoint,
  7862. [&](const char *data, size_t data_length) -> bool {
  7863. received_body.append(data, data_length);
  7864. return true;
  7865. },
  7866. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7867. progress_values.push_back(current);
  7868. return true;
  7869. });
  7870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7871. EXPECT_EQ(200, res->status);
  7872. EXPECT_FALSE(progress_values.empty());
  7873. EXPECT_EQ(expected_content_size, received_body.size());
  7874. EXPECT_TRUE(res->body.empty());
  7875. }
  7876. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7877. TestContentReceiverDownloadProgress(
  7878. [](Server &svr) {
  7879. svr.Get("/download-receiver",
  7880. [](const Request & /*req*/, Response &res) {
  7881. string content(2000, 'R');
  7882. res.set_content(content, "text/plain");
  7883. });
  7884. },
  7885. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7886. DownloadProgress progress_callback) {
  7887. return cli.Get(endpoint, content_receiver, progress_callback);
  7888. },
  7889. "/download-receiver", 2000u);
  7890. }
  7891. TEST(StreamingTest, NoContentLengthStreaming) {
  7892. Server svr;
  7893. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7894. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7895. if (offset < 6) {
  7896. sink.os << (offset < 3 ? "a" : "b");
  7897. } else {
  7898. sink.done();
  7899. }
  7900. return true;
  7901. });
  7902. });
  7903. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7904. auto listen_se = detail::scope_exit([&] {
  7905. svr.stop();
  7906. listen_thread.join();
  7907. ASSERT_FALSE(svr.is_running());
  7908. });
  7909. svr.wait_until_ready();
  7910. Client client(HOST, PORT);
  7911. auto get_thread = std::thread([&client]() {
  7912. std::string s;
  7913. auto res =
  7914. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7915. s += std::string(data, len);
  7916. return true;
  7917. });
  7918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7919. EXPECT_EQ(StatusCode::OK_200, res->status);
  7920. EXPECT_EQ("aaabbb", s);
  7921. });
  7922. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7923. // Give GET time to get a few messages.
  7924. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7925. }
  7926. TEST(MountTest, Unmount) {
  7927. Server svr;
  7928. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7929. auto se = detail::scope_exit([&] {
  7930. svr.stop();
  7931. listen_thread.join();
  7932. ASSERT_FALSE(svr.is_running());
  7933. });
  7934. svr.wait_until_ready();
  7935. Client cli("localhost", PORT);
  7936. svr.set_mount_point("/mount2", "./www2");
  7937. auto res = cli.Get("/");
  7938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7939. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7940. res = cli.Get("/mount2/dir/test.html");
  7941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7942. EXPECT_EQ(StatusCode::OK_200, res->status);
  7943. svr.set_mount_point("/", "./www");
  7944. res = cli.Get("/dir/");
  7945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7946. EXPECT_EQ(StatusCode::OK_200, res->status);
  7947. svr.remove_mount_point("/");
  7948. res = cli.Get("/dir/");
  7949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7950. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7951. svr.remove_mount_point("/mount2");
  7952. res = cli.Get("/mount2/dir/test.html");
  7953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7954. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7955. }
  7956. TEST(MountTest, Redicect) {
  7957. Server svr;
  7958. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7959. auto se = detail::scope_exit([&] {
  7960. svr.stop();
  7961. listen_thread.join();
  7962. ASSERT_FALSE(svr.is_running());
  7963. });
  7964. svr.set_mount_point("/", "./www");
  7965. svr.wait_until_ready();
  7966. Client cli("localhost", PORT);
  7967. auto res = cli.Get("/dir/");
  7968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7969. EXPECT_EQ(StatusCode::OK_200, res->status);
  7970. res = cli.Get("/dir");
  7971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7972. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7973. res = cli.Get("/file");
  7974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7975. EXPECT_EQ(StatusCode::OK_200, res->status);
  7976. res = cli.Get("/file/");
  7977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7978. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7979. cli.set_follow_location(true);
  7980. res = cli.Get("/dir");
  7981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7982. EXPECT_EQ(StatusCode::OK_200, res->status);
  7983. }
  7984. TEST(MountTest, MultibytesPathName) {
  7985. Server svr;
  7986. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7987. auto se = detail::scope_exit([&] {
  7988. svr.stop();
  7989. listen_thread.join();
  7990. ASSERT_FALSE(svr.is_running());
  7991. });
  7992. svr.set_mount_point("/", "./www");
  7993. svr.wait_until_ready();
  7994. Client cli("localhost", PORT);
  7995. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7997. EXPECT_EQ(StatusCode::OK_200, res->status);
  7998. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7999. }
  8000. #ifdef _WIN32
  8001. // Issue #2435: mmap::open() must succeed even when another handle holds
  8002. // the file open for writing (e.g. an active log file).
  8003. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8004. const char *path = "mmap_concurrent_writer_test.txt";
  8005. const char *content = "hello";
  8006. {
  8007. std::ofstream f(path, std::ios::binary);
  8008. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8009. }
  8010. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8011. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8012. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8013. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8014. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8015. detail::mmap m(path);
  8016. ASSERT_TRUE(m.is_open());
  8017. EXPECT_EQ(strlen(content), m.size());
  8018. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8019. }
  8020. #endif
  8021. #ifndef _WIN32
  8022. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8023. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8024. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8025. TEST(MmapTest, FailedMappingIsNotOpen) {
  8026. const char *path = "./mmap_failed_mapping_test_dir";
  8027. ASSERT_EQ(0, ::mkdir(path, 0755));
  8028. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8029. detail::mmap m(path);
  8030. EXPECT_FALSE(m.is_open());
  8031. EXPECT_EQ(0U, m.size());
  8032. EXPECT_NE(static_cast<const void *>(m.data()),
  8033. static_cast<const void *>(MAP_FAILED));
  8034. }
  8035. #endif
  8036. TEST(KeepAliveTest, ReadTimeout) {
  8037. Server svr;
  8038. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8039. std::this_thread::sleep_for(std::chrono::seconds(2));
  8040. res.set_content("a", "text/plain");
  8041. });
  8042. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8043. res.set_content("b", "text/plain");
  8044. });
  8045. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8046. auto se = detail::scope_exit([&] {
  8047. svr.stop();
  8048. listen_thread.join();
  8049. ASSERT_FALSE(svr.is_running());
  8050. });
  8051. svr.wait_until_ready();
  8052. Client cli("localhost", PORT);
  8053. cli.set_keep_alive(true);
  8054. cli.set_read_timeout(std::chrono::seconds(1));
  8055. auto resa = cli.Get("/a");
  8056. ASSERT_FALSE(resa);
  8057. EXPECT_EQ(Error::Read, resa.error());
  8058. auto resb = cli.Get("/b");
  8059. ASSERT_TRUE(resb);
  8060. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8061. EXPECT_EQ("b", resb->body);
  8062. }
  8063. TEST(KeepAliveTest, MaxCount) {
  8064. size_t keep_alive_max_count = 3;
  8065. Server svr;
  8066. svr.set_keep_alive_max_count(keep_alive_max_count);
  8067. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8068. res.set_content("Hello World!", "text/plain");
  8069. });
  8070. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8071. auto se = detail::scope_exit([&] {
  8072. svr.stop();
  8073. listen_thread.join();
  8074. ASSERT_FALSE(svr.is_running());
  8075. });
  8076. svr.wait_until_ready();
  8077. Client cli(HOST, PORT);
  8078. cli.set_keep_alive(true);
  8079. for (size_t i = 0; i < 5; i++) {
  8080. auto result = cli.Get("/hi");
  8081. ASSERT_TRUE(result);
  8082. EXPECT_EQ(StatusCode::OK_200, result->status);
  8083. if (i == keep_alive_max_count - 1) {
  8084. EXPECT_EQ("close", result->get_header_value("Connection"));
  8085. } else {
  8086. EXPECT_FALSE(result->has_header("Connection"));
  8087. }
  8088. }
  8089. }
  8090. TEST(KeepAliveTest, Issue1041) {
  8091. Server svr;
  8092. svr.set_keep_alive_timeout(3);
  8093. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8094. res.set_content("Hello World!", "text/plain");
  8095. });
  8096. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8097. auto se = detail::scope_exit([&] {
  8098. svr.stop();
  8099. listen_thread.join();
  8100. ASSERT_FALSE(svr.is_running());
  8101. });
  8102. svr.wait_until_ready();
  8103. Client cli(HOST, PORT);
  8104. cli.set_keep_alive(true);
  8105. auto result = cli.Get("/hi");
  8106. ASSERT_TRUE(result);
  8107. EXPECT_EQ(StatusCode::OK_200, result->status);
  8108. std::this_thread::sleep_for(std::chrono::seconds(5));
  8109. result = cli.Get("/hi");
  8110. ASSERT_TRUE(result);
  8111. EXPECT_EQ(StatusCode::OK_200, result->status);
  8112. }
  8113. TEST(KeepAliveTest, Issue1959) {
  8114. Server svr;
  8115. svr.set_keep_alive_timeout(5);
  8116. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8117. res.set_content("a", "text/plain");
  8118. });
  8119. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8120. auto se = detail::scope_exit([&] {
  8121. if (!svr.is_running()) return;
  8122. svr.stop();
  8123. listen_thread.join();
  8124. ASSERT_FALSE(svr.is_running());
  8125. });
  8126. svr.wait_until_ready();
  8127. Client cli("localhost", PORT);
  8128. cli.set_keep_alive(true);
  8129. using namespace std::chrono;
  8130. auto start = steady_clock::now();
  8131. cli.Get("/a");
  8132. svr.stop();
  8133. listen_thread.join();
  8134. auto end = steady_clock::now();
  8135. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8136. EXPECT_LT(elapsed, 5000);
  8137. }
  8138. #ifdef CPPHTTPLIB_SSL_ENABLED
  8139. TEST(KeepAliveTest, SSLClientReconnection) {
  8140. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8141. ASSERT_TRUE(svr.is_valid());
  8142. svr.set_keep_alive_timeout(1);
  8143. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8144. res.set_content("Hello World!", "text/plain");
  8145. });
  8146. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8147. auto se = detail::scope_exit([&] {
  8148. svr.stop();
  8149. listen_thread.join();
  8150. ASSERT_FALSE(svr.is_running());
  8151. });
  8152. svr.wait_until_ready();
  8153. SSLClient cli(HOST, PORT);
  8154. cli.enable_server_certificate_verification(false);
  8155. cli.set_keep_alive(true);
  8156. auto result = cli.Get("/hi");
  8157. ASSERT_TRUE(result);
  8158. EXPECT_EQ(StatusCode::OK_200, result->status);
  8159. result = cli.Get("/hi");
  8160. ASSERT_TRUE(result);
  8161. EXPECT_EQ(StatusCode::OK_200, result->status);
  8162. std::this_thread::sleep_for(std::chrono::seconds(2));
  8163. // Recoonect
  8164. result = cli.Get("/hi");
  8165. ASSERT_TRUE(result);
  8166. EXPECT_EQ(StatusCode::OK_200, result->status);
  8167. result = cli.Get("/hi");
  8168. ASSERT_TRUE(result);
  8169. EXPECT_EQ(StatusCode::OK_200, result->status);
  8170. }
  8171. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8172. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8173. ASSERT_TRUE(svr.is_valid());
  8174. svr.set_keep_alive_timeout(1);
  8175. std::string content = "reconnect";
  8176. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8177. res.set_content("Hello World!", "text/plain");
  8178. });
  8179. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8180. auto se = detail::scope_exit([&] {
  8181. svr.stop();
  8182. listen_thread.join();
  8183. ASSERT_FALSE(svr.is_running());
  8184. });
  8185. svr.wait_until_ready();
  8186. SSLClient cli(HOST, PORT);
  8187. cli.enable_server_certificate_verification(false);
  8188. cli.set_keep_alive(true);
  8189. auto result = cli.Post(
  8190. "/hi", content.size(),
  8191. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8192. sink.write(content.c_str(), content.size());
  8193. return true;
  8194. },
  8195. "text/plain");
  8196. ASSERT_TRUE(result);
  8197. EXPECT_EQ(200, result->status);
  8198. std::this_thread::sleep_for(std::chrono::seconds(2));
  8199. // Recoonect
  8200. result = cli.Post(
  8201. "/hi", content.size(),
  8202. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8203. sink.write(content.c_str(), content.size());
  8204. return true;
  8205. },
  8206. "text/plain");
  8207. ASSERT_TRUE(result);
  8208. EXPECT_EQ(200, result->status);
  8209. result = cli.Post(
  8210. "/hi", content.size(),
  8211. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8212. sink.write(content.c_str(), content.size());
  8213. return true;
  8214. },
  8215. "text/plain");
  8216. ASSERT_TRUE(result);
  8217. EXPECT_EQ(200, result->status);
  8218. }
  8219. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8220. using namespace httplib::tls;
  8221. {
  8222. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8223. ASSERT_TRUE(svr.is_valid());
  8224. svr.Get("/sni", [&](const Request &req, Response &res) {
  8225. std::string expected = req.sni();
  8226. EXPECT_EQ(expected, req.get_param_value("expected"));
  8227. res.set_content("ok", "text/plain");
  8228. });
  8229. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8230. auto se = detail::scope_exit([&] {
  8231. svr.stop();
  8232. listen_thread.join();
  8233. ASSERT_FALSE(svr.is_running());
  8234. });
  8235. svr.wait_until_ready();
  8236. {
  8237. SSLClient cli("localhost", PORT);
  8238. cli.enable_server_certificate_verification(false);
  8239. auto res = cli.Get("/sni?expected=localhost");
  8240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8241. }
  8242. {
  8243. SSLClient cli("::1", PORT);
  8244. cli.enable_server_certificate_verification(false);
  8245. auto res = cli.Get("/sni?expected=");
  8246. // NOTE: This may fail if the server is listening on IPv4 only
  8247. // (e.g., when localhost resolves to 127.0.0.1 only)
  8248. if (res) {
  8249. EXPECT_EQ(StatusCode::OK_200, res->status);
  8250. } else {
  8251. EXPECT_EQ(Error::Connection, res.error());
  8252. }
  8253. }
  8254. }
  8255. }
  8256. #endif
  8257. TEST(ClientProblemDetectionTest, ContentProvider) {
  8258. Server svr;
  8259. size_t content_length = 1024 * 1024;
  8260. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8261. res.set_content_provider(
  8262. content_length, "text/plain",
  8263. [&](size_t offset, size_t length, DataSink &sink) {
  8264. auto out_len = std::min(length, static_cast<size_t>(1024));
  8265. std::string out(out_len, '@');
  8266. sink.write(out.data(), out_len);
  8267. return offset < 4096;
  8268. },
  8269. [](bool success) { ASSERT_FALSE(success); });
  8270. });
  8271. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8272. res.set_content_provider(
  8273. 0, "text/plain",
  8274. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8275. EXPECT_TRUE(false);
  8276. return true;
  8277. },
  8278. [](bool success) { ASSERT_FALSE(success); });
  8279. });
  8280. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8281. auto se = detail::scope_exit([&] {
  8282. svr.stop();
  8283. listen_thread.join();
  8284. ASSERT_FALSE(svr.is_running());
  8285. });
  8286. svr.wait_until_ready();
  8287. Client cli("localhost", PORT);
  8288. {
  8289. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8290. size_t /*data_length*/) { return false; });
  8291. ASSERT_FALSE(res);
  8292. }
  8293. {
  8294. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8295. size_t /*data_length*/) { return false; });
  8296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8297. }
  8298. }
  8299. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8300. Server svr;
  8301. svr.set_error_handler([](Request const &, Response &res) -> void {
  8302. res.set_chunked_content_provider(
  8303. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8304. sink.os << "hello";
  8305. sink.os << "world";
  8306. sink.done();
  8307. return true;
  8308. });
  8309. });
  8310. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8311. auto se = detail::scope_exit([&] {
  8312. svr.stop();
  8313. listen_thread.join();
  8314. ASSERT_FALSE(svr.is_running());
  8315. });
  8316. svr.wait_until_ready();
  8317. Client cli("localhost", PORT);
  8318. auto res = cli.Get("/");
  8319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8320. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8321. EXPECT_EQ("helloworld", res->body);
  8322. }
  8323. TEST(LongPollingTest, ClientCloseDetection) {
  8324. Server svr;
  8325. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8326. res.set_chunked_content_provider(
  8327. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8328. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8329. sink.os << "hello";
  8330. auto count = 10;
  8331. while (count > 0 && sink.is_writable()) {
  8332. this_thread::sleep_for(chrono::milliseconds(10));
  8333. count--;
  8334. }
  8335. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8336. return true;
  8337. });
  8338. });
  8339. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8340. auto se = detail::scope_exit([&] {
  8341. svr.stop();
  8342. listen_thread.join();
  8343. ASSERT_FALSE(svr.is_running());
  8344. });
  8345. svr.wait_until_ready();
  8346. Client cli("localhost", PORT);
  8347. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8348. EXPECT_EQ("hello", string(data, data_length));
  8349. return false; // close the socket immediately.
  8350. });
  8351. ASSERT_FALSE(res);
  8352. }
  8353. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8354. Server svr;
  8355. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8356. res.set_chunked_content_provider(
  8357. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8358. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8359. sink.os << "hello";
  8360. EXPECT_TRUE(sink.os.good());
  8361. // Wait for the client to close the connection
  8362. auto count = 10;
  8363. while (count > 0 && sink.is_writable()) {
  8364. this_thread::sleep_for(chrono::milliseconds(10));
  8365. count--;
  8366. }
  8367. // After client disconnect, write repeatedly until the socket
  8368. // write actually fails (small writes may be absorbed by the
  8369. // kernel buffer)
  8370. std::string chunk(1024, 'x');
  8371. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8372. sink.os << chunk;
  8373. }
  8374. EXPECT_TRUE(sink.os.fail());
  8375. return true;
  8376. });
  8377. });
  8378. auto port = svr.bind_to_any_port("localhost");
  8379. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8380. auto se = detail::scope_exit([&] {
  8381. svr.stop();
  8382. listen_thread.join();
  8383. ASSERT_FALSE(svr.is_running());
  8384. });
  8385. svr.wait_until_ready();
  8386. Client cli("localhost", port);
  8387. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8388. EXPECT_EQ("hello", string(data, data_length));
  8389. return false; // close the socket immediately.
  8390. });
  8391. ASSERT_FALSE(res);
  8392. }
  8393. TEST(GetWithParametersTest, GetWithParameters) {
  8394. Server svr;
  8395. svr.Get("/", [&](const Request &req, Response &) {
  8396. EXPECT_EQ("world", req.get_param_value("hello"));
  8397. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8398. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8399. });
  8400. svr.Get("/params", [&](const Request &req, Response &) {
  8401. EXPECT_EQ("world", req.get_param_value("hello"));
  8402. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8403. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8404. });
  8405. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8406. EXPECT_EQ("resource-id", req.matches[1]);
  8407. EXPECT_EQ("foo", req.get_param_value("param1"));
  8408. EXPECT_EQ("bar", req.get_param_value("param2"));
  8409. });
  8410. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8411. EXPECT_EQ("user-id", req.path_params.at("id"));
  8412. EXPECT_EQ("foo", req.get_param_value("param1"));
  8413. EXPECT_EQ("bar", req.get_param_value("param2"));
  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. {
  8423. Client cli(HOST, PORT);
  8424. Params params;
  8425. params.emplace("hello", "world");
  8426. params.emplace("hello2", "world2");
  8427. params.emplace("hello3", "world3");
  8428. auto res = cli.Get("/", params, Headers{});
  8429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8430. EXPECT_EQ(StatusCode::OK_200, res->status);
  8431. }
  8432. {
  8433. Client cli(HOST, PORT);
  8434. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8436. EXPECT_EQ(StatusCode::OK_200, res->status);
  8437. }
  8438. {
  8439. Client cli(HOST, PORT);
  8440. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8442. EXPECT_EQ(StatusCode::OK_200, res->status);
  8443. }
  8444. {
  8445. Client cli(HOST, PORT);
  8446. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8448. EXPECT_EQ(StatusCode::OK_200, res->status);
  8449. }
  8450. }
  8451. TEST(GetWithParametersTest, GetWithParameters2) {
  8452. Server svr;
  8453. svr.Get("/", [&](const Request &req, Response &res) {
  8454. auto text = req.get_param_value("hello");
  8455. res.set_content(text, "text/plain");
  8456. });
  8457. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8458. auto se = detail::scope_exit([&] {
  8459. svr.stop();
  8460. listen_thread.join();
  8461. ASSERT_FALSE(svr.is_running());
  8462. });
  8463. svr.wait_until_ready();
  8464. Client cli("localhost", PORT);
  8465. Params params;
  8466. params.emplace("hello", "world");
  8467. std::string body;
  8468. auto res = cli.Get("/", params, Headers{},
  8469. [&](const char *data, size_t data_length) {
  8470. body.append(data, data_length);
  8471. return true;
  8472. });
  8473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8474. EXPECT_EQ(StatusCode::OK_200, res->status);
  8475. EXPECT_EQ("world", body);
  8476. }
  8477. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8478. Server svr;
  8479. svr.Get("/search", [&](const Request &req, Response &res) {
  8480. auto q = req.get_param_value("q");
  8481. res.set_content(q, "text/plain");
  8482. });
  8483. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8484. auto se = detail::scope_exit([&] {
  8485. svr.stop();
  8486. listen_thread.join();
  8487. ASSERT_FALSE(svr.is_running());
  8488. });
  8489. svr.wait_until_ready();
  8490. Client cli("localhost", PORT);
  8491. // Verify that Get(path, params) works without requiring Headers argument
  8492. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8494. EXPECT_EQ(StatusCode::OK_200, res->status);
  8495. EXPECT_EQ("cpp-httplib", res->body);
  8496. }
  8497. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8498. auto host = "httpbingo.org";
  8499. auto path = std::string{"/range/32"};
  8500. #ifdef CPPHTTPLIB_SSL_ENABLED
  8501. SSLClient cli(host);
  8502. #else
  8503. Client cli(host);
  8504. #endif
  8505. cli.set_default_headers({make_range_header({{1, 10}})});
  8506. cli.set_connection_timeout(5);
  8507. {
  8508. auto res = cli.Get(path);
  8509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8510. EXPECT_EQ("bcdefghijk", res->body);
  8511. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8512. }
  8513. {
  8514. auto res = cli.Get(path);
  8515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8516. EXPECT_EQ("bcdefghijk", res->body);
  8517. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8518. }
  8519. }
  8520. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8521. Server svr;
  8522. svr.set_default_headers({{"Hello", "World"}});
  8523. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8524. res.set_content("ok", "text/plain");
  8525. });
  8526. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8527. auto se = detail::scope_exit([&] {
  8528. svr.stop();
  8529. listen_thread.join();
  8530. ASSERT_FALSE(svr.is_running());
  8531. });
  8532. svr.wait_until_ready();
  8533. Client cli("localhost", PORT);
  8534. auto res = cli.Get("/");
  8535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8536. EXPECT_EQ(StatusCode::OK_200, res->status);
  8537. EXPECT_EQ("ok", res->body);
  8538. EXPECT_EQ("World", res->get_header_value("Hello"));
  8539. }
  8540. #ifdef CPPHTTPLIB_SSL_ENABLED
  8541. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8542. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8543. ASSERT_TRUE(svr.is_valid());
  8544. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8545. std::this_thread::sleep_for(std::chrono::seconds(2));
  8546. res.set_content("a", "text/plain");
  8547. });
  8548. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8549. res.set_content("b", "text/plain");
  8550. });
  8551. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8552. auto se = detail::scope_exit([&] {
  8553. svr.stop();
  8554. listen_thread.join();
  8555. ASSERT_FALSE(svr.is_running());
  8556. });
  8557. svr.wait_until_ready();
  8558. SSLClient cli("localhost", PORT);
  8559. cli.enable_server_certificate_verification(false);
  8560. cli.set_keep_alive(true);
  8561. cli.set_read_timeout(std::chrono::seconds(1));
  8562. auto resa = cli.Get("/a");
  8563. ASSERT_TRUE(!resa);
  8564. EXPECT_EQ(Error::Read, resa.error());
  8565. auto resb = cli.Get("/b");
  8566. ASSERT_TRUE(resb);
  8567. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8568. EXPECT_EQ("b", resb->body);
  8569. }
  8570. #endif
  8571. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8572. protected:
  8573. ServerTestWithAI_PASSIVE()
  8574. : cli_(HOST, PORT)
  8575. #ifdef CPPHTTPLIB_SSL_ENABLED
  8576. ,
  8577. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8578. #endif
  8579. {
  8580. #ifdef CPPHTTPLIB_SSL_ENABLED
  8581. cli_.enable_server_certificate_verification(false);
  8582. #endif
  8583. }
  8584. virtual void SetUp() {
  8585. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8586. res.set_content("Hello World!", "text/plain");
  8587. });
  8588. t_ = thread(
  8589. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8590. svr_.wait_until_ready();
  8591. }
  8592. virtual void TearDown() {
  8593. svr_.stop();
  8594. t_.join();
  8595. }
  8596. #ifdef CPPHTTPLIB_SSL_ENABLED
  8597. SSLClient cli_;
  8598. SSLServer svr_;
  8599. #else
  8600. Client cli_;
  8601. Server svr_;
  8602. #endif
  8603. thread t_;
  8604. };
  8605. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8606. auto res = cli_.Get("/hi");
  8607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8608. EXPECT_EQ(StatusCode::OK_200, res->status);
  8609. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8610. EXPECT_EQ("Hello World!", res->body);
  8611. }
  8612. class ServerUpDownTest : public ::testing::Test {
  8613. protected:
  8614. ServerUpDownTest() : cli_(HOST, PORT) {}
  8615. virtual void SetUp() {
  8616. t_ = thread([&]() {
  8617. svr_.bind_to_any_port(HOST);
  8618. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8619. ASSERT_TRUE(svr_.listen_after_bind());
  8620. });
  8621. svr_.wait_until_ready();
  8622. }
  8623. virtual void TearDown() {
  8624. svr_.stop();
  8625. t_.join();
  8626. }
  8627. Client cli_;
  8628. Server svr_;
  8629. thread t_;
  8630. };
  8631. TEST_F(ServerUpDownTest, QuickStartStop) {
  8632. // Should not crash, especially when run with
  8633. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8634. }
  8635. class PayloadMaxLengthTest : public ::testing::Test {
  8636. protected:
  8637. PayloadMaxLengthTest()
  8638. : cli_(HOST, PORT)
  8639. #ifdef CPPHTTPLIB_SSL_ENABLED
  8640. ,
  8641. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8642. #endif
  8643. {
  8644. #ifdef CPPHTTPLIB_SSL_ENABLED
  8645. cli_.enable_server_certificate_verification(false);
  8646. #endif
  8647. }
  8648. virtual void SetUp() {
  8649. svr_.set_payload_max_length(8);
  8650. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8651. res.set_content("test", "text/plain");
  8652. });
  8653. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8654. svr_.wait_until_ready();
  8655. }
  8656. virtual void TearDown() {
  8657. svr_.stop();
  8658. t_.join();
  8659. }
  8660. #ifdef CPPHTTPLIB_SSL_ENABLED
  8661. SSLClient cli_;
  8662. SSLServer svr_;
  8663. #else
  8664. Client cli_;
  8665. Server svr_;
  8666. #endif
  8667. thread t_;
  8668. };
  8669. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8670. auto res = cli_.Post("/test", "123456789", "text/plain");
  8671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8672. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8673. res = cli_.Post("/test", "12345678", "text/plain");
  8674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8675. EXPECT_EQ(StatusCode::OK_200, res->status);
  8676. }
  8677. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8678. // Test chunked encoding with payload exceeding the 8-byte limit
  8679. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8680. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8682. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8683. }
  8684. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8685. // Test chunked encoding with payload within the 8-byte limit
  8686. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8687. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8689. EXPECT_EQ(StatusCode::OK_200, res->status);
  8690. }
  8691. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8692. // Test using send_request to send chunked data exceeding payload limit
  8693. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8694. "Host: " +
  8695. std::string(HOST) + ":" + std::to_string(PORT) +
  8696. "\r\n"
  8697. "Transfer-Encoding: chunked\r\n"
  8698. "Connection: close\r\n"
  8699. "\r\n"
  8700. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8701. "0123456789\r\n"
  8702. "0\r\n" // End chunk
  8703. "\r\n";
  8704. std::string response;
  8705. bool result = send_request(1, chunked_request, &response);
  8706. if (!result) {
  8707. // If send_request fails, it might be because the server closed the
  8708. // connection due to payload limit enforcement, which is acceptable
  8709. SUCCEED()
  8710. << "Server rejected oversized chunked request (connection closed)";
  8711. } else {
  8712. // If we got a response, check if it's an error response or connection was
  8713. // closed early Short response length indicates connection was closed due to
  8714. // payload limit
  8715. if (response.length() <= 10) {
  8716. SUCCEED() << "Server closed connection for oversized chunked request";
  8717. } else {
  8718. // Check for error status codes
  8719. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8720. response.find("Payload Too Large") != std::string::npos ||
  8721. response.find("400") != std::string::npos);
  8722. }
  8723. }
  8724. }
  8725. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8726. // Test request without Content-Length header exceeding payload limit
  8727. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8728. "Host: " +
  8729. std::string(HOST) + ":" +
  8730. std::to_string(PORT) +
  8731. "\r\n"
  8732. "Connection: close\r\n"
  8733. "\r\n";
  8734. // Add payload exceeding the 8-byte limit
  8735. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8736. request_without_content_length += large_payload;
  8737. std::string response;
  8738. bool result = send_request(1, request_without_content_length, &response);
  8739. if (!result) {
  8740. // If send_request fails, server likely closed connection due to payload
  8741. // limit
  8742. SUCCEED() << "Server rejected oversized request without Content-Length "
  8743. "(connection closed)";
  8744. } else {
  8745. // Check if server responded with error or closed connection early
  8746. if (response.length() <= 10) {
  8747. SUCCEED() << "Server closed connection for oversized request without "
  8748. "Content-Length";
  8749. } else {
  8750. // Check for error status codes
  8751. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8752. response.find("Payload Too Large") != std::string::npos ||
  8753. response.find("400") != std::string::npos);
  8754. }
  8755. }
  8756. }
  8757. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8758. // Test request without Content-Length header within payload limit
  8759. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8760. "Host: " +
  8761. std::string(HOST) + ":" +
  8762. std::to_string(PORT) +
  8763. "\r\n"
  8764. "Connection: close\r\n"
  8765. "\r\n";
  8766. // Add payload within the 8-byte limit
  8767. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8768. request_without_content_length += small_payload;
  8769. std::string response;
  8770. bool result = send_request(1, request_without_content_length, &response);
  8771. // For requests without Content-Length, the server may have different behavior
  8772. // The key is that it should not reject due to payload limit for small
  8773. // payloads
  8774. if (result) {
  8775. // Check for any HTTP response (success or error, but not connection closed)
  8776. if (response.length() > 10) {
  8777. SUCCEED()
  8778. << "Server processed request without Content-Length within limit";
  8779. } else {
  8780. // Short response might indicate connection closed, which is acceptable
  8781. SUCCEED() << "Server closed connection for request without "
  8782. "Content-Length (acceptable behavior)";
  8783. }
  8784. } else {
  8785. // Connection failure might be due to protocol requirements
  8786. SUCCEED() << "Connection issue with request without Content-Length "
  8787. "(environment-specific)";
  8788. }
  8789. }
  8790. class LargePayloadMaxLengthTest : public ::testing::Test {
  8791. protected:
  8792. LargePayloadMaxLengthTest()
  8793. : cli_(HOST, PORT)
  8794. #ifdef CPPHTTPLIB_SSL_ENABLED
  8795. ,
  8796. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8797. #endif
  8798. {
  8799. #ifdef CPPHTTPLIB_SSL_ENABLED
  8800. cli_.enable_server_certificate_verification(false);
  8801. #endif
  8802. }
  8803. virtual void SetUp() {
  8804. // Set 10MB payload limit
  8805. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8806. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8807. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8808. res.set_content("Large payload test", "text/plain");
  8809. });
  8810. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8811. svr_.wait_until_ready();
  8812. }
  8813. virtual void TearDown() {
  8814. svr_.stop();
  8815. t_.join();
  8816. }
  8817. #ifdef CPPHTTPLIB_SSL_ENABLED
  8818. SSLClient cli_;
  8819. SSLServer svr_;
  8820. #else
  8821. Client cli_;
  8822. Server svr_;
  8823. #endif
  8824. thread t_;
  8825. };
  8826. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8827. // Test chunked encoding with payload within 10MB limit
  8828. std::string medium_payload(5 * 1024 * 1024,
  8829. 'A'); // 5MB payload, within 10MB limit
  8830. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8832. EXPECT_EQ(StatusCode::OK_200, res->status);
  8833. }
  8834. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8835. // Test chunked encoding with payload exceeding 10MB limit
  8836. std::string large_payload(12 * 1024 * 1024,
  8837. 'B'); // 12MB payload, exceeds 10MB limit
  8838. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8839. // Server may either return 413 or close the connection
  8840. if (res) {
  8841. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8842. } else {
  8843. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8844. }
  8845. }
  8846. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8847. // Test request without Content-Length header within 10MB limit
  8848. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8849. "Host: " +
  8850. std::string(HOST) + ":" +
  8851. std::to_string(PORT) +
  8852. "\r\n"
  8853. "Connection: close\r\n"
  8854. "\r\n";
  8855. // Add 1MB payload (within 10MB limit)
  8856. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8857. request_without_content_length += medium_payload;
  8858. std::string response;
  8859. bool result = send_request(5, request_without_content_length, &response);
  8860. if (result) {
  8861. // Should get a proper HTTP response for payloads within limit
  8862. if (response.length() > 10) {
  8863. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8864. "10MB limit";
  8865. } else {
  8866. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8867. "Content-Length)";
  8868. }
  8869. } else {
  8870. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8871. }
  8872. }
  8873. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8874. // Test request without Content-Length header exceeding 10MB limit
  8875. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8876. "Host: " +
  8877. std::string(HOST) + ":" +
  8878. std::to_string(PORT) +
  8879. "\r\n"
  8880. "Connection: close\r\n"
  8881. "\r\n";
  8882. // Add 12MB payload (exceeds 10MB limit)
  8883. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8884. request_without_content_length += large_payload;
  8885. std::string response;
  8886. bool result = send_request(10, request_without_content_length, &response);
  8887. if (!result) {
  8888. // Server should close connection due to payload limit
  8889. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8890. "(connection closed)";
  8891. } else {
  8892. // Check for error response
  8893. if (response.length() <= 10) {
  8894. SUCCEED()
  8895. << "Server closed connection for 12MB request exceeding 10MB limit";
  8896. } else {
  8897. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8898. response.find("Payload Too Large") != std::string::npos ||
  8899. response.find("400") != std::string::npos);
  8900. }
  8901. }
  8902. }
  8903. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8904. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8905. // path.
  8906. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8907. Server svr;
  8908. const size_t LIMIT = 64 * 1024; // 64KB
  8909. svr.set_payload_max_length(LIMIT);
  8910. size_t total = 0;
  8911. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8912. const ContentReader &content_reader) {
  8913. content_reader([&](const char * /*data*/, size_t len) {
  8914. total += len;
  8915. return true;
  8916. });
  8917. res.status = 200;
  8918. res.set_content("stream_ok", "text/plain");
  8919. });
  8920. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8921. auto se = detail::scope_exit([&] {
  8922. svr.stop();
  8923. thread.join();
  8924. ASSERT_FALSE(svr.is_running());
  8925. });
  8926. svr.wait_until_ready();
  8927. // Prepare 256KB raw data and gzip-compress it
  8928. std::string raw(256 * 1024, 'A');
  8929. std::string gz;
  8930. {
  8931. z_stream zs{};
  8932. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8933. Z_DEFAULT_STRATEGY);
  8934. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8935. zs.avail_in = static_cast<uInt>(raw.size());
  8936. char outbuf[4096];
  8937. int ret;
  8938. do {
  8939. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8940. zs.avail_out = sizeof(outbuf);
  8941. ret = deflate(&zs, Z_FINISH);
  8942. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8943. } while (ret != Z_STREAM_END);
  8944. deflateEnd(&zs);
  8945. }
  8946. Client cli(HOST, PORT);
  8947. cli.set_connection_timeout(std::chrono::seconds(5));
  8948. Headers headers = {{"Content-Encoding", "gzip"}};
  8949. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8950. "application/octet-stream");
  8951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8952. // Server must reject oversized decompressed payloads with 413.
  8953. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8954. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8955. EXPECT_LE(total, LIMIT);
  8956. }
  8957. #endif
  8958. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  8959. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  8960. // the payload must be passed through untouched instead of being rejected.
  8961. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  8962. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  8963. Server svr;
  8964. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  8965. res.set_content(body, "image/jpeg");
  8966. res.set_header("Content-Encoding", "UTF-8");
  8967. });
  8968. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  8969. res.set_content(body, "image/jpeg");
  8970. res.set_header("Content-Encoding", "identity");
  8971. });
  8972. svr.Post("/echo", [](const Request &req, Response &res) {
  8973. res.set_content(req.body, "image/jpeg");
  8974. });
  8975. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8976. auto se = detail::scope_exit([&] {
  8977. svr.stop();
  8978. t.join();
  8979. ASSERT_FALSE(svr.is_running());
  8980. });
  8981. svr.wait_until_ready();
  8982. Client cli(HOST, PORT);
  8983. {
  8984. auto res = cli.Get("/image");
  8985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8986. EXPECT_EQ(StatusCode::OK_200, res->status);
  8987. EXPECT_EQ(body, res->body);
  8988. }
  8989. {
  8990. auto res = cli.Get("/identity");
  8991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8992. EXPECT_EQ(StatusCode::OK_200, res->status);
  8993. EXPECT_EQ(body, res->body);
  8994. }
  8995. {
  8996. // The same applies to a request body reaching the server.
  8997. Headers headers = {{"Content-Encoding", "UTF-8"}};
  8998. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  8999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9000. EXPECT_EQ(StatusCode::OK_200, res->status);
  9001. EXPECT_EQ(body, res->body);
  9002. }
  9003. }
  9004. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9005. // gzip-encoded response even when the build has no zlib support.
  9006. static const char GZIPPED_HELLO_WORLD[] = {
  9007. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9008. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9009. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9010. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9011. // A content coding cpp-httplib recognizes but was not built with must be
  9012. // reported as such. Handing the still-compressed payload back to the caller
  9013. // would silently corrupt it.
  9014. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9015. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9016. Server svr;
  9017. // "image/jpeg" keeps the server from applying a content coding of its own,
  9018. // so the hand-crafted Content-Encoding below survives.
  9019. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9020. res.set_content(gzipped, "image/jpeg");
  9021. res.set_header("Content-Encoding", "gzip");
  9022. });
  9023. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9024. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9025. res.set_content(gzipped, "image/jpeg");
  9026. res.set_header("Content-Encoding", "GZIP");
  9027. });
  9028. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9029. auto se = detail::scope_exit([&] {
  9030. svr.stop();
  9031. t.join();
  9032. ASSERT_FALSE(svr.is_running());
  9033. });
  9034. svr.wait_until_ready();
  9035. Client cli(HOST, PORT);
  9036. {
  9037. auto res = cli.Get("/gzipped");
  9038. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9040. EXPECT_EQ("Hello World!", res->body);
  9041. #else
  9042. ASSERT_FALSE(res);
  9043. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9044. #endif
  9045. }
  9046. {
  9047. // open_stream() must behave the same way.
  9048. auto handle = cli.open_stream("GET", "/gzipped");
  9049. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9050. ASSERT_TRUE(handle.is_valid());
  9051. std::string received;
  9052. char buf[256];
  9053. ssize_t n;
  9054. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9055. received.append(buf, static_cast<size_t>(n));
  9056. }
  9057. EXPECT_EQ("Hello World!", received);
  9058. #else
  9059. EXPECT_FALSE(handle.is_valid());
  9060. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9061. #endif
  9062. }
  9063. {
  9064. // A differently-cased coding must not be mistaken for an unknown one, or
  9065. // the body would be handed back still compressed.
  9066. auto res = cli.Get("/gzipped-uppercase");
  9067. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9069. EXPECT_EQ("Hello World!", res->body);
  9070. #else
  9071. ASSERT_FALSE(res);
  9072. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9073. #endif
  9074. }
  9075. }
  9076. // Regression test for DoS vulnerability: a malicious server sending a response
  9077. // without Content-Length header must not cause unbounded memory consumption on
  9078. // the client side. The client should stop reading after a reasonable limit,
  9079. // similar to the server-side set_payload_max_length protection.
  9080. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9081. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9082. #ifndef _WIN32
  9083. signal(SIGPIPE, SIG_IGN);
  9084. #endif
  9085. auto server_thread = std::thread([] {
  9086. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9087. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9088. default_socket_options(srv);
  9089. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9090. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9091. sockaddr_in addr{};
  9092. addr.sin_family = AF_INET;
  9093. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9094. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9095. int opt = 1;
  9096. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9097. #ifdef _WIN32
  9098. reinterpret_cast<const char *>(&opt),
  9099. #else
  9100. &opt,
  9101. #endif
  9102. sizeof(opt));
  9103. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9104. ::listen(srv, 1);
  9105. sockaddr_in cli_addr{};
  9106. socklen_t cli_len = sizeof(cli_addr);
  9107. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9108. if (cli != INVALID_SOCKET) {
  9109. char buf[4096];
  9110. ::recv(cli, buf, sizeof(buf), 0);
  9111. // Malicious response: no Content-Length, no chunked encoding
  9112. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9113. "Connection: close\r\n"
  9114. "\r\n";
  9115. ::send(cli,
  9116. #ifdef _WIN32
  9117. static_cast<const char *>(response_header.c_str()),
  9118. static_cast<int>(response_header.size()),
  9119. #else
  9120. response_header.c_str(), response_header.size(),
  9121. #endif
  9122. 0);
  9123. // Send 10MB of data
  9124. std::string chunk(64 * 1024, 'A');
  9125. size_t total_sent = 0;
  9126. while (total_sent < MALICIOUS_DATA_SIZE) {
  9127. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9128. auto sent = ::send(cli,
  9129. #ifdef _WIN32
  9130. static_cast<const char *>(chunk.c_str()),
  9131. static_cast<int>(to_send),
  9132. #else
  9133. chunk.c_str(), to_send,
  9134. #endif
  9135. 0);
  9136. if (sent <= 0) break;
  9137. total_sent += static_cast<size_t>(sent);
  9138. }
  9139. detail::close_socket(cli);
  9140. }
  9141. detail::close_socket(srv);
  9142. });
  9143. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9144. size_t total_read = 0;
  9145. {
  9146. Client cli("127.0.0.1", PORT + 2);
  9147. cli.set_read_timeout(5, 0);
  9148. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9149. auto stream = cli.open_stream("GET", "/malicious");
  9150. ASSERT_TRUE(stream.is_valid());
  9151. char buffer[64 * 1024];
  9152. ssize_t n;
  9153. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9154. total_read += static_cast<size_t>(n);
  9155. }
  9156. } // StreamHandle and Client destroyed here, closing the socket
  9157. server_thread.join();
  9158. // With set_payload_max_length, the client must stop reading before consuming
  9159. // all 10MB. The read loop should be cut off at or near the configured limit.
  9160. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9161. << "Client read " << total_read << " bytes, exceeding the configured "
  9162. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9163. }
  9164. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9165. // the entire response body without truncation.
  9166. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9167. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9168. #ifndef _WIN32
  9169. signal(SIGPIPE, SIG_IGN);
  9170. #endif
  9171. auto server_thread = std::thread([] {
  9172. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9173. default_socket_options(srv);
  9174. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9175. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9176. sockaddr_in addr{};
  9177. addr.sin_family = AF_INET;
  9178. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9179. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9180. int opt = 1;
  9181. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9182. #ifdef _WIN32
  9183. reinterpret_cast<const char *>(&opt),
  9184. #else
  9185. &opt,
  9186. #endif
  9187. sizeof(opt));
  9188. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9189. ::listen(srv, 1);
  9190. sockaddr_in cli_addr{};
  9191. socklen_t cli_len = sizeof(cli_addr);
  9192. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9193. if (cli != INVALID_SOCKET) {
  9194. char buf[4096];
  9195. ::recv(cli, buf, sizeof(buf), 0);
  9196. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9197. "Connection: close\r\n"
  9198. "\r\n";
  9199. ::send(cli,
  9200. #ifdef _WIN32
  9201. static_cast<const char *>(response_header.c_str()),
  9202. static_cast<int>(response_header.size()),
  9203. #else
  9204. response_header.c_str(), response_header.size(),
  9205. #endif
  9206. 0);
  9207. std::string chunk(64 * 1024, 'A');
  9208. size_t total_sent = 0;
  9209. while (total_sent < DATA_SIZE) {
  9210. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9211. auto sent = ::send(cli,
  9212. #ifdef _WIN32
  9213. static_cast<const char *>(chunk.c_str()),
  9214. static_cast<int>(to_send),
  9215. #else
  9216. chunk.c_str(), to_send,
  9217. #endif
  9218. 0);
  9219. if (sent <= 0) break;
  9220. total_sent += static_cast<size_t>(sent);
  9221. }
  9222. #ifdef _WIN32
  9223. ::shutdown(cli, SD_SEND);
  9224. #else
  9225. ::shutdown(cli, SHUT_WR);
  9226. #endif
  9227. // Drain until the client closes its end, ensuring all data is delivered
  9228. char drain[1024];
  9229. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9230. detail::close_socket(cli);
  9231. }
  9232. detail::close_socket(srv);
  9233. });
  9234. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9235. size_t total_read = 0;
  9236. {
  9237. Client cli("127.0.0.1", PORT + 2);
  9238. cli.set_read_timeout(5, 0);
  9239. cli.set_payload_max_length(0); // 0 means no limit
  9240. auto stream = cli.open_stream("GET", "/data");
  9241. ASSERT_TRUE(stream.is_valid());
  9242. char buffer[64 * 1024];
  9243. ssize_t n;
  9244. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9245. total_read += static_cast<size_t>(n);
  9246. }
  9247. }
  9248. server_thread.join();
  9249. EXPECT_EQ(total_read, DATA_SIZE)
  9250. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9251. << " bytes without truncation, but only read " << total_read << " bytes.";
  9252. }
  9253. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9254. // enormous Content-Length must not cause the client to pre-allocate a huge
  9255. // response body buffer. The reservation is capped at payload_max_length_, and
  9256. // the read itself fails when the body exceeds the limit.
  9257. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9258. #ifndef _WIN32
  9259. signal(SIGPIPE, SIG_IGN);
  9260. #endif
  9261. auto server_thread = std::thread([] {
  9262. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9263. default_socket_options(srv);
  9264. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9265. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9266. sockaddr_in addr{};
  9267. addr.sin_family = AF_INET;
  9268. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9269. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9270. int opt = 1;
  9271. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9272. #ifdef _WIN32
  9273. reinterpret_cast<const char *>(&opt),
  9274. #else
  9275. &opt,
  9276. #endif
  9277. sizeof(opt));
  9278. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9279. ::listen(srv, 1);
  9280. sockaddr_in cli_addr{};
  9281. socklen_t cli_len = sizeof(cli_addr);
  9282. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9283. if (cli != INVALID_SOCKET) {
  9284. char buf[4096];
  9285. ::recv(cli, buf, sizeof(buf), 0);
  9286. // Malicious response: claim a 20GB body but send only a tiny payload.
  9287. std::string response = "HTTP/1.1 200 OK\r\n"
  9288. "Content-Length: 20000000000\r\n"
  9289. "\r\n"
  9290. "abc";
  9291. ::send(cli,
  9292. #ifdef _WIN32
  9293. static_cast<const char *>(response.c_str()),
  9294. static_cast<int>(response.size()),
  9295. #else
  9296. response.c_str(), response.size(),
  9297. #endif
  9298. 0);
  9299. detail::close_socket(cli);
  9300. }
  9301. detail::close_socket(srv);
  9302. });
  9303. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9304. {
  9305. Client cli("127.0.0.1", PORT + 2);
  9306. cli.set_read_timeout(5, 0);
  9307. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9308. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9309. // (server claims more bytes than payload_max_length permits), but it must
  9310. // not exhaust memory before getting there.
  9311. auto res = cli.Get("/malicious");
  9312. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9313. }
  9314. server_thread.join();
  9315. }
  9316. // Verify that content_receiver bypasses the default payload_max_length,
  9317. // allowing streaming downloads larger than 100MB without requiring an explicit
  9318. // set_payload_max_length call.
  9319. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9320. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9321. #ifndef _WIN32
  9322. signal(SIGPIPE, SIG_IGN);
  9323. #endif
  9324. auto server_thread = std::thread([] {
  9325. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9326. default_socket_options(srv);
  9327. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9328. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9329. sockaddr_in addr{};
  9330. addr.sin_family = AF_INET;
  9331. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9332. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9333. int opt = 1;
  9334. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9335. #ifdef _WIN32
  9336. reinterpret_cast<const char *>(&opt),
  9337. #else
  9338. &opt,
  9339. #endif
  9340. sizeof(opt));
  9341. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9342. ::listen(srv, 1);
  9343. sockaddr_in cli_addr{};
  9344. socklen_t cli_len = sizeof(cli_addr);
  9345. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9346. if (cli != INVALID_SOCKET) {
  9347. char buf[4096];
  9348. ::recv(cli, buf, sizeof(buf), 0);
  9349. // Response with Content-Length larger than default 100MB limit
  9350. auto content_length = std::to_string(DATA_SIZE);
  9351. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9352. "Content-Length: " +
  9353. content_length +
  9354. "\r\n"
  9355. "Connection: close\r\n"
  9356. "\r\n";
  9357. ::send(cli,
  9358. #ifdef _WIN32
  9359. static_cast<const char *>(response_header.c_str()),
  9360. static_cast<int>(response_header.size()),
  9361. #else
  9362. response_header.c_str(), response_header.size(),
  9363. #endif
  9364. 0);
  9365. std::string chunk(64 * 1024, 'A');
  9366. size_t total_sent = 0;
  9367. while (total_sent < DATA_SIZE) {
  9368. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9369. auto sent = ::send(cli,
  9370. #ifdef _WIN32
  9371. static_cast<const char *>(chunk.c_str()),
  9372. static_cast<int>(to_send),
  9373. #else
  9374. chunk.c_str(), to_send,
  9375. #endif
  9376. 0);
  9377. if (sent <= 0) break;
  9378. total_sent += static_cast<size_t>(sent);
  9379. }
  9380. detail::close_socket(cli);
  9381. }
  9382. detail::close_socket(srv);
  9383. });
  9384. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9385. size_t total_received = 0;
  9386. {
  9387. Client cli("127.0.0.1", PORT + 2);
  9388. cli.set_read_timeout(10, 0);
  9389. // Do NOT call set_payload_max_length — use the default 100MB limit
  9390. auto res =
  9391. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9392. total_received += data_length;
  9393. return true;
  9394. });
  9395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9396. EXPECT_EQ(StatusCode::OK_200, res->status);
  9397. }
  9398. server_thread.join();
  9399. EXPECT_EQ(total_received, DATA_SIZE)
  9400. << "With content_receiver, the client should read all " << DATA_SIZE
  9401. << " bytes despite the default 100MB payload_max_length, but only read "
  9402. << total_received << " bytes.";
  9403. }
  9404. // Verify that an explicit set_payload_max_length smaller than the response is
  9405. // enforced even when a content_receiver is used.
  9406. TEST(ClientVulnerabilityTest,
  9407. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9408. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9409. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9410. #ifndef _WIN32
  9411. signal(SIGPIPE, SIG_IGN);
  9412. #endif
  9413. auto server_thread = std::thread([] {
  9414. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9415. default_socket_options(srv);
  9416. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9417. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9418. sockaddr_in addr{};
  9419. addr.sin_family = AF_INET;
  9420. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9421. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9422. int opt = 1;
  9423. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9424. #ifdef _WIN32
  9425. reinterpret_cast<const char *>(&opt),
  9426. #else
  9427. &opt,
  9428. #endif
  9429. sizeof(opt));
  9430. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9431. ::listen(srv, 1);
  9432. sockaddr_in cli_addr{};
  9433. socklen_t cli_len = sizeof(cli_addr);
  9434. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9435. if (cli != INVALID_SOCKET) {
  9436. char buf[4096];
  9437. ::recv(cli, buf, sizeof(buf), 0);
  9438. auto content_length = std::to_string(DATA_SIZE);
  9439. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9440. "Content-Length: " +
  9441. content_length +
  9442. "\r\n"
  9443. "Connection: close\r\n"
  9444. "\r\n";
  9445. ::send(cli,
  9446. #ifdef _WIN32
  9447. static_cast<const char *>(response_header.c_str()),
  9448. static_cast<int>(response_header.size()),
  9449. #else
  9450. response_header.c_str(), response_header.size(),
  9451. #endif
  9452. 0);
  9453. std::string chunk(64 * 1024, 'A');
  9454. size_t total_sent = 0;
  9455. while (total_sent < DATA_SIZE) {
  9456. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9457. auto sent = ::send(cli,
  9458. #ifdef _WIN32
  9459. static_cast<const char *>(chunk.c_str()),
  9460. static_cast<int>(to_send),
  9461. #else
  9462. chunk.c_str(), to_send,
  9463. #endif
  9464. 0);
  9465. if (sent <= 0) break;
  9466. total_sent += static_cast<size_t>(sent);
  9467. }
  9468. detail::close_socket(cli);
  9469. }
  9470. detail::close_socket(srv);
  9471. });
  9472. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9473. size_t total_received = 0;
  9474. {
  9475. Client cli("127.0.0.1", PORT + 2);
  9476. cli.set_read_timeout(10, 0);
  9477. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9478. auto res =
  9479. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9480. total_received += data_length;
  9481. return true;
  9482. });
  9483. // Should fail because 200MB exceeds the explicit 150MB limit
  9484. EXPECT_FALSE(res);
  9485. }
  9486. server_thread.join();
  9487. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9488. << "Client with content_receiver should respect the explicit "
  9489. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9490. << total_received << " bytes.";
  9491. }
  9492. // Verify that an explicit set_payload_max_length larger than the response
  9493. // allows the content_receiver to read all data successfully.
  9494. TEST(ClientVulnerabilityTest,
  9495. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9496. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9497. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9498. #ifndef _WIN32
  9499. signal(SIGPIPE, SIG_IGN);
  9500. #endif
  9501. auto server_thread = std::thread([] {
  9502. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9503. default_socket_options(srv);
  9504. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9505. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9506. sockaddr_in addr{};
  9507. addr.sin_family = AF_INET;
  9508. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9509. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9510. int opt = 1;
  9511. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9512. #ifdef _WIN32
  9513. reinterpret_cast<const char *>(&opt),
  9514. #else
  9515. &opt,
  9516. #endif
  9517. sizeof(opt));
  9518. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9519. ::listen(srv, 1);
  9520. sockaddr_in cli_addr{};
  9521. socklen_t cli_len = sizeof(cli_addr);
  9522. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9523. if (cli != INVALID_SOCKET) {
  9524. char buf[4096];
  9525. ::recv(cli, buf, sizeof(buf), 0);
  9526. auto content_length = std::to_string(DATA_SIZE);
  9527. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9528. "Content-Length: " +
  9529. content_length +
  9530. "\r\n"
  9531. "Connection: close\r\n"
  9532. "\r\n";
  9533. ::send(cli,
  9534. #ifdef _WIN32
  9535. static_cast<const char *>(response_header.c_str()),
  9536. static_cast<int>(response_header.size()),
  9537. #else
  9538. response_header.c_str(), response_header.size(),
  9539. #endif
  9540. 0);
  9541. std::string chunk(64 * 1024, 'A');
  9542. size_t total_sent = 0;
  9543. while (total_sent < DATA_SIZE) {
  9544. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9545. auto sent = ::send(cli,
  9546. #ifdef _WIN32
  9547. static_cast<const char *>(chunk.c_str()),
  9548. static_cast<int>(to_send),
  9549. #else
  9550. chunk.c_str(), to_send,
  9551. #endif
  9552. 0);
  9553. if (sent <= 0) break;
  9554. total_sent += static_cast<size_t>(sent);
  9555. }
  9556. #ifdef _WIN32
  9557. ::shutdown(cli, SD_SEND);
  9558. #else
  9559. ::shutdown(cli, SHUT_WR);
  9560. #endif
  9561. char drain[1024];
  9562. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9563. detail::close_socket(cli);
  9564. }
  9565. detail::close_socket(srv);
  9566. });
  9567. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9568. size_t total_received = 0;
  9569. {
  9570. Client cli("127.0.0.1", PORT + 2);
  9571. cli.set_read_timeout(10, 0);
  9572. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9573. auto res =
  9574. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9575. total_received += data_length;
  9576. return true;
  9577. });
  9578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9579. EXPECT_EQ(StatusCode::OK_200, res->status);
  9580. }
  9581. server_thread.join();
  9582. EXPECT_EQ(total_received, DATA_SIZE)
  9583. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9584. << " bytes (larger than " << DATA_SIZE
  9585. << " bytes response), content_receiver should read all data, but only "
  9586. "read "
  9587. << total_received << " bytes.";
  9588. }
  9589. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9590. // Regression test for "zip bomb" attack on the client side: a malicious server
  9591. // sends a small gzip-compressed response that decompresses to a huge payload.
  9592. // The client must enforce payload_max_length on the decompressed size.
  9593. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9594. constexpr size_t DECOMPRESSED_SIZE =
  9595. 10 * 1024 * 1024; // 10MB after decompression
  9596. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9597. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9598. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9599. std::string compressed;
  9600. {
  9601. httplib::detail::gzip_compressor compressor;
  9602. bool ok =
  9603. compressor.compress(uncompressed.data(), uncompressed.size(),
  9604. /*last=*/true, [&](const char *buf, size_t len) {
  9605. compressed.append(buf, len);
  9606. return true;
  9607. });
  9608. ASSERT_TRUE(ok);
  9609. }
  9610. // Sanity: compressed data should be much smaller than the decompressed size
  9611. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9612. #ifndef _WIN32
  9613. signal(SIGPIPE, SIG_IGN);
  9614. #endif
  9615. // Set up the listening socket in the main thread so the server is guaranteed
  9616. // to be ready before the client connects (eliminates race condition).
  9617. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9618. default_socket_options(srv);
  9619. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9620. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9621. sockaddr_in addr{};
  9622. addr.sin_family = AF_INET;
  9623. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9624. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9625. int opt = 1;
  9626. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9627. #ifdef _WIN32
  9628. reinterpret_cast<const char *>(&opt),
  9629. #else
  9630. &opt,
  9631. #endif
  9632. sizeof(opt));
  9633. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9634. ASSERT_EQ(0, ::listen(srv, 1));
  9635. auto server_thread = std::thread([&compressed, srv] {
  9636. sockaddr_in cli_addr{};
  9637. socklen_t cli_len = sizeof(cli_addr);
  9638. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9639. if (cli != INVALID_SOCKET) {
  9640. // Read the full HTTP request (until \r\n\r\n)
  9641. char buf[4096];
  9642. size_t total = 0;
  9643. while (total < sizeof(buf)) {
  9644. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9645. if (n <= 0) break;
  9646. total += static_cast<size_t>(n);
  9647. // Check for end of headers
  9648. if (total >= 4) {
  9649. std::string req(buf, total);
  9650. if (req.find("\r\n\r\n") != std::string::npos) break;
  9651. }
  9652. }
  9653. // Malicious response: gzip-compressed body, no Content-Length
  9654. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9655. "Content-Encoding: gzip\r\n"
  9656. "Connection: close\r\n"
  9657. "\r\n";
  9658. ::send(cli,
  9659. #ifdef _WIN32
  9660. static_cast<const char *>(response_header.c_str()),
  9661. static_cast<int>(response_header.size()),
  9662. #else
  9663. response_header.c_str(), response_header.size(),
  9664. #endif
  9665. 0);
  9666. // Send the compressed payload (small on the wire, huge when decompressed)
  9667. size_t total_sent = 0;
  9668. while (total_sent < compressed.size()) {
  9669. auto to_send = std::min(compressed.size() - total_sent,
  9670. static_cast<size_t>(64 * 1024));
  9671. auto sent =
  9672. ::send(cli,
  9673. #ifdef _WIN32
  9674. static_cast<const char *>(compressed.c_str() + total_sent),
  9675. static_cast<int>(to_send),
  9676. #else
  9677. compressed.c_str() + total_sent, to_send,
  9678. #endif
  9679. 0);
  9680. if (sent <= 0) break;
  9681. total_sent += static_cast<size_t>(sent);
  9682. }
  9683. detail::close_socket(cli);
  9684. }
  9685. });
  9686. auto se = detail::scope_exit([&] {
  9687. detail::close_socket(srv);
  9688. server_thread.join();
  9689. });
  9690. size_t total_decompressed = 0;
  9691. {
  9692. Client cli("127.0.0.1", PORT + 3);
  9693. cli.set_read_timeout(5, 0);
  9694. cli.set_decompress(true);
  9695. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9696. auto stream = cli.open_stream("GET", "/zipbomb");
  9697. ASSERT_TRUE(stream.is_valid());
  9698. char buffer[64 * 1024];
  9699. ssize_t n;
  9700. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9701. total_decompressed += static_cast<size_t>(n);
  9702. }
  9703. }
  9704. // The decompressed size must be capped by payload_max_length. Without
  9705. // protection, the client would decompress the full 10MB from a tiny
  9706. // compressed payload, enabling a zip bomb DoS attack.
  9707. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9708. << "Client decompressed " << total_decompressed
  9709. << " bytes from a gzip response. The decompressed size should be "
  9710. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9711. }
  9712. #endif
  9713. TEST(HostAndPortPropertiesTest, NoSSL) {
  9714. httplib::Client cli("www.google.com", 1234);
  9715. ASSERT_EQ("www.google.com", cli.host());
  9716. ASSERT_EQ(1234, cli.port());
  9717. }
  9718. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9719. httplib::Client cli("www.google.com:1234");
  9720. ASSERT_EQ("www.google.com", cli.host());
  9721. ASSERT_EQ(1234, cli.port());
  9722. }
  9723. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9724. // Port number that overflows int — should not crash, client becomes invalid
  9725. httplib::Client cli("http://www.google.com:99999999999999999999");
  9726. ASSERT_FALSE(cli.is_valid());
  9727. }
  9728. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9729. // Port 99999 exceeds valid range (1-65535) — should not crash
  9730. httplib::Client cli("http://www.google.com:99999");
  9731. ASSERT_FALSE(cli.is_valid());
  9732. }
  9733. #ifdef CPPHTTPLIB_SSL_ENABLED
  9734. TEST(HostAndPortPropertiesTest, SSL) {
  9735. httplib::SSLClient cli("www.google.com");
  9736. ASSERT_EQ("www.google.com", cli.host());
  9737. ASSERT_EQ(443, cli.port());
  9738. }
  9739. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9740. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9741. std::string cert;
  9742. read_file(CA_CERT_FILE, cert);
  9743. httplib::SSLClient httplib_client("www.google.com");
  9744. // Load CA store first time
  9745. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9746. // Load CA store second time (update)
  9747. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9748. // Verify client is still valid and can make connections
  9749. httplib_client.enable_server_certificate_verification(true);
  9750. auto res = httplib_client.Get("/");
  9751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9752. // Google may return 200 or 301 depending on various factors
  9753. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9754. res->status == StatusCode::MovedPermanently_301);
  9755. }
  9756. TEST(SSLClientTest, ServerNameIndication_Online) {
  9757. auto host = "httpbingo.org";
  9758. auto path = std::string{"/get"};
  9759. SSLClient cli(host, 443);
  9760. auto res = cli.Get(path);
  9761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9762. ASSERT_EQ(StatusCode::OK_200, res->status);
  9763. }
  9764. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9765. // Use a site that will cause SSL verification failure due to self-signed cert
  9766. SSLClient cli("self-signed.badssl.com", 443);
  9767. cli.enable_server_certificate_verification(true);
  9768. auto res = cli.Get("/");
  9769. ASSERT_TRUE(!res);
  9770. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9771. // Verify backend error is captured for SSLServerVerification
  9772. // This occurs when certificate verification fails
  9773. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9774. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9775. EXPECT_NE(0UL, res.ssl_backend_error());
  9776. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9777. // For OpenSSL, ssl_error is 0 for verification errors
  9778. EXPECT_EQ(0, res.ssl_error());
  9779. #if !defined(_WIN32) || \
  9780. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9781. // On non-Windows or when Windows Schannel is disabled, the error comes
  9782. // from OpenSSL's verification
  9783. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9784. res.ssl_backend_error());
  9785. #endif
  9786. #endif
  9787. }
  9788. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9789. // Use a site where hostname doesn't match the certificate
  9790. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9791. SSLClient cli("wrong.host.badssl.com", 443);
  9792. cli.enable_server_certificate_verification(true);
  9793. cli.enable_server_hostname_verification(true);
  9794. auto res = cli.Get("/");
  9795. ASSERT_TRUE(!res);
  9796. // The error type depends on when hostname verification occurs:
  9797. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9798. // - Mbed TLS: SSLServerVerification (during handshake)
  9799. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9800. res.error() == Error::SSLServerVerification);
  9801. // Verify backend error is captured for hostname verification failure
  9802. EXPECT_NE(0UL, res.ssl_backend_error());
  9803. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9804. // For OpenSSL, ssl_error is 0 for verification errors
  9805. EXPECT_EQ(0, res.ssl_error());
  9806. #if !defined(_WIN32) || \
  9807. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9808. // On non-Windows or when Windows Schannel is disabled, the error comes
  9809. // from OpenSSL's hostname verification
  9810. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9811. res.ssl_backend_error());
  9812. #endif
  9813. #endif
  9814. }
  9815. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9816. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9817. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9818. SSLClient cli("www.google.com", 443);
  9819. cli.enable_server_certificate_verification(true);
  9820. auto res = cli.Get("/");
  9821. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9822. }
  9823. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9824. SSLClient cli("www.google.com", 443);
  9825. cli.enable_server_certificate_verification(true);
  9826. cli.enable_windows_certificate_verification(false);
  9827. auto res = cli.Get("/");
  9828. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9829. }
  9830. #endif
  9831. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9832. Client cli("https://google.com");
  9833. auto res = cli.Get("/");
  9834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9835. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9836. }
  9837. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9838. SSLClient cli("google.com");
  9839. cli.set_ca_cert_path(CA_CERT_FILE);
  9840. auto res = cli.Get("/");
  9841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9842. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9843. }
  9844. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9845. SSLClient cli("google.com");
  9846. cli.enable_server_certificate_verification(true);
  9847. cli.set_ca_cert_path("hello");
  9848. auto res = cli.Get("/");
  9849. ASSERT_TRUE(!res);
  9850. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9851. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9852. // should be set
  9853. EXPECT_EQ(0, res.ssl_error());
  9854. // Verify backend error is captured for SSLLoadingCerts
  9855. // This error occurs when loading CA certificates fails
  9856. EXPECT_NE(0UL, res.ssl_backend_error());
  9857. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9858. // OpenSSL specific error codes:
  9859. // > openssl errstr 0x80000002
  9860. // error:80000002:system library::No such file or directory
  9861. // > openssl errstr 0xA000126
  9862. // error:0A000126:SSL routines::unexpected eof while reading
  9863. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9864. res.ssl_backend_error() == 0xA000126);
  9865. #endif
  9866. }
  9867. TEST(SSLClientTest, ServerCertificateVerification4) {
  9868. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9869. ASSERT_TRUE(svr.is_valid());
  9870. svr.Get("/test", [&](const Request &, Response &res) {
  9871. res.set_content("test", "text/plain");
  9872. svr.stop();
  9873. ASSERT_TRUE(true);
  9874. });
  9875. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9876. auto se = detail::scope_exit([&] {
  9877. t.join();
  9878. ASSERT_FALSE(svr.is_running());
  9879. });
  9880. svr.wait_until_ready();
  9881. SSLClient cli("127.0.0.1", PORT);
  9882. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9883. cli.enable_server_certificate_verification(true);
  9884. cli.set_connection_timeout(30);
  9885. auto res = cli.Get("/test");
  9886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9887. ASSERT_EQ(StatusCode::OK_200, res->status);
  9888. }
  9889. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9890. std::string cert;
  9891. read_file(CA_CERT_FILE, cert);
  9892. SSLClient cli("google.com");
  9893. cli.load_ca_cert_store(cert.data(), cert.size());
  9894. const auto res = cli.Get("/");
  9895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9896. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9897. }
  9898. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9899. // clang-format off
  9900. static constexpr char cert[] =
  9901. "GlobalSign Root CA\n"
  9902. "==================\n"
  9903. "-----BEGIN CERTIFICATE-----\n"
  9904. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9905. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9906. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9907. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9908. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9909. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9910. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9911. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9912. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9913. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9914. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9915. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9916. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9917. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9918. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9919. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9920. "-----END CERTIFICATE-----\n";
  9921. // clang-format on
  9922. SSLClient cli("google.com");
  9923. cli.load_ca_cert_store(cert, sizeof(cert));
  9924. const auto res = cli.Get("/");
  9925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9926. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9927. }
  9928. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9929. SSLClient cli("www.youtube.com");
  9930. cli.set_ca_cert_path(CA_CERT_FILE);
  9931. cli.enable_server_certificate_verification(true);
  9932. cli.set_follow_location(true);
  9933. auto res = cli.Get("/");
  9934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9935. ASSERT_EQ(StatusCode::OK_200, res->status);
  9936. }
  9937. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9938. SSLClient cli("wWw.YouTube.Com");
  9939. cli.set_ca_cert_path(CA_CERT_FILE);
  9940. cli.enable_server_certificate_verification(true);
  9941. cli.enable_server_hostname_verification(true);
  9942. cli.set_follow_location(true);
  9943. auto res = cli.Get("/");
  9944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9945. ASSERT_EQ(StatusCode::OK_200, res->status);
  9946. }
  9947. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9948. SSLClient cli("gOoGlE.COm");
  9949. cli.enable_server_certificate_verification(true);
  9950. cli.enable_server_hostname_verification(true);
  9951. cli.set_follow_location(true);
  9952. auto res = cli.Get("/");
  9953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9954. ASSERT_EQ(StatusCode::OK_200, res->status);
  9955. }
  9956. TEST(SSLClientTest, Issue2004_Online) {
  9957. Client client("https://google.com");
  9958. client.set_follow_location(true);
  9959. auto res = client.Get("/");
  9960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9961. ASSERT_EQ(StatusCode::OK_200, res->status);
  9962. auto body = res->body;
  9963. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9964. }
  9965. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9966. // Create SSLClient with invalid cert/key to make is_valid() return false
  9967. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9968. "nonexistent_key.pem");
  9969. // is_valid() should be false due to cert loading failure
  9970. ASSERT_FALSE(cli.is_valid());
  9971. auto res = cli.Get("/");
  9972. ASSERT_FALSE(res);
  9973. EXPECT_EQ(Error::SSLConnection, res.error());
  9974. }
  9975. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9976. // Test for Issue #2251: SSL error not properly reported when client cert
  9977. // and key paths are swapped or mismatched
  9978. // This simulates the scenario where user accidentally swaps the cert and key
  9979. // files
  9980. // Using client cert file as private key and vice versa (completely wrong)
  9981. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9982. // Should fail validation due to cert/key mismatch
  9983. ASSERT_FALSE(cli.is_valid());
  9984. // Attempt to make a request should fail with proper error
  9985. auto res = cli.Get("/");
  9986. ASSERT_FALSE(res);
  9987. EXPECT_EQ(Error::SSLConnection, res.error());
  9988. // SSL error should be recorded in the Result object (this is the key fix for
  9989. // Issue #2251)
  9990. auto backend_error = res.ssl_backend_error();
  9991. EXPECT_NE(0u, backend_error);
  9992. }
  9993. // Tests cert/key mismatch detection at the TLS context level
  9994. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9995. // Test that using mismatched cert/key causes connection failure.
  9996. // We verify this at the SSLClient level rather than through internal
  9997. // TLS API functions.
  9998. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9999. cli.enable_server_certificate_verification(false);
  10000. cli.set_connection_timeout(2);
  10001. // The mismatch should cause a connection or handshake error
  10002. auto res = cli.Get("/test");
  10003. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10004. // Either way, the request should fail
  10005. EXPECT_FALSE(res);
  10006. }
  10007. #endif
  10008. #if 0
  10009. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10010. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10011. ASSERT_TRUE(cli != nullptr);
  10012. cli->set_address_family(AF_INET6);
  10013. cli->set_interface("en0");
  10014. auto res = cli->Get("/get");
  10015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10016. ASSERT_EQ(StatusCode::OK_200, res->status);
  10017. }
  10018. #endif
  10019. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10020. #ifdef CPPHTTPLIB_SSL_ENABLED
  10021. void ClientCertPresent(
  10022. const std::string &client_cert_file,
  10023. const std::string &client_private_key_file,
  10024. const std::string &client_encrypted_private_key_pass = std::string()) {
  10025. using namespace httplib::tls;
  10026. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10027. CLIENT_CA_CERT_DIR);
  10028. ASSERT_TRUE(svr.is_valid());
  10029. svr.Get("/test", [&](const Request &req, Response &res) {
  10030. res.set_content("test", "text/plain");
  10031. auto cert = req.peer_cert();
  10032. ASSERT_TRUE(static_cast<bool>(cert));
  10033. std::string common_name = cert.subject_cn();
  10034. EXPECT_EQ("Common Name", common_name);
  10035. });
  10036. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10037. auto se = detail::scope_exit([&] {
  10038. svr.stop();
  10039. t.join();
  10040. ASSERT_FALSE(svr.is_running());
  10041. });
  10042. svr.wait_until_ready();
  10043. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10044. client_encrypted_private_key_pass);
  10045. cli.enable_server_certificate_verification(false);
  10046. cli.set_connection_timeout(30);
  10047. auto res = cli.Get("/test");
  10048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10049. ASSERT_EQ(StatusCode::OK_200, res->status);
  10050. }
  10051. TEST(SSLClientServerTest, ClientCertPresent) {
  10052. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10053. }
  10054. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10055. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10056. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10057. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10058. }
  10059. // PEM memory-based constructor tests (works with all TLS backends)
  10060. void PemMemoryClientCertPresent(
  10061. const std::string &client_cert_file,
  10062. const std::string &client_private_key_file,
  10063. const std::string &client_encrypted_private_key_pass = std::string()) {
  10064. // Read PEM files into memory
  10065. std::string server_cert_pem, server_key_pem;
  10066. std::string client_ca_pem;
  10067. std::string client_cert_pem, client_key_pem;
  10068. read_file(SERVER_CERT_FILE, server_cert_pem);
  10069. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10070. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10071. read_file(client_cert_file, client_cert_pem);
  10072. read_file(client_private_key_file, client_key_pem);
  10073. // Create server with PEM memory
  10074. SSLServer::PemMemory server_pem = {
  10075. server_cert_pem.c_str(),
  10076. server_cert_pem.size(),
  10077. server_key_pem.c_str(),
  10078. server_key_pem.size(),
  10079. client_ca_pem.c_str(),
  10080. client_ca_pem.size(),
  10081. nullptr // no password for server key
  10082. };
  10083. SSLServer svr(server_pem);
  10084. ASSERT_TRUE(svr.is_valid());
  10085. svr.Get("/test", [&](const Request &, Response &res) {
  10086. res.set_content("test", "text/plain");
  10087. });
  10088. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10089. auto se = detail::scope_exit([&] {
  10090. svr.stop();
  10091. t.join();
  10092. ASSERT_FALSE(svr.is_running());
  10093. });
  10094. svr.wait_until_ready();
  10095. // Create client with PEM memory
  10096. const char *password = client_encrypted_private_key_pass.empty()
  10097. ? nullptr
  10098. : client_encrypted_private_key_pass.c_str();
  10099. SSLClient::PemMemory client_pem = {
  10100. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10101. client_key_pem.size(), password};
  10102. SSLClient cli(HOST, PORT, client_pem);
  10103. cli.enable_server_certificate_verification(false);
  10104. cli.set_connection_timeout(30);
  10105. auto res = cli.Get("/test");
  10106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10107. ASSERT_EQ(StatusCode::OK_200, res->status);
  10108. }
  10109. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10110. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10111. }
  10112. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10113. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10114. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10115. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10116. }
  10117. TEST(SSLClientServerTest, ClientCertMissing) {
  10118. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10119. CLIENT_CA_CERT_DIR);
  10120. ASSERT_TRUE(svr.is_valid());
  10121. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10122. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10123. auto se = detail::scope_exit([&] {
  10124. svr.stop();
  10125. t.join();
  10126. ASSERT_FALSE(svr.is_running());
  10127. });
  10128. svr.wait_until_ready();
  10129. SSLClient cli(HOST, PORT);
  10130. cli.set_connection_timeout(30);
  10131. auto res = cli.Get("/test");
  10132. ASSERT_TRUE(!res);
  10133. // When client cert is missing and server requires it, connection fails
  10134. // Error type depends on backend implementation
  10135. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10136. res.error() == Error::SSLConnection);
  10137. // Verify backend error is captured
  10138. // Note: This test may have different error codes depending on the exact
  10139. // verification failure
  10140. EXPECT_NE(0UL, res.ssl_backend_error());
  10141. }
  10142. TEST(SSLClientServerTest, TrustDirOptional) {
  10143. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10144. ASSERT_TRUE(svr.is_valid());
  10145. svr.Get("/test", [&](const Request &, Response &res) {
  10146. res.set_content("test", "text/plain");
  10147. });
  10148. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10149. auto se = detail::scope_exit([&] {
  10150. svr.stop();
  10151. t.join();
  10152. ASSERT_FALSE(svr.is_running());
  10153. });
  10154. svr.wait_until_ready();
  10155. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10156. cli.enable_server_certificate_verification(false);
  10157. cli.set_connection_timeout(30);
  10158. auto res = cli.Get("/test");
  10159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10160. ASSERT_EQ(StatusCode::OK_200, res->status);
  10161. }
  10162. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10163. class NoListenSSLServer : public SSLServer {
  10164. public:
  10165. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10166. const char *client_ca_cert_file_path,
  10167. const char *client_ca_cert_dir_path = nullptr)
  10168. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10169. client_ca_cert_dir_path),
  10170. stop_(false) {}
  10171. std::atomic_bool stop_;
  10172. private:
  10173. bool process_and_close_socket(socket_t /*sock*/) override {
  10174. // Don't create SSL context
  10175. while (!stop_.load()) {
  10176. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10177. }
  10178. return true;
  10179. }
  10180. };
  10181. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10182. CLIENT_CA_CERT_FILE);
  10183. ASSERT_TRUE(svr.is_valid());
  10184. svr.Get("/test", [&](const Request &, Response &res) {
  10185. res.set_content("test", "text/plain");
  10186. });
  10187. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10188. auto se = detail::scope_exit([&] {
  10189. svr.stop_ = true;
  10190. svr.stop();
  10191. t.join();
  10192. ASSERT_FALSE(svr.is_running());
  10193. });
  10194. svr.wait_until_ready();
  10195. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10196. cli.enable_server_certificate_verification(false);
  10197. cli.set_connection_timeout(1);
  10198. auto res = cli.Get("/test");
  10199. ASSERT_TRUE(!res);
  10200. EXPECT_EQ(Error::SSLConnection, res.error());
  10201. // Timeout results in WantRead error code (maps to backend-specific value)
  10202. EXPECT_NE(0, res.ssl_error());
  10203. }
  10204. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10205. // Test SSLServer with client certificate verification using the standard
  10206. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10207. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10208. CLIENT_CA_CERT_DIR);
  10209. ASSERT_TRUE(svr.is_valid());
  10210. svr.Get("/test", [&](const Request &req, Response &res) {
  10211. res.set_content("test", "text/plain");
  10212. auto cert = req.peer_cert();
  10213. ASSERT_TRUE(static_cast<bool>(cert));
  10214. auto common_name = cert.subject_cn();
  10215. EXPECT_EQ("Common Name", common_name);
  10216. });
  10217. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10218. auto se = detail::scope_exit([&] {
  10219. svr.stop();
  10220. t.join();
  10221. ASSERT_FALSE(svr.is_running());
  10222. });
  10223. svr.wait_until_ready();
  10224. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10225. cli.enable_server_certificate_verification(false);
  10226. cli.set_connection_timeout(30);
  10227. auto res = cli.Get("/test");
  10228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10229. ASSERT_EQ(StatusCode::OK_200, res->status);
  10230. }
  10231. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10232. // Verifies that wildcard matching and exact matching work consistently
  10233. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10234. using namespace httplib::tls;
  10235. // We need a running server to test against
  10236. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10237. ASSERT_TRUE(svr.is_valid());
  10238. svr.Get("/test", [](const Request &, Response &res) {
  10239. res.set_content("ok", "text/plain");
  10240. });
  10241. thread t([&]() { svr.listen(HOST, PORT); });
  10242. auto se = detail::scope_exit([&] {
  10243. svr.stop();
  10244. t.join();
  10245. });
  10246. svr.wait_until_ready();
  10247. bool verify_callback_called = false;
  10248. bool verify_result_wrong = false;
  10249. SSLClient cli(HOST, PORT);
  10250. cli.enable_server_certificate_verification(true);
  10251. cli.set_ca_cert_path(CA_CERT_FILE);
  10252. cli.set_connection_timeout(5);
  10253. // Note: Test certificate has CN="Common Name", not "localhost"
  10254. bool verify_result_cn = false;
  10255. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10256. verify_callback_called = true;
  10257. if (!ctx.cert) return false;
  10258. // Test 1: "Common Name" should match (our test server cert CN)
  10259. verify_result_cn = ctx.check_hostname("Common Name");
  10260. // Test 2: wrong hostname should not match
  10261. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10262. return true; // Accept for the purpose of this test
  10263. });
  10264. auto res = cli.Get("/test");
  10265. // The request may succeed or fail depending on cert configuration
  10266. // but the callback should have been called
  10267. ASSERT_TRUE(verify_callback_called)
  10268. << "Verify callback should have been called";
  10269. // CN="Common Name" should match our test certificate
  10270. //
  10271. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10272. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10273. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10274. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10275. // <openssl/base.h>, which is included transitively when
  10276. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10277. #if defined(OPENSSL_IS_BORINGSSL)
  10278. EXPECT_FALSE(verify_result_cn)
  10279. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10280. #else
  10281. EXPECT_TRUE(verify_result_cn)
  10282. << "verify_hostname should match 'Common Name' (certificate CN)";
  10283. #endif
  10284. // Wrong hostname should not match
  10285. EXPECT_FALSE(verify_result_wrong)
  10286. << "verify_hostname should not match 'wronghost.example.com'";
  10287. }
  10288. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10289. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10290. // X509_check_ip behavior and must hold for every backend.
  10291. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10292. using namespace httplib::tls;
  10293. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10294. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10295. ASSERT_TRUE(svr.is_valid());
  10296. svr.Get("/test", [](const Request &, Response &res) {
  10297. res.set_content("ok", "text/plain");
  10298. });
  10299. thread t([&]() { svr.listen(HOST, PORT); });
  10300. auto se = detail::scope_exit([&] {
  10301. svr.stop();
  10302. t.join();
  10303. });
  10304. svr.wait_until_ready();
  10305. bool verify_callback_called = false;
  10306. bool ip_matched_via_cn = true;
  10307. SSLClient cli(HOST, PORT);
  10308. cli.enable_server_certificate_verification(true);
  10309. cli.set_ca_cert_path(CA_CERT_FILE);
  10310. cli.set_connection_timeout(5);
  10311. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10312. verify_callback_called = true;
  10313. if (!ctx.cert) return false;
  10314. // The IP appears only in the CN, so it must NOT be accepted.
  10315. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10316. return true; // Accept for the purpose of this test
  10317. });
  10318. cli.Get("/test");
  10319. ASSERT_TRUE(verify_callback_called)
  10320. << "Verify callback should have been called";
  10321. EXPECT_FALSE(ip_matched_via_cn)
  10322. << "An IP host must not be authenticated via the certificate CN";
  10323. }
  10324. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10325. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10326. using namespace httplib::tls;
  10327. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10328. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10329. ASSERT_TRUE(svr.is_valid());
  10330. svr.Get("/test", [](const Request &, Response &res) {
  10331. res.set_content("ok", "text/plain");
  10332. });
  10333. thread t([&]() { svr.listen(HOST, PORT); });
  10334. auto se = detail::scope_exit([&] {
  10335. svr.stop();
  10336. t.join();
  10337. });
  10338. svr.wait_until_ready();
  10339. bool verify_callback_called = false;
  10340. bool san_matched = false;
  10341. bool wrong_ipv6_matched = true;
  10342. bool cn_ipv6_matched = true;
  10343. SSLClient cli(HOST, PORT);
  10344. cli.enable_server_certificate_verification(true);
  10345. cli.set_ca_cert_path(CA_CERT_FILE);
  10346. cli.set_connection_timeout(5);
  10347. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10348. verify_callback_called = true;
  10349. if (!ctx.cert) return false;
  10350. // Matches the IPv6 iPAddress SAN.
  10351. san_matched = ctx.check_hostname("2001:db8::1");
  10352. // A different IPv6 address must not match.
  10353. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10354. // "::1" lives only in the CN, so it must not be accepted.
  10355. cn_ipv6_matched = ctx.check_hostname("::1");
  10356. return true; // Accept for the purpose of this test
  10357. });
  10358. cli.Get("/test");
  10359. ASSERT_TRUE(verify_callback_called)
  10360. << "Verify callback should have been called";
  10361. EXPECT_TRUE(san_matched)
  10362. << "verify_hostname should match an IPv6 iPAddress SAN";
  10363. EXPECT_FALSE(wrong_ipv6_matched)
  10364. << "verify_hostname should not match a non-matching IPv6 address";
  10365. EXPECT_FALSE(cn_ipv6_matched)
  10366. << "An IPv6 host must not be authenticated via the certificate CN";
  10367. }
  10368. #endif
  10369. // mbedTLS-specific callback constructor test
  10370. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10371. #ifdef CPPHTTPLIB_SSL_ENABLED
  10372. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10374. ASSERT_TRUE(svr.is_valid());
  10375. // Set up a handler to verify client certificate is present
  10376. bool client_cert_verified = false;
  10377. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10378. // Verify that client certificate was provided
  10379. client_cert_verified = true;
  10380. res.set_content("success", "text/plain");
  10381. });
  10382. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10383. auto se = detail::scope_exit([&] {
  10384. svr.stop();
  10385. t.join();
  10386. ASSERT_FALSE(svr.is_running());
  10387. });
  10388. svr.wait_until_ready();
  10389. // Client with certificate
  10390. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10391. cli.enable_server_certificate_verification(false);
  10392. cli.set_connection_timeout(30);
  10393. auto res = cli.Get("/test");
  10394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10395. ASSERT_EQ(StatusCode::OK_200, res->status);
  10396. ASSERT_TRUE(client_cert_verified);
  10397. EXPECT_EQ("success", res->body);
  10398. }
  10399. #endif
  10400. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10401. // backends
  10402. #ifdef CPPHTTPLIB_SSL_ENABLED
  10403. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10404. using namespace httplib::tls;
  10405. // Test that when client CA cert file is provided,
  10406. // the server properly requests and validates client certificates
  10407. // Create a server with client authentication
  10408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10409. ASSERT_TRUE(svr.is_valid());
  10410. bool handler_called = false;
  10411. svr.Get("/test", [&](const Request &req, Response &res) {
  10412. handler_called = true;
  10413. // Verify that a client certificate was provided
  10414. auto cert = req.peer_cert();
  10415. ASSERT_TRUE(static_cast<bool>(cert));
  10416. // Get the issuer name
  10417. std::string issuer_str = cert.issuer_name();
  10418. ASSERT_FALSE(issuer_str.empty());
  10419. // The client certificate should be issued by our test CA
  10420. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10421. res.set_content("authenticated", "text/plain");
  10422. });
  10423. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10424. auto se = detail::scope_exit([&] {
  10425. svr.stop();
  10426. t.join();
  10427. ASSERT_FALSE(svr.is_running());
  10428. });
  10429. svr.wait_until_ready();
  10430. // Connect with a client certificate issued by the CA
  10431. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10432. cli.enable_server_certificate_verification(false);
  10433. cli.set_connection_timeout(30);
  10434. auto res = cli.Get("/test");
  10435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10436. ASSERT_EQ(StatusCode::OK_200, res->status);
  10437. ASSERT_TRUE(handler_called);
  10438. EXPECT_EQ("authenticated", res->body);
  10439. }
  10440. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10441. using namespace httplib::tls;
  10442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10443. ASSERT_TRUE(svr.is_valid());
  10444. svr.Get("/test", [](const Request &, Response &res) {
  10445. res.set_content("ok", "text/plain");
  10446. });
  10447. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10448. auto se = detail::scope_exit([&] {
  10449. svr.stop();
  10450. t.join();
  10451. });
  10452. svr.wait_until_ready();
  10453. SSLClient cli(HOST, PORT);
  10454. cli.enable_server_certificate_verification(false);
  10455. cli.set_connection_timeout(30);
  10456. bool cert_checked = false;
  10457. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10458. if (ctx.cert) {
  10459. auto sans = ctx.sans();
  10460. // Test certificate may or may not have SANs - just verify the API
  10461. // works If SANs exist, verify the types are valid
  10462. for (const auto &san : sans) {
  10463. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10464. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10465. san.type == SanType::OTHER);
  10466. EXPECT_FALSE(san.value.empty());
  10467. }
  10468. cert_checked = true;
  10469. }
  10470. return true;
  10471. });
  10472. auto res = cli.Get("/test");
  10473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10474. EXPECT_TRUE(cert_checked);
  10475. }
  10476. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10477. using namespace httplib::tls;
  10478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10479. ASSERT_TRUE(svr.is_valid());
  10480. svr.Get("/test", [](const Request &, Response &res) {
  10481. res.set_content("ok", "text/plain");
  10482. });
  10483. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10484. auto se = detail::scope_exit([&] {
  10485. svr.stop();
  10486. t.join();
  10487. });
  10488. svr.wait_until_ready();
  10489. SSLClient cli(HOST, PORT);
  10490. cli.enable_server_certificate_verification(false);
  10491. cli.set_connection_timeout(30);
  10492. bool validity_checked = false;
  10493. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10494. if (ctx.cert) {
  10495. time_t not_before = 0, not_after = 0;
  10496. bool result = ctx.validity(not_before, not_after);
  10497. EXPECT_TRUE(result);
  10498. // Verify that not_before < now < not_after for a valid cert
  10499. time_t now = time(nullptr);
  10500. EXPECT_LT(not_before, now);
  10501. EXPECT_GT(not_after, now);
  10502. validity_checked = true;
  10503. }
  10504. return true;
  10505. });
  10506. auto res = cli.Get("/test");
  10507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10508. EXPECT_TRUE(validity_checked);
  10509. }
  10510. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10511. using namespace httplib::tls;
  10512. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10513. ASSERT_TRUE(svr.is_valid());
  10514. svr.Get("/test", [](const Request &, Response &res) {
  10515. res.set_content("ok", "text/plain");
  10516. });
  10517. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10518. auto se = detail::scope_exit([&] {
  10519. svr.stop();
  10520. t.join();
  10521. });
  10522. svr.wait_until_ready();
  10523. SSLClient cli(HOST, PORT);
  10524. cli.enable_server_certificate_verification(false);
  10525. cli.set_connection_timeout(30);
  10526. bool serial_checked = false;
  10527. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10528. if (ctx.cert) {
  10529. std::string serial = ctx.serial();
  10530. EXPECT_FALSE(serial.empty());
  10531. // Serial should be a hex string
  10532. for (char c : serial) {
  10533. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10534. (c >= 'a' && c <= 'f'));
  10535. }
  10536. serial_checked = true;
  10537. }
  10538. return true;
  10539. });
  10540. auto res = cli.Get("/test");
  10541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10542. EXPECT_TRUE(serial_checked);
  10543. }
  10544. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10545. // Test 1: Valid CA file - no error should be recorded
  10546. {
  10547. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10548. CLIENT_CA_CERT_FILE);
  10549. ASSERT_TRUE(svr.is_valid());
  10550. // With valid setup, last_ssl_error should be 0
  10551. EXPECT_EQ(0, svr.ssl_last_error());
  10552. }
  10553. // Test 2: Invalid CA file content
  10554. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10555. {
  10556. // Create a temporary file with completely invalid content
  10557. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10558. {
  10559. std::ofstream ofs(temp_invalid_ca);
  10560. ofs << "This is not a certificate file at all\n";
  10561. ofs << "Just plain text content\n";
  10562. }
  10563. // Create server with invalid CA file
  10564. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10565. // Clean up temporary file
  10566. std::remove(temp_invalid_ca);
  10567. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10568. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10569. // Note: SSL_CTX_load_verify_locations typically fails first,
  10570. // but our error handling code path is still exercised
  10571. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10572. }
  10573. }
  10574. TEST(VerifyCallbackTest, VerifyContextFields) {
  10575. using namespace httplib::tls;
  10576. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10577. ASSERT_TRUE(svr.is_valid());
  10578. svr.Get("/test", [](const Request &, Response &res) {
  10579. res.set_content("ok", "text/plain");
  10580. });
  10581. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10582. auto se = detail::scope_exit([&] {
  10583. svr.stop();
  10584. t.join();
  10585. });
  10586. svr.wait_until_ready();
  10587. SSLClient cli(HOST, PORT);
  10588. cli.enable_server_certificate_verification(false);
  10589. cli.set_connection_timeout(30);
  10590. int callback_count = 0;
  10591. bool saw_leaf_cert = false;
  10592. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10593. if (ctx.cert) {
  10594. callback_count++;
  10595. // We should see at least one certificate (the leaf)
  10596. std::string cn = ctx.subject_cn();
  10597. if (!cn.empty()) { saw_leaf_cert = true; }
  10598. // Verify context fields are populated
  10599. EXPECT_NE(ctx.session, nullptr);
  10600. EXPECT_GE(ctx.depth, 0);
  10601. }
  10602. return true;
  10603. });
  10604. auto res = cli.Get("/test");
  10605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10606. EXPECT_GT(callback_count, 0);
  10607. EXPECT_TRUE(saw_leaf_cert);
  10608. }
  10609. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10610. using httplib::tls::TlsError;
  10611. // Test that verify_error_to_string returns empty for success
  10612. std::string success_str = TlsError::verify_error_to_string(0);
  10613. EXPECT_TRUE(success_str.empty());
  10614. // Test that verify_error_to_string returns non-empty for error codes
  10615. // Using a common error code (certificate expired)
  10616. std::string error_str =
  10617. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10618. EXPECT_FALSE(error_str.empty());
  10619. }
  10620. TEST(SessionVerifierTest, CertificateAccepted) {
  10621. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10622. ASSERT_TRUE(svr.is_valid());
  10623. svr.Get("/test", [](const Request &, Response &res) {
  10624. res.set_content("ok", "text/plain");
  10625. });
  10626. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10627. auto se = detail::scope_exit([&] {
  10628. svr.stop();
  10629. t.join();
  10630. });
  10631. svr.wait_until_ready();
  10632. SSLClient cli(HOST, PORT);
  10633. cli.enable_server_certificate_verification(false);
  10634. cli.set_connection_timeout(30);
  10635. bool callback_called = false;
  10636. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10637. EXPECT_NE(session, nullptr);
  10638. callback_called = true;
  10639. return SSLVerifierResponse::CertificateAccepted;
  10640. });
  10641. auto res = cli.Get("/test");
  10642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10643. EXPECT_EQ(200, res->status);
  10644. EXPECT_TRUE(callback_called);
  10645. }
  10646. TEST(SessionVerifierTest, CertificateRejected) {
  10647. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10648. ASSERT_TRUE(svr.is_valid());
  10649. svr.Get("/test", [](const Request &, Response &res) {
  10650. res.set_content("ok", "text/plain");
  10651. });
  10652. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10653. auto se = detail::scope_exit([&] {
  10654. svr.stop();
  10655. t.join();
  10656. });
  10657. svr.wait_until_ready();
  10658. SSLClient cli(HOST, PORT);
  10659. cli.enable_server_certificate_verification(false);
  10660. cli.set_connection_timeout(30);
  10661. bool callback_called = false;
  10662. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10663. EXPECT_NE(session, nullptr);
  10664. callback_called = true;
  10665. return SSLVerifierResponse::CertificateRejected;
  10666. });
  10667. auto res = cli.Get("/test");
  10668. EXPECT_FALSE(res);
  10669. EXPECT_TRUE(callback_called);
  10670. }
  10671. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10672. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10673. ASSERT_TRUE(svr.is_valid());
  10674. svr.Get("/test", [](const Request &, Response &res) {
  10675. res.set_content("ok", "text/plain");
  10676. });
  10677. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10678. auto se = detail::scope_exit([&] {
  10679. svr.stop();
  10680. t.join();
  10681. });
  10682. svr.wait_until_ready();
  10683. // NoDecisionMade with verification disabled should succeed (no default check)
  10684. SSLClient cli(HOST, PORT);
  10685. cli.enable_server_certificate_verification(false);
  10686. cli.set_connection_timeout(30);
  10687. bool callback_called = false;
  10688. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10689. EXPECT_NE(session, nullptr);
  10690. callback_called = true;
  10691. return SSLVerifierResponse::NoDecisionMade;
  10692. });
  10693. auto res = cli.Get("/test");
  10694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10695. EXPECT_EQ(200, res->status);
  10696. EXPECT_TRUE(callback_called);
  10697. }
  10698. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10699. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10700. ASSERT_TRUE(svr.is_valid());
  10701. svr.Get("/test", [](const Request &, Response &res) {
  10702. res.set_content("ok", "text/plain");
  10703. });
  10704. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10705. auto se = detail::scope_exit([&] {
  10706. svr.stop();
  10707. t.join();
  10708. });
  10709. svr.wait_until_ready();
  10710. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10711. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10712. // so we only check that the request fails, not whether the callback was
  10713. // called.
  10714. SSLClient cli(HOST, PORT);
  10715. cli.enable_server_certificate_verification(true);
  10716. cli.set_connection_timeout(30);
  10717. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10718. EXPECT_NE(session, nullptr);
  10719. return SSLVerifierResponse::NoDecisionMade;
  10720. });
  10721. auto res = cli.Get("/test");
  10722. EXPECT_FALSE(res);
  10723. }
  10724. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10725. // Test SSL server using PemMemory constructor with client CA certificates
  10726. // Read PEM files
  10727. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10728. read_file(SERVER_CERT_FILE, server_cert_pem);
  10729. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10730. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10731. // Create SSLServer with PemMemory constructor including client CA
  10732. SSLServer::PemMemory server_pem = {
  10733. server_cert_pem.c_str(),
  10734. server_cert_pem.size(),
  10735. server_key_pem.c_str(),
  10736. server_key_pem.size(),
  10737. client_ca_pem.c_str(),
  10738. client_ca_pem.size(),
  10739. nullptr // no password for server key
  10740. };
  10741. SSLServer svr(server_pem);
  10742. ASSERT_TRUE(svr.is_valid());
  10743. // No SSL error should be recorded for valid setup
  10744. EXPECT_EQ(0, svr.ssl_last_error());
  10745. // Set up server endpoints
  10746. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10747. res.set_content("ok", "text/plain");
  10748. });
  10749. // Start server in a thread
  10750. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10751. svr.wait_until_ready();
  10752. // Connect with client certificate (using constructor with paths)
  10753. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10754. cli.enable_server_certificate_verification(false);
  10755. auto res = cli.Get("/test-pem-ca");
  10756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10757. EXPECT_EQ(200, res->status);
  10758. EXPECT_EQ("ok", res->body);
  10759. svr.stop();
  10760. server_thread.join();
  10761. }
  10762. #endif
  10763. #ifdef _WIN32
  10764. TEST(CleanupTest, WSACleanup) {
  10765. int ret = WSACleanup();
  10766. ASSERT_EQ(0, ret);
  10767. }
  10768. #endif
  10769. #ifndef CPPHTTPLIB_SSL_ENABLED
  10770. TEST(NoSSLSupport, SimpleInterface) {
  10771. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10772. }
  10773. #endif
  10774. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10775. TEST(InvalidScheme, SimpleInterface) {
  10776. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10777. }
  10778. #endif
  10779. TEST(NoScheme, SimpleInterface) {
  10780. Client cli("yahoo.com:80");
  10781. ASSERT_TRUE(cli.is_valid());
  10782. }
  10783. TEST(SendAPI, SimpleInterface_Online) {
  10784. Client cli("http://yahoo.com");
  10785. Request req;
  10786. req.method = "GET";
  10787. req.path = "/";
  10788. auto res = cli.send(req);
  10789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10790. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10791. }
  10792. TEST(SendAPI, WithParamsInRequest) {
  10793. Server svr;
  10794. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10795. EXPECT_TRUE(req.has_param("test"));
  10796. EXPECT_EQ("test_value", req.get_param_value("test"));
  10797. });
  10798. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10799. auto se = detail::scope_exit([&] {
  10800. svr.stop();
  10801. t.join();
  10802. ASSERT_FALSE(svr.is_running());
  10803. });
  10804. svr.wait_until_ready();
  10805. Client cli(HOST, PORT);
  10806. {
  10807. Request req;
  10808. req.method = "GET";
  10809. req.path = "/";
  10810. req.params.emplace("test", "test_value");
  10811. auto res = cli.send(req);
  10812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10813. }
  10814. {
  10815. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10817. }
  10818. }
  10819. TEST(ClientImplMethods, GetSocketTest) {
  10820. httplib::Server svr;
  10821. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10822. res.status = StatusCode::OK_200;
  10823. });
  10824. auto port = svr.bind_to_any_port("127.0.0.1");
  10825. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10826. auto se = detail::scope_exit([&] {
  10827. svr.stop();
  10828. thread.join();
  10829. ASSERT_FALSE(svr.is_running());
  10830. });
  10831. svr.wait_until_ready();
  10832. {
  10833. httplib::Client cli("127.0.0.1", port);
  10834. cli.set_keep_alive(true);
  10835. // Use the behavior of cpp-httplib of opening the connection
  10836. // only when the first request happens. If that changes,
  10837. // this test would be obsolete.
  10838. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10839. // This also implicitly tests the server. But other tests would fail much
  10840. // earlier than this one to be considered.
  10841. auto res = cli.Get("/");
  10842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10843. EXPECT_EQ(StatusCode::OK_200, res->status);
  10844. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10845. }
  10846. }
  10847. #ifdef CPPHTTPLIB_SSL_ENABLED
  10848. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10849. Client cli("http://yahoo.com");
  10850. auto res = cli.Get("/");
  10851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10852. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10853. cli.set_follow_location(true);
  10854. res = cli.Get("/");
  10855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10856. EXPECT_EQ(StatusCode::OK_200, res->status);
  10857. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10858. }
  10859. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10860. Client cli("https://yahoo.com");
  10861. auto res = cli.Get("/");
  10862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10863. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10864. cli.set_follow_location(true);
  10865. res = cli.Get("/");
  10866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10867. EXPECT_EQ(StatusCode::OK_200, res->status);
  10868. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10869. }
  10870. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10871. Client cli("https://yahoo.com");
  10872. auto res = cli.Get("/");
  10873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10874. ASSERT_FALSE(!res);
  10875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10876. ASSERT_FALSE(res == nullptr);
  10877. ASSERT_TRUE(res != nullptr);
  10878. EXPECT_EQ(Error::Success, res.error());
  10879. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10880. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10881. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10882. cli.set_follow_location(true);
  10883. res = cli.Get("/");
  10884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10885. EXPECT_EQ(Error::Success, res.error());
  10886. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10887. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10888. EXPECT_EQ(StatusCode::OK_200, res->status);
  10889. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10890. }
  10891. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10892. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10893. Client cli("https://cdnjs.cloudflare.com");
  10894. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10895. Headers{{"Accept-Encoding", "br"}});
  10896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10897. EXPECT_EQ(StatusCode::OK_200, res->status);
  10898. EXPECT_EQ(287630U, res->body.size());
  10899. EXPECT_EQ("application/javascript; charset=utf-8",
  10900. res->get_header_value("Content-Type"));
  10901. }
  10902. #endif
  10903. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10904. #undef REDIR_HOST // Silence compiler warning
  10905. #define REDIR_HOST "https://httpbingo.org"
  10906. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10907. Client cli(REDIR_HOST);
  10908. cli.set_follow_location(true);
  10909. auto res =
  10910. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10912. EXPECT_EQ(StatusCode::OK_200, res->status);
  10913. }
  10914. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10915. Client cli(REDIR_HOST);
  10916. cli.set_follow_location(true);
  10917. Params params;
  10918. params.emplace("url", "http://example.com");
  10919. params.emplace("status_code", "302");
  10920. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10922. EXPECT_EQ(StatusCode::OK_200, res->status);
  10923. }
  10924. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10925. Client cli(REDIR_HOST);
  10926. cli.set_follow_location(true);
  10927. Params params;
  10928. params.emplace("url", "http://example.com");
  10929. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10931. EXPECT_EQ(StatusCode::OK_200, res->status);
  10932. }
  10933. TEST(HttpToHttpsRedirectTest, CertFile) {
  10934. auto ssl_port = PORT + 1;
  10935. Server svr;
  10936. ASSERT_TRUE(svr.is_valid());
  10937. svr.Get("/index", [&](const Request &, Response &res) {
  10938. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10939. "/index");
  10940. svr.stop();
  10941. });
  10942. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10943. ASSERT_TRUE(ssl_svr.is_valid());
  10944. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10945. res.set_content("test", "text/plain");
  10946. ssl_svr.stop();
  10947. });
  10948. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10949. thread t2 =
  10950. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10951. auto se = detail::scope_exit([&] {
  10952. t2.join();
  10953. t.join();
  10954. ASSERT_FALSE(svr.is_running());
  10955. });
  10956. svr.wait_until_ready();
  10957. ssl_svr.wait_until_ready();
  10958. Client cli("127.0.0.1", PORT);
  10959. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10960. cli.enable_server_certificate_verification(true);
  10961. cli.set_follow_location(true);
  10962. cli.set_connection_timeout(30);
  10963. auto res = cli.Get("/index");
  10964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10965. ASSERT_EQ(StatusCode::OK_200, res->status);
  10966. }
  10967. TEST(SSLClientRedirectTest, CertFile) {
  10968. auto ssl_port = PORT + 1;
  10969. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10970. ASSERT_TRUE(ssl_svr1.is_valid());
  10971. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10972. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10973. "/index");
  10974. ssl_svr1.stop();
  10975. });
  10976. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10977. ASSERT_TRUE(ssl_svr2.is_valid());
  10978. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10979. res.set_content("test", "text/plain");
  10980. ssl_svr2.stop();
  10981. });
  10982. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10983. thread t2 =
  10984. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10985. auto se = detail::scope_exit([&] {
  10986. t2.join();
  10987. t.join();
  10988. ASSERT_FALSE(ssl_svr1.is_running());
  10989. });
  10990. ssl_svr1.wait_until_ready();
  10991. ssl_svr2.wait_until_ready();
  10992. SSLClient cli("127.0.0.1", PORT);
  10993. std::string cert;
  10994. read_file(SERVER_CERT2_FILE, cert);
  10995. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10996. cli.enable_server_certificate_verification(true);
  10997. cli.set_follow_location(true);
  10998. cli.set_connection_timeout(30);
  10999. auto res = cli.Get("/index");
  11000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11001. ASSERT_EQ(StatusCode::OK_200, res->status);
  11002. }
  11003. #endif
  11004. #ifdef CPPHTTPLIB_SSL_ENABLED
  11005. // Test that set_ca_cert_store() skips system certs (consistent with
  11006. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11007. // should be trusted - system certs should NOT be loaded.
  11008. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11009. // Load a specific cert that is NOT a system CA cert
  11010. std::string cert;
  11011. read_file(SERVER_CERT2_FILE, cert);
  11012. SSLClient cli("google.com");
  11013. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11014. cli.enable_server_certificate_verification(true);
  11015. // This should FAIL because:
  11016. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11017. // 2. System certs should NOT be loaded when custom store is set
  11018. // If system certs WERE loaded, this would succeed
  11019. auto res = cli.Get("/");
  11020. ASSERT_FALSE(res);
  11021. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11022. }
  11023. // Same as above, but through the native store handle path. Regression test:
  11024. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11025. // merged system certs into the user-provided store.
  11026. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11027. std::string cert;
  11028. read_file(SERVER_CERT2_FILE, cert);
  11029. SSLClient cli("google.com");
  11030. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11031. cli.enable_server_certificate_verification(true);
  11032. auto res = cli.Get("/");
  11033. ASSERT_FALSE(res);
  11034. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11035. }
  11036. // A custom store set via the native handle must still verify a server whose
  11037. // cert it does contain.
  11038. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11039. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11040. ASSERT_TRUE(svr.is_valid());
  11041. svr.Get("/test", [&](const Request &, Response &res) {
  11042. res.set_content("test", "text/plain");
  11043. });
  11044. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11045. auto se = detail::scope_exit([&] {
  11046. svr.stop();
  11047. t.join();
  11048. ASSERT_FALSE(svr.is_running());
  11049. });
  11050. svr.wait_until_ready();
  11051. SSLClient cli("127.0.0.1", PORT);
  11052. std::string cert;
  11053. read_file(SERVER_CERT2_FILE, cert);
  11054. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11055. cli.enable_server_certificate_verification(true);
  11056. cli.set_connection_timeout(30);
  11057. auto res = cli.Get("/test");
  11058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11059. ASSERT_EQ(StatusCode::OK_200, res->status);
  11060. }
  11061. // CA certs loaded through the universal Client must be transferred to the
  11062. // client created internally for following an HTTPS redirect. Regression test:
  11063. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11064. // the CA data for redirect transfer.
  11065. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11066. auto ssl_port = PORT + 1;
  11067. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11068. ASSERT_TRUE(ssl_svr1.is_valid());
  11069. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11070. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11071. "/index");
  11072. });
  11073. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11074. ASSERT_TRUE(ssl_svr2.is_valid());
  11075. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11076. res.set_content("test", "text/plain");
  11077. });
  11078. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11079. thread t2 =
  11080. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11081. auto se = detail::scope_exit([&] {
  11082. ssl_svr2.stop();
  11083. ssl_svr1.stop();
  11084. t2.join();
  11085. t.join();
  11086. ASSERT_FALSE(ssl_svr1.is_running());
  11087. });
  11088. ssl_svr1.wait_until_ready();
  11089. ssl_svr2.wait_until_ready();
  11090. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11091. std::string cert;
  11092. read_file(SERVER_CERT2_FILE, cert);
  11093. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11094. cli.enable_server_certificate_verification(true);
  11095. cli.set_follow_location(true);
  11096. cli.set_connection_timeout(30);
  11097. auto res = cli.Get("/index");
  11098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11099. ASSERT_EQ(StatusCode::OK_200, res->status);
  11100. }
  11101. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11102. // so a host signed by a system CA verifies even though a custom CA is set
  11103. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11104. std::string cert;
  11105. read_file(SERVER_CERT2_FILE, cert);
  11106. SSLClient cli("google.com");
  11107. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11108. cli.enable_system_ca(true);
  11109. cli.enable_server_certificate_verification(true);
  11110. auto res = cli.Get("/");
  11111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11112. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11113. }
  11114. // The custom CA remains effective when combined with the system CA
  11115. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11116. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11117. ASSERT_TRUE(svr.is_valid());
  11118. svr.Get("/test", [&](const Request &, Response &res) {
  11119. res.set_content("test", "text/plain");
  11120. });
  11121. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11122. auto se = detail::scope_exit([&] {
  11123. svr.stop();
  11124. t.join();
  11125. ASSERT_FALSE(svr.is_running());
  11126. });
  11127. svr.wait_until_ready();
  11128. SSLClient cli("127.0.0.1", PORT);
  11129. std::string cert;
  11130. read_file(SERVER_CERT2_FILE, cert);
  11131. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11132. cli.enable_system_ca(true);
  11133. cli.enable_server_certificate_verification(true);
  11134. cli.set_connection_timeout(30);
  11135. auto res = cli.Get("/test");
  11136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11137. ASSERT_EQ(StatusCode::OK_200, res->status);
  11138. }
  11139. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11140. // skip chain verification entirely (only the certificate identity was
  11141. // checked), so a server presenting an untrusted certificate with a matching
  11142. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11143. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11144. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11145. ASSERT_TRUE(svr.is_valid());
  11146. svr.Get("/test", [&](const Request &, Response &res) {
  11147. res.set_content("test", "text/plain");
  11148. });
  11149. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11150. auto se = detail::scope_exit([&] {
  11151. svr.stop();
  11152. t.join();
  11153. ASSERT_FALSE(svr.is_running());
  11154. });
  11155. svr.wait_until_ready();
  11156. SSLClient cli("127.0.0.1", PORT);
  11157. std::string cert;
  11158. // A trusted CA that did not sign the server certificate. The server cert
  11159. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11160. // this connection.
  11161. read_file(CLIENT_CA_CERT_FILE, cert);
  11162. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11163. cli.enable_server_certificate_verification(true);
  11164. cli.set_connection_timeout(30);
  11165. auto res = cli.Get("/test");
  11166. ASSERT_FALSE(res);
  11167. }
  11168. // enable_system_ca(false) prevents system CA loading entirely
  11169. TEST(SSLClientTest, DisableSystemCa_Online) {
  11170. SSLClient cli("google.com");
  11171. cli.enable_system_ca(false);
  11172. cli.enable_server_certificate_verification(true);
  11173. auto res = cli.Get("/");
  11174. ASSERT_FALSE(res);
  11175. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11176. // itself when the CA chain is empty
  11177. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11178. res.error() == Error::SSLConnection);
  11179. }
  11180. // The universal Client forwards enable_system_ca()
  11181. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11182. std::string cert;
  11183. read_file(SERVER_CERT2_FILE, cert);
  11184. Client cli("https://google.com");
  11185. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11186. cli.enable_system_ca(true);
  11187. cli.enable_server_certificate_verification(true);
  11188. auto res = cli.Get("/");
  11189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11190. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11191. }
  11192. // The system CA policy must carry over to the client created internally for
  11193. // following a cross-host HTTPS redirect
  11194. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11195. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11196. ASSERT_TRUE(svr.is_valid());
  11197. svr.Get("/index", [&](const Request &, Response &res) {
  11198. res.set_redirect("https://www.google.com/");
  11199. });
  11200. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11201. auto se = detail::scope_exit([&] {
  11202. svr.stop();
  11203. t.join();
  11204. ASSERT_FALSE(svr.is_running());
  11205. });
  11206. svr.wait_until_ready();
  11207. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11208. std::string cert;
  11209. read_file(SERVER_CERT2_FILE, cert);
  11210. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11211. cli.enable_system_ca(true);
  11212. cli.enable_server_certificate_verification(true);
  11213. cli.set_follow_location(true);
  11214. cli.set_connection_timeout(30);
  11215. // Receiving any response proves the redirect client completed the TLS
  11216. // handshake with a system-CA-signed host
  11217. auto res = cli.Get("/index");
  11218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11219. }
  11220. TEST(MultipartFormDataTest, LargeData) {
  11221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11222. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11223. const ContentReader &content_reader) {
  11224. if (req.is_multipart_form_data()) {
  11225. std::vector<FormData> items;
  11226. content_reader(
  11227. [&](const FormData &file) {
  11228. items.push_back(file);
  11229. return true;
  11230. },
  11231. [&](const char *data, size_t data_length) {
  11232. items.back().content.append(data, data_length);
  11233. return true;
  11234. });
  11235. EXPECT_TRUE(std::string(items[0].name) == "document");
  11236. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11237. EXPECT_TRUE(items[0].filename == "2MB_data");
  11238. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11239. EXPECT_TRUE(items[1].name == "hello");
  11240. EXPECT_TRUE(items[1].content == "world");
  11241. EXPECT_TRUE(items[1].filename == "");
  11242. EXPECT_TRUE(items[1].content_type == "");
  11243. } else {
  11244. std::string body;
  11245. content_reader([&](const char *data, size_t data_length) {
  11246. body.append(data, data_length);
  11247. return true;
  11248. });
  11249. }
  11250. });
  11251. auto port = svr.bind_to_any_port(HOST);
  11252. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11253. auto se = detail::scope_exit([&] {
  11254. svr.stop();
  11255. t.join();
  11256. ASSERT_FALSE(svr.is_running());
  11257. });
  11258. svr.wait_until_ready();
  11259. {
  11260. std::string data(1024 * 1024 * 2, '.');
  11261. std::stringstream buffer;
  11262. buffer << data;
  11263. SSLClient cli(HOST, port);
  11264. cli.enable_server_certificate_verification(false);
  11265. UploadFormDataItems items{
  11266. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11267. {"hello", "world", "", ""},
  11268. };
  11269. auto res = cli.Post("/post", items);
  11270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11271. ASSERT_EQ(StatusCode::OK_200, res->status);
  11272. }
  11273. }
  11274. TEST(MultipartFormDataTest, DataProviderItems) {
  11275. std::random_device seed_gen;
  11276. std::mt19937 random(seed_gen());
  11277. std::string rand1;
  11278. rand1.resize(1000);
  11279. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11280. std::string rand2;
  11281. rand2.resize(3000);
  11282. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11283. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11284. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11285. const ContentReader &content_reader) {
  11286. ASSERT_FALSE(req.is_multipart_form_data());
  11287. std::string body;
  11288. content_reader([&](const char *data, size_t data_length) {
  11289. body.append(data, data_length);
  11290. return true;
  11291. });
  11292. EXPECT_EQ(body, "");
  11293. });
  11294. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11295. const ContentReader &content_reader) {
  11296. ASSERT_TRUE(req.is_multipart_form_data());
  11297. std::vector<FormData> items;
  11298. content_reader(
  11299. [&](const FormData &file) {
  11300. items.push_back(file);
  11301. return true;
  11302. },
  11303. [&](const char *data, size_t data_length) {
  11304. items.back().content.append(data, data_length);
  11305. return true;
  11306. });
  11307. ASSERT_TRUE(items.size() == 2);
  11308. EXPECT_EQ(std::string(items[0].name), "name1");
  11309. EXPECT_EQ(items[0].content, "Testing123");
  11310. EXPECT_EQ(items[0].filename, "filename1");
  11311. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11312. EXPECT_EQ(items[1].name, "name2");
  11313. EXPECT_EQ(items[1].content, "Testing456");
  11314. EXPECT_EQ(items[1].filename, "");
  11315. EXPECT_EQ(items[1].content_type, "");
  11316. });
  11317. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11318. const ContentReader &content_reader) {
  11319. ASSERT_TRUE(req.is_multipart_form_data());
  11320. std::vector<FormData> items;
  11321. content_reader(
  11322. [&](const FormData &file) {
  11323. items.push_back(file);
  11324. return true;
  11325. },
  11326. [&](const char *data, size_t data_length) {
  11327. items.back().content.append(data, data_length);
  11328. return true;
  11329. });
  11330. ASSERT_TRUE(items.size() == 2);
  11331. EXPECT_EQ(items[0].name, "name3");
  11332. EXPECT_EQ(items[0].content, rand1);
  11333. EXPECT_EQ(items[0].filename, "filename3");
  11334. EXPECT_EQ(items[0].content_type, "");
  11335. EXPECT_EQ(items[1].name, "name4");
  11336. EXPECT_EQ(items[1].content, rand2);
  11337. EXPECT_EQ(items[1].filename, "filename4");
  11338. EXPECT_EQ(items[1].content_type, "");
  11339. });
  11340. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11341. const ContentReader &content_reader) {
  11342. ASSERT_TRUE(req.is_multipart_form_data());
  11343. std::vector<FormData> items;
  11344. content_reader(
  11345. [&](const FormData &file) {
  11346. items.push_back(file);
  11347. return true;
  11348. },
  11349. [&](const char *data, size_t data_length) {
  11350. items.back().content.append(data, data_length);
  11351. return true;
  11352. });
  11353. ASSERT_TRUE(items.size() == 4);
  11354. EXPECT_EQ(std::string(items[0].name), "name1");
  11355. EXPECT_EQ(items[0].content, "Testing123");
  11356. EXPECT_EQ(items[0].filename, "filename1");
  11357. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11358. EXPECT_EQ(items[1].name, "name2");
  11359. EXPECT_EQ(items[1].content, "Testing456");
  11360. EXPECT_EQ(items[1].filename, "");
  11361. EXPECT_EQ(items[1].content_type, "");
  11362. EXPECT_EQ(items[2].name, "name3");
  11363. EXPECT_EQ(items[2].content, rand1);
  11364. EXPECT_EQ(items[2].filename, "filename3");
  11365. EXPECT_EQ(items[2].content_type, "");
  11366. EXPECT_EQ(items[3].name, "name4");
  11367. EXPECT_EQ(items[3].content, rand2);
  11368. EXPECT_EQ(items[3].filename, "filename4");
  11369. EXPECT_EQ(items[3].content_type, "");
  11370. });
  11371. auto port = svr.bind_to_any_port("localhost");
  11372. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11373. auto se = detail::scope_exit([&] {
  11374. svr.stop();
  11375. t.join();
  11376. ASSERT_FALSE(svr.is_running());
  11377. });
  11378. svr.wait_until_ready();
  11379. {
  11380. SSLClient cli("localhost", port);
  11381. cli.enable_server_certificate_verification(false);
  11382. UploadFormDataItems items{
  11383. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11384. {"name2", "Testing456", "", ""}, // not a file
  11385. };
  11386. {
  11387. auto res = cli.Post("/post-none", {}, {}, {});
  11388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11389. ASSERT_EQ(StatusCode::OK_200, res->status);
  11390. }
  11391. FormDataProviderItems providers;
  11392. {
  11393. auto res =
  11394. cli.Post("/post-items", {}, items, providers); // empty providers
  11395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11396. ASSERT_EQ(StatusCode::OK_200, res->status);
  11397. }
  11398. providers.push_back({"name3",
  11399. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11400. // test the offset is given correctly at each step
  11401. if (!offset)
  11402. sink.os.write(rand1.data(), 30);
  11403. else if (offset == 30)
  11404. sink.os.write(rand1.data() + 30, 300);
  11405. else if (offset == 330)
  11406. sink.os.write(rand1.data() + 330, 670);
  11407. else if (offset == rand1.size())
  11408. sink.done();
  11409. return true;
  11410. },
  11411. "filename3",
  11412. {}});
  11413. providers.push_back({"name4",
  11414. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11415. // test the offset is given correctly at each step
  11416. if (!offset)
  11417. sink.os.write(rand2.data(), 2000);
  11418. else if (offset == 2000)
  11419. sink.os.write(rand2.data() + 2000, 1);
  11420. else if (offset == 2001)
  11421. sink.os.write(rand2.data() + 2001, 999);
  11422. else if (offset == rand2.size())
  11423. sink.done();
  11424. return true;
  11425. },
  11426. "filename4",
  11427. {}});
  11428. {
  11429. auto res = cli.Post("/post-providers", {}, {}, providers);
  11430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11431. ASSERT_EQ(StatusCode::OK_200, res->status);
  11432. }
  11433. {
  11434. auto res = cli.Post("/post-both", {}, items, providers);
  11435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11436. ASSERT_EQ(StatusCode::OK_200, res->status);
  11437. }
  11438. }
  11439. }
  11440. TEST(MultipartFormDataTest, BadHeader) {
  11441. Server svr;
  11442. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11443. res.set_content("ok", "text/plain");
  11444. });
  11445. thread t = thread([&] { svr.listen(HOST, PORT); });
  11446. auto se = detail::scope_exit([&] {
  11447. svr.stop();
  11448. t.join();
  11449. ASSERT_FALSE(svr.is_running());
  11450. });
  11451. svr.wait_until_ready();
  11452. const std::string body =
  11453. "This is the preamble. It is to be ignored, though it\r\n"
  11454. "is a handy place for composition agents to include an\r\n"
  11455. "explanatory note to non-MIME conformant readers.\r\n"
  11456. "\r\n"
  11457. "\r\n"
  11458. "--simple boundary\r\n"
  11459. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11460. ": BAD...\r\n"
  11461. "\r\n"
  11462. "value1\r\n"
  11463. "--simple boundary\r\n"
  11464. "Content-Disposition: form-data; name=\"field2\"; "
  11465. "filename=\"example.txt\"\r\n"
  11466. "\r\n"
  11467. "value2\r\n"
  11468. "--simple boundary--\r\n"
  11469. "This is the epilogue. It is also to be ignored.\r\n";
  11470. std::string content_type =
  11471. R"(multipart/form-data; boundary="simple boundary")";
  11472. Client cli(HOST, PORT);
  11473. auto res = cli.Post("/post", body, content_type.c_str());
  11474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11475. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11476. }
  11477. TEST(MultipartFormDataTest, WithPreamble) {
  11478. Server svr;
  11479. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11480. res.set_content("ok", "text/plain");
  11481. });
  11482. thread t = thread([&] { svr.listen(HOST, PORT); });
  11483. auto se = detail::scope_exit([&] {
  11484. svr.stop();
  11485. t.join();
  11486. ASSERT_FALSE(svr.is_running());
  11487. });
  11488. svr.wait_until_ready();
  11489. const std::string body =
  11490. "This is the preamble. It is to be ignored, though it\r\n"
  11491. "is a handy place for composition agents to include an\r\n"
  11492. "explanatory note to non-MIME conformant readers.\r\n"
  11493. "\r\n"
  11494. "\r\n"
  11495. "--simple boundary\r\n"
  11496. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11497. "\r\n"
  11498. "value1\r\n"
  11499. "--simple boundary\r\n"
  11500. "Content-Disposition: form-data; name=\"field2\"; "
  11501. "filename=\"example.txt\"\r\n"
  11502. "\r\n"
  11503. "value2\r\n"
  11504. "--simple boundary--\r\n"
  11505. "This is the epilogue. It is also to be ignored.\r\n";
  11506. std::string content_type =
  11507. R"(multipart/form-data; boundary="simple boundary")";
  11508. Client cli(HOST, PORT);
  11509. auto res = cli.Post("/post", body, content_type.c_str());
  11510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11511. EXPECT_EQ(StatusCode::OK_200, res->status);
  11512. }
  11513. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11514. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11515. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11516. const ContentReader &content_reader) {
  11517. if (req.is_multipart_form_data()) {
  11518. std::vector<FormData> items;
  11519. content_reader(
  11520. [&](const FormData &file) {
  11521. items.push_back(file);
  11522. return true;
  11523. },
  11524. [&](const char *data, size_t data_length) {
  11525. items.back().content.append(data, data_length);
  11526. return true;
  11527. });
  11528. EXPECT_TRUE(std::string(items[0].name) == "document");
  11529. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11530. EXPECT_TRUE(items[0].filename == "2MB_data");
  11531. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11532. EXPECT_TRUE(items[1].name == "hello");
  11533. EXPECT_TRUE(items[1].content == "world");
  11534. EXPECT_TRUE(items[1].filename == "");
  11535. EXPECT_TRUE(items[1].content_type == "");
  11536. } else {
  11537. std::string body;
  11538. content_reader([&](const char *data, size_t data_length) {
  11539. body.append(data, data_length);
  11540. return true;
  11541. });
  11542. }
  11543. });
  11544. auto port = svr.bind_to_any_port("localhost");
  11545. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11546. auto se = detail::scope_exit([&] {
  11547. svr.stop();
  11548. t.join();
  11549. ASSERT_FALSE(svr.is_running());
  11550. });
  11551. svr.wait_until_ready();
  11552. {
  11553. std::string data(1024 * 1024 * 2, '.');
  11554. std::stringstream buffer;
  11555. buffer << data;
  11556. SSLClient cli("localhost", port);
  11557. cli.enable_server_certificate_verification(false);
  11558. UploadFormDataItems items{
  11559. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11560. {"hello", "world", "", ""},
  11561. };
  11562. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11564. ASSERT_EQ(StatusCode::OK_200, res->status);
  11565. }
  11566. }
  11567. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11568. std::string data(1024 * 1024 * 2, '&');
  11569. std::stringstream buffer;
  11570. buffer << data;
  11571. Client cli("https://localhost:8080");
  11572. UploadFormDataItems items{
  11573. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11574. {"hello", "world", "", ""},
  11575. };
  11576. for (const char &c : " \t\r\n") {
  11577. auto res =
  11578. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11579. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11580. ASSERT_FALSE(res);
  11581. }
  11582. }
  11583. TEST(MultipartFormDataTest, PutFormData) {
  11584. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11585. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11586. const ContentReader &content_reader) {
  11587. if (req.is_multipart_form_data()) {
  11588. std::vector<FormData> items;
  11589. content_reader(
  11590. [&](const FormData &file) {
  11591. items.push_back(file);
  11592. return true;
  11593. },
  11594. [&](const char *data, size_t data_length) {
  11595. items.back().content.append(data, data_length);
  11596. return true;
  11597. });
  11598. EXPECT_TRUE(std::string(items[0].name) == "document");
  11599. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11600. EXPECT_TRUE(items[0].filename == "2MB_data");
  11601. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11602. EXPECT_TRUE(items[1].name == "hello");
  11603. EXPECT_TRUE(items[1].content == "world");
  11604. EXPECT_TRUE(items[1].filename == "");
  11605. EXPECT_TRUE(items[1].content_type == "");
  11606. } else {
  11607. std::string body;
  11608. content_reader([&](const char *data, size_t data_length) {
  11609. body.append(data, data_length);
  11610. return true;
  11611. });
  11612. }
  11613. });
  11614. auto port = svr.bind_to_any_port("localhost");
  11615. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11616. auto se = detail::scope_exit([&] {
  11617. svr.stop();
  11618. t.join();
  11619. ASSERT_FALSE(svr.is_running());
  11620. });
  11621. svr.wait_until_ready();
  11622. {
  11623. std::string data(1024 * 1024 * 2, '&');
  11624. std::stringstream buffer;
  11625. buffer << data;
  11626. SSLClient cli("localhost", port);
  11627. cli.enable_server_certificate_verification(false);
  11628. UploadFormDataItems items{
  11629. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11630. {"hello", "world", "", ""},
  11631. };
  11632. auto res = cli.Put("/put", items);
  11633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11634. ASSERT_EQ(StatusCode::OK_200, res->status);
  11635. }
  11636. }
  11637. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11638. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11639. svr.Put("/put_customboundary",
  11640. [&](const Request &req, const Response & /*res*/,
  11641. const ContentReader &content_reader) {
  11642. if (req.is_multipart_form_data()) {
  11643. std::vector<FormData> items;
  11644. content_reader(
  11645. [&](const FormData &file) {
  11646. items.push_back(file);
  11647. return true;
  11648. },
  11649. [&](const char *data, size_t data_length) {
  11650. items.back().content.append(data, data_length);
  11651. return true;
  11652. });
  11653. EXPECT_TRUE(std::string(items[0].name) == "document");
  11654. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11655. EXPECT_TRUE(items[0].filename == "2MB_data");
  11656. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11657. EXPECT_TRUE(items[1].name == "hello");
  11658. EXPECT_TRUE(items[1].content == "world");
  11659. EXPECT_TRUE(items[1].filename == "");
  11660. EXPECT_TRUE(items[1].content_type == "");
  11661. } else {
  11662. std::string body;
  11663. content_reader([&](const char *data, size_t data_length) {
  11664. body.append(data, data_length);
  11665. return true;
  11666. });
  11667. }
  11668. });
  11669. auto port = svr.bind_to_any_port("localhost");
  11670. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11671. auto se = detail::scope_exit([&] {
  11672. svr.stop();
  11673. t.join();
  11674. ASSERT_FALSE(svr.is_running());
  11675. });
  11676. svr.wait_until_ready();
  11677. {
  11678. std::string data(1024 * 1024 * 2, '&');
  11679. std::stringstream buffer;
  11680. buffer << data;
  11681. SSLClient cli("localhost", port);
  11682. cli.enable_server_certificate_verification(false);
  11683. UploadFormDataItems items{
  11684. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11685. {"hello", "world", "", ""},
  11686. };
  11687. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11689. ASSERT_EQ(StatusCode::OK_200, res->status);
  11690. }
  11691. }
  11692. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11693. std::string data(1024 * 1024 * 2, '&');
  11694. std::stringstream buffer;
  11695. buffer << data;
  11696. Client cli("https://localhost:8080");
  11697. cli.enable_server_certificate_verification(false);
  11698. UploadFormDataItems items{
  11699. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11700. {"hello", "world", "", ""},
  11701. };
  11702. for (const char &c : " \t\r\n") {
  11703. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11704. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11705. ASSERT_FALSE(res);
  11706. }
  11707. }
  11708. TEST(MultipartFormDataTest, AlternateFilename) {
  11709. auto handled = false;
  11710. Server svr;
  11711. svr.Post("/test", [&](const Request &req, Response &res) {
  11712. ASSERT_EQ(2u, req.form.files.size());
  11713. ASSERT_EQ(1u, req.form.fields.size());
  11714. // Test files
  11715. const auto &file1 = req.form.get_file("file1");
  11716. ASSERT_EQ("file1", file1.name);
  11717. ASSERT_EQ("A.txt", file1.filename);
  11718. ASSERT_EQ("text/plain", file1.content_type);
  11719. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11720. const auto &file2 = req.form.get_file("file2");
  11721. ASSERT_EQ("file2", file2.name);
  11722. ASSERT_EQ("a.html", file2.filename);
  11723. ASSERT_EQ("text/html", file2.content_type);
  11724. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11725. file2.content);
  11726. // Test text field
  11727. const auto &text = req.form.get_field("text");
  11728. ASSERT_EQ("text default", text);
  11729. res.set_content("ok", "text/plain");
  11730. handled = true;
  11731. });
  11732. thread t = thread([&] { svr.listen(HOST, PORT); });
  11733. auto se = detail::scope_exit([&] {
  11734. svr.stop();
  11735. t.join();
  11736. ASSERT_FALSE(svr.is_running());
  11737. ASSERT_TRUE(handled);
  11738. });
  11739. svr.wait_until_ready();
  11740. auto req = "POST /test HTTP/1.1\r\n"
  11741. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11742. "Content-Length: 399\r\n"
  11743. "\r\n"
  11744. "----------\r\n"
  11745. "Content-Disposition: form-data; name=\"text\"\r\n"
  11746. "\r\n"
  11747. "text default\r\n"
  11748. "----------\r\n"
  11749. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11750. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11751. "Content-Type: text/plain\r\n"
  11752. "\r\n"
  11753. "Content of a.txt.\r\n"
  11754. "\r\n"
  11755. "----------\r\n"
  11756. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11757. "\"a.html\"\r\n"
  11758. "Content-Type: text/html\r\n"
  11759. "\r\n"
  11760. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11761. "\r\n"
  11762. "------------\r\n";
  11763. ASSERT_TRUE(send_request(1, req));
  11764. }
  11765. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11766. auto handled = false;
  11767. Server svr;
  11768. svr.Post("/test", [&](const Request &req, Response &res) {
  11769. // Case-insensitive "utf-8''" prefix with a long value
  11770. const auto &file = req.form.get_file("file1");
  11771. ASSERT_EQ("file1", file.name);
  11772. // 8000 chars exercises both the Content-Disposition parser and the
  11773. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11774. // Prior to the fix, std::regex_match on this header would cause O(N)
  11775. // stack recursion in libstdc++, leading to SIGSEGV.
  11776. std::string expected_filename(8000, 'A');
  11777. ASSERT_EQ(expected_filename, file.filename);
  11778. res.set_content("ok", "text/plain");
  11779. handled = true;
  11780. });
  11781. thread t = thread([&] { svr.listen(HOST, PORT); });
  11782. auto se = detail::scope_exit([&] {
  11783. svr.stop();
  11784. t.join();
  11785. ASSERT_FALSE(svr.is_running());
  11786. ASSERT_TRUE(handled);
  11787. });
  11788. svr.wait_until_ready();
  11789. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11790. // Regression test for GHSA-qq6v-r583-3h69
  11791. std::string long_filename(8000, 'A');
  11792. std::string body = "----------\r\n"
  11793. "Content-Disposition: form-data; name=\"file1\"; "
  11794. "filename*=\"Utf-8''" +
  11795. long_filename +
  11796. "\"\r\n"
  11797. "\r\n"
  11798. "hello\r\n"
  11799. "------------\r\n";
  11800. auto req = "POST /test HTTP/1.1\r\n"
  11801. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11802. "Content-Length: " +
  11803. std::to_string(body.size()) + "\r\n\r\n" + body;
  11804. ASSERT_TRUE(send_request(1, req));
  11805. }
  11806. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11807. auto handled = false;
  11808. Server svr;
  11809. svr.Post("/test", [&](const Request &req, Response &) {
  11810. ASSERT_EQ(2u, req.form.fields.size());
  11811. const auto &text1 = req.form.get_field("text1");
  11812. ASSERT_EQ("text1", text1);
  11813. const auto &text2 = req.form.get_field("text2");
  11814. ASSERT_EQ("text2", text2);
  11815. handled = true;
  11816. });
  11817. thread t = thread([&] { svr.listen(HOST, PORT); });
  11818. auto se = detail::scope_exit([&] {
  11819. svr.stop();
  11820. t.join();
  11821. ASSERT_FALSE(svr.is_running());
  11822. ASSERT_TRUE(handled);
  11823. });
  11824. svr.wait_until_ready();
  11825. auto req = "POST /test HTTP/1.1\r\n"
  11826. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11827. "Content-Length: 146\r\n"
  11828. "\r\n----------\r\n"
  11829. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11830. "\r\n"
  11831. "text1"
  11832. "\r\n----------\r\n"
  11833. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11834. "\r\n"
  11835. "text2"
  11836. "\r\n------------";
  11837. std::string response;
  11838. ASSERT_TRUE(send_request(1, req, &response));
  11839. ASSERT_EQ("200", response.substr(9, 3));
  11840. }
  11841. TEST(MultipartFormDataTest, ContentLength) {
  11842. auto handled = false;
  11843. Server svr;
  11844. svr.Post("/test", [&](const Request &req, Response &) {
  11845. ASSERT_EQ(2u, req.form.fields.size());
  11846. const auto &text1 = req.form.get_field("text1");
  11847. ASSERT_EQ("text1", text1);
  11848. const auto &text2 = req.form.get_field("text2");
  11849. ASSERT_EQ("text2", text2);
  11850. handled = true;
  11851. });
  11852. thread t = thread([&] { svr.listen(HOST, PORT); });
  11853. auto se = detail::scope_exit([&] {
  11854. svr.stop();
  11855. t.join();
  11856. ASSERT_FALSE(svr.is_running());
  11857. ASSERT_TRUE(handled);
  11858. });
  11859. svr.wait_until_ready();
  11860. auto req = "POST /test HTTP/1.1\r\n"
  11861. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11862. "Content-Length: 167\r\n"
  11863. "\r\n----------\r\n"
  11864. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11865. "Content-Length: 5\r\n"
  11866. "\r\n"
  11867. "text1"
  11868. "\r\n----------\r\n"
  11869. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11870. "\r\n"
  11871. "text2"
  11872. "\r\n------------\r\n";
  11873. std::string response;
  11874. ASSERT_TRUE(send_request(1, req, &response));
  11875. ASSERT_EQ("200", response.substr(9, 3));
  11876. }
  11877. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11878. auto handled = false;
  11879. Server svr;
  11880. svr.Post("/test", [&](const Request &req, Response &) {
  11881. ASSERT_EQ(2u, req.form.fields.size());
  11882. const auto &text1 = req.form.get_field("text1");
  11883. ASSERT_EQ("text1", text1);
  11884. // TODO: Add header access for text fields if needed
  11885. const auto &text2 = req.form.get_field("text2");
  11886. ASSERT_EQ("text2", text2);
  11887. // TODO: Header access for text fields needs to be implemented
  11888. // auto &headers = it->second.headers;
  11889. // ASSERT_EQ(3U, headers.size());
  11890. // auto custom_header = headers.find("x-whatever");
  11891. // ASSERT_TRUE(custom_header != headers.end());
  11892. // ASSERT_NE("customvalue", custom_header->second);
  11893. // ASSERT_EQ("CustomValue", custom_header->second);
  11894. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11895. handled = true;
  11896. });
  11897. thread t = thread([&] { svr.listen(HOST, PORT); });
  11898. auto se = detail::scope_exit([&] {
  11899. svr.stop();
  11900. t.join();
  11901. ASSERT_FALSE(svr.is_running());
  11902. ASSERT_TRUE(handled);
  11903. });
  11904. svr.wait_until_ready();
  11905. auto req = "POST /test HTTP/1.1\r\n"
  11906. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11907. "Content-Length: 232\r\n"
  11908. "\r\n----------\r\n"
  11909. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11910. "Content-Length: 5\r\n"
  11911. "X-Test: 1\r\n"
  11912. "\r\n"
  11913. "text1"
  11914. "\r\n----------\r\n"
  11915. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11916. "Content-Type: text/plain\r\n"
  11917. "X-Whatever: CustomValue\r\n"
  11918. "\r\n"
  11919. "text2"
  11920. "\r\n------------\r\n"
  11921. "That should be disregarded. Not even read";
  11922. std::string response;
  11923. ASSERT_TRUE(send_request(1, req, &response));
  11924. ASSERT_EQ("200", response.substr(9, 3));
  11925. }
  11926. TEST(MultipartFormDataTest, LargeHeader) {
  11927. auto handled = false;
  11928. Server svr;
  11929. svr.Post("/test", [&](const Request &req, Response &) {
  11930. ASSERT_EQ(1u, req.form.fields.size());
  11931. const auto &text = req.form.get_field("name1");
  11932. ASSERT_EQ("text1", text);
  11933. handled = true;
  11934. });
  11935. thread t = thread([&] { svr.listen(HOST, PORT); });
  11936. auto se = detail::scope_exit([&] {
  11937. svr.stop();
  11938. t.join();
  11939. ASSERT_FALSE(svr.is_running());
  11940. ASSERT_TRUE(handled);
  11941. });
  11942. svr.wait_until_ready();
  11943. auto boundary = std::string("cpp-httplib-multipart-data");
  11944. std::string content = "--" + boundary +
  11945. "\r\n"
  11946. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11947. "\r\n"
  11948. "text1\r\n"
  11949. "--" +
  11950. boundary + "--\r\n";
  11951. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11952. "Content-Type: multipart/form-data;boundary=" +
  11953. boundary +
  11954. "\r\n"
  11955. "Content-Length: " +
  11956. std::to_string(content.size()) +
  11957. "\r\n"
  11958. "Dummy-Header: ";
  11959. std::string header_suffix = "\r\n"
  11960. "\r\n";
  11961. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11962. size_t header_dummy_size =
  11963. read_buff_size -
  11964. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11965. auto header_dummy = std::string(header_dummy_size, '@');
  11966. auto req = header_prefix + header_dummy + header_suffix + content;
  11967. std::string response;
  11968. ASSERT_TRUE(send_request(1, req, &response));
  11969. ASSERT_EQ("200", response.substr(9, 3));
  11970. }
  11971. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11972. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11973. // (not chunked Transfer-Encoding) after the streaming refactor.
  11974. auto handled = false;
  11975. Server svr;
  11976. svr.Post("/upload", [&](const Request &req, Response &res) {
  11977. auto cl_it = req.headers.find("Content-Length");
  11978. EXPECT_TRUE(cl_it != req.headers.end());
  11979. auto te_it = req.headers.find("Transfer-Encoding");
  11980. EXPECT_TRUE(te_it == req.headers.end());
  11981. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11982. res.set_content("ok", "text/plain");
  11983. handled = true;
  11984. });
  11985. auto port = svr.bind_to_any_port(HOST);
  11986. auto t = thread([&] { svr.listen_after_bind(); });
  11987. auto se = detail::scope_exit([&] {
  11988. svr.stop();
  11989. t.join();
  11990. ASSERT_FALSE(svr.is_running());
  11991. ASSERT_TRUE(handled);
  11992. });
  11993. svr.wait_until_ready();
  11994. UploadFormDataItems items = {
  11995. {"field1", "hello", "", "text/plain"},
  11996. {"file1", "world", "test.txt", "application/octet-stream"},
  11997. };
  11998. Client cli(HOST, port);
  11999. auto res = cli.Post("/upload", {}, items);
  12000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12001. EXPECT_EQ(StatusCode::OK_200, res->status);
  12002. }
  12003. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12004. // Verify that make_multipart_content_provider coalesces many small segments
  12005. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12006. constexpr size_t kItemCount = 1000;
  12007. UploadFormDataItems items;
  12008. items.reserve(kItemCount);
  12009. for (size_t i = 0; i < kItemCount; i++) {
  12010. items.push_back(
  12011. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12012. }
  12013. const std::string boundary = "----test-boundary";
  12014. auto content_length = detail::get_multipart_content_length(items, boundary);
  12015. auto provider = detail::make_multipart_content_provider(items, boundary);
  12016. // Drive the provider the same way write_content_with_progress does
  12017. size_t write_count = 0;
  12018. size_t total_bytes = 0;
  12019. DataSink sink;
  12020. size_t offset = 0;
  12021. sink.write = [&](const char *d, size_t l) -> bool {
  12022. (void)d;
  12023. write_count++;
  12024. total_bytes += l;
  12025. offset += l;
  12026. return true;
  12027. };
  12028. sink.is_writable = []() -> bool { return true; };
  12029. while (offset < content_length) {
  12030. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12031. }
  12032. EXPECT_EQ(content_length, total_bytes);
  12033. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12034. // With buffering into 64KB blocks, write_count should be much smaller.
  12035. auto segment_count = 3 * kItemCount + 1;
  12036. EXPECT_LT(write_count, segment_count / 10);
  12037. }
  12038. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12039. // Integration test: send many UploadFormDataItems and verify the server
  12040. // receives all of them correctly (#2410).
  12041. constexpr size_t kItemCount = 500;
  12042. auto handled = false;
  12043. Server svr;
  12044. svr.Post("/upload", [&](const Request &req, Response &res) {
  12045. EXPECT_EQ(kItemCount, req.form.fields.size());
  12046. for (size_t i = 0; i < kItemCount; i++) {
  12047. auto key = "field" + std::to_string(i);
  12048. auto val = "value" + std::to_string(i);
  12049. auto it = req.form.fields.find(key);
  12050. if (it != req.form.fields.end()) {
  12051. EXPECT_EQ(val, it->second.content);
  12052. } else {
  12053. ADD_FAILURE() << "Missing field: " << key;
  12054. }
  12055. }
  12056. res.set_content("ok", "text/plain");
  12057. handled = true;
  12058. });
  12059. auto port = svr.bind_to_any_port(HOST);
  12060. auto t = thread([&] { svr.listen_after_bind(); });
  12061. auto se = detail::scope_exit([&] {
  12062. svr.stop();
  12063. t.join();
  12064. ASSERT_FALSE(svr.is_running());
  12065. ASSERT_TRUE(handled);
  12066. });
  12067. svr.wait_until_ready();
  12068. UploadFormDataItems items;
  12069. items.reserve(kItemCount);
  12070. for (size_t i = 0; i < kItemCount; i++) {
  12071. items.push_back(
  12072. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12073. }
  12074. Client cli(HOST, port);
  12075. auto res = cli.Post("/upload", items);
  12076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12077. EXPECT_EQ(StatusCode::OK_200, res->status);
  12078. }
  12079. TEST(MultipartFormDataTest, MakeFileProvider) {
  12080. // Verify make_file_provider sends a file's contents correctly.
  12081. const std::string file_content(4096, 'Z');
  12082. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12083. {
  12084. std::ofstream ofs(tmp_path, std::ios::binary);
  12085. ofs.write(file_content.data(),
  12086. static_cast<std::streamsize>(file_content.size()));
  12087. }
  12088. auto handled = false;
  12089. Server svr;
  12090. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12091. const ContentReader &content_reader) {
  12092. ASSERT_TRUE(req.is_multipart_form_data());
  12093. std::vector<FormData> items;
  12094. content_reader(
  12095. [&](const FormData &file) {
  12096. items.push_back(file);
  12097. return true;
  12098. },
  12099. [&](const char *data, size_t data_length) {
  12100. items.back().content.append(data, data_length);
  12101. return true;
  12102. });
  12103. ASSERT_EQ(1u, items.size());
  12104. EXPECT_EQ("myfile", items[0].name);
  12105. EXPECT_EQ("data.bin", items[0].filename);
  12106. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12107. EXPECT_EQ(file_content, items[0].content);
  12108. handled = true;
  12109. });
  12110. auto port = svr.bind_to_any_port(HOST);
  12111. auto t = thread([&] { svr.listen_after_bind(); });
  12112. auto se = detail::scope_exit([&] {
  12113. svr.stop();
  12114. t.join();
  12115. ASSERT_FALSE(svr.is_running());
  12116. ASSERT_TRUE(handled);
  12117. std::remove(tmp_path.c_str());
  12118. });
  12119. svr.wait_until_ready();
  12120. FormDataProviderItems providers;
  12121. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12122. "application/octet-stream"));
  12123. Client cli(HOST, port);
  12124. auto res = cli.Post("/upload", {}, {}, providers);
  12125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12126. EXPECT_EQ(StatusCode::OK_200, res->status);
  12127. }
  12128. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12129. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12130. // (100) headers is rejected with a 400 Bad Request response.
  12131. Server svr;
  12132. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12133. res.set_content("ok", "text/plain");
  12134. });
  12135. thread t = thread([&] { svr.listen(HOST, PORT); });
  12136. auto se = detail::scope_exit([&] {
  12137. svr.stop();
  12138. t.join();
  12139. ASSERT_FALSE(svr.is_running());
  12140. });
  12141. svr.wait_until_ready();
  12142. // Build a multipart part with 101 custom headers (exceeding
  12143. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12144. std::stringstream body;
  12145. body << "--simpleboundary\r\n"
  12146. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12147. for (int i = 0; i < 101; i++) {
  12148. body << "X-Custom-Header-" << i << ": value\r\n";
  12149. }
  12150. body << "\r\n"
  12151. << "value1\r\n"
  12152. << "--simpleboundary--\r\n";
  12153. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12154. Client cli(HOST, PORT);
  12155. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12157. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12158. }
  12159. TEST(MakeFileBodyTest, Basic) {
  12160. const std::string file_content(4096, 'Z');
  12161. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12162. {
  12163. std::ofstream ofs(tmp_path, std::ios::binary);
  12164. ofs.write(file_content.data(),
  12165. static_cast<std::streamsize>(file_content.size()));
  12166. }
  12167. auto handled = false;
  12168. Server svr;
  12169. svr.Post("/upload", [&](const Request &req, Response &res) {
  12170. EXPECT_EQ(file_content, req.body);
  12171. handled = true;
  12172. res.status = StatusCode::OK_200;
  12173. });
  12174. auto port = svr.bind_to_any_port(HOST);
  12175. auto t = thread([&] { svr.listen_after_bind(); });
  12176. auto se = detail::scope_exit([&] {
  12177. svr.stop();
  12178. t.join();
  12179. ASSERT_FALSE(svr.is_running());
  12180. ASSERT_TRUE(handled);
  12181. std::remove(tmp_path.c_str());
  12182. });
  12183. svr.wait_until_ready();
  12184. auto fb = make_file_body(tmp_path);
  12185. ASSERT_GT(fb.first, 0u);
  12186. Client cli(HOST, port);
  12187. auto res =
  12188. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12190. EXPECT_EQ(StatusCode::OK_200, res->status);
  12191. }
  12192. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12193. static constexpr unsigned int number_of_tasks{1000000};
  12194. std::atomic_uint count{0};
  12195. std::unique_ptr<TaskQueue> task_queue{
  12196. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12197. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12198. auto queued = task_queue->enqueue(
  12199. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12200. EXPECT_TRUE(queued);
  12201. }
  12202. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12203. task_queue->shutdown();
  12204. #else
  12205. EXPECT_NO_THROW(task_queue->shutdown());
  12206. #endif
  12207. EXPECT_EQ(number_of_tasks, count.load());
  12208. }
  12209. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12210. static constexpr unsigned int number_of_tasks{1000000};
  12211. static constexpr unsigned int qlimit{2};
  12212. unsigned int queued_count{0};
  12213. std::atomic_uint count{0};
  12214. std::unique_ptr<TaskQueue> task_queue{
  12215. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12216. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12217. if (task_queue->enqueue(
  12218. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12219. queued_count++;
  12220. }
  12221. }
  12222. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12223. task_queue->shutdown();
  12224. #else
  12225. EXPECT_NO_THROW(task_queue->shutdown());
  12226. #endif
  12227. EXPECT_EQ(queued_count, count.load());
  12228. EXPECT_TRUE(queued_count <= number_of_tasks);
  12229. EXPECT_TRUE(queued_count >= qlimit);
  12230. }
  12231. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12232. // Use a short idle timeout so a dynamic thread spawns, times out and
  12233. // exits during the test, and the pool keeps working afterwards.
  12234. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12235. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12236. /*idle_timeout_sec=*/1}};
  12237. std::atomic_uint count{0};
  12238. std::condition_variable cv;
  12239. std::mutex mtx;
  12240. bool release = false;
  12241. // Block the base thread so the second task spawns a dynamic thread.
  12242. EXPECT_TRUE(task_queue->enqueue([&] {
  12243. std::unique_lock<std::mutex> lock(mtx);
  12244. while (!release) {
  12245. cv.wait(lock);
  12246. }
  12247. count++;
  12248. }));
  12249. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12250. // Let the dynamic thread finish its task and exceed the idle timeout.
  12251. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12252. {
  12253. std::unique_lock<std::mutex> lock(mtx);
  12254. release = true;
  12255. }
  12256. cv.notify_all();
  12257. // The pool must still accept and run tasks after the dynamic thread exited.
  12258. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12259. task_queue->shutdown();
  12260. EXPECT_EQ(3u, count.load());
  12261. }
  12262. TEST(TaskQueueTest, MaxQueuedRequests) {
  12263. static constexpr unsigned int qlimit{3};
  12264. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12265. std::condition_variable sem_cv;
  12266. std::mutex sem_mtx;
  12267. int credits = 0;
  12268. bool queued;
  12269. /* Fill up the queue with tasks that will block until we give them credits to
  12270. * complete. */
  12271. for (unsigned int n = 0; n <= qlimit;) {
  12272. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12273. std::unique_lock<std::mutex> lock(sem_mtx);
  12274. while (credits <= 0) {
  12275. sem_cv.wait(lock);
  12276. }
  12277. /* Consume the credit and signal the test code if they are all gone. */
  12278. if (--credits == 0) { sem_cv.notify_one(); }
  12279. });
  12280. if (n < qlimit) {
  12281. /* The first qlimit enqueues must succeed. */
  12282. EXPECT_TRUE(queued);
  12283. } else {
  12284. /* The last one will succeed only when the worker thread
  12285. * starts and dequeues the first blocking task. Although
  12286. * not necessary for the correctness of this test, we sleep for
  12287. * a short while to avoid busy waiting. */
  12288. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12289. }
  12290. if (queued) { n++; }
  12291. }
  12292. /* Further enqueues must fail since the queue is full. */
  12293. for (auto i = 0; i < 4; i++) {
  12294. queued = task_queue->enqueue([] {});
  12295. EXPECT_FALSE(queued);
  12296. }
  12297. /* Give the credits to allow the previous tasks to complete. */
  12298. {
  12299. std::unique_lock<std::mutex> lock(sem_mtx);
  12300. credits += qlimit + 1;
  12301. }
  12302. sem_cv.notify_all();
  12303. /* Wait for all the credits to be consumed. */
  12304. {
  12305. std::unique_lock<std::mutex> lock(sem_mtx);
  12306. while (credits > 0) {
  12307. sem_cv.wait(lock);
  12308. }
  12309. }
  12310. /* Check that we are able again to enqueue at least qlimit tasks. */
  12311. for (unsigned int i = 0; i < qlimit; i++) {
  12312. queued = task_queue->enqueue([] {});
  12313. EXPECT_TRUE(queued);
  12314. }
  12315. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12316. task_queue->shutdown();
  12317. #else
  12318. EXPECT_NO_THROW(task_queue->shutdown());
  12319. #endif
  12320. }
  12321. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12322. Server svr;
  12323. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12324. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12325. });
  12326. svr.Get("/hello", [](const Request &req, Response &res) {
  12327. res.set_content(req.get_param_value("key"), "text/plain");
  12328. });
  12329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12330. auto se = detail::scope_exit([&] {
  12331. svr.stop();
  12332. thread.join();
  12333. ASSERT_FALSE(svr.is_running());
  12334. });
  12335. svr.wait_until_ready();
  12336. {
  12337. Client cli(HOST, PORT);
  12338. cli.set_follow_location(true);
  12339. auto res = cli.Get("/");
  12340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12341. EXPECT_EQ(StatusCode::OK_200, res->status);
  12342. EXPECT_EQ("val&key2=val2", res->body);
  12343. }
  12344. }
  12345. #endif
  12346. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12347. Server svr;
  12348. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12349. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12350. });
  12351. svr.Get("/hello", [](const Request &req, Response &res) {
  12352. res.set_content(req.get_param_value("key"), "text/plain");
  12353. });
  12354. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12355. auto se = detail::scope_exit([&] {
  12356. svr.stop();
  12357. thread.join();
  12358. ASSERT_FALSE(svr.is_running());
  12359. });
  12360. svr.wait_until_ready();
  12361. {
  12362. Client cli(HOST, PORT);
  12363. cli.set_follow_location(true);
  12364. auto res = cli.Get("/");
  12365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12366. EXPECT_EQ(StatusCode::OK_200, res->status);
  12367. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12368. }
  12369. }
  12370. TEST(RedirectTest, RedirectWithPlusInPath) {
  12371. Server svr;
  12372. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12373. res.set_redirect("/a+b");
  12374. });
  12375. // Route pattern uses regex; escape + as \\+
  12376. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12377. res.set_content(req.path, "text/plain");
  12378. });
  12379. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12380. auto se = detail::scope_exit([&] {
  12381. svr.stop();
  12382. thread.join();
  12383. ASSERT_FALSE(svr.is_running());
  12384. });
  12385. svr.wait_until_ready();
  12386. {
  12387. Client cli(HOST, PORT);
  12388. cli.set_follow_location(true);
  12389. auto res = cli.Get("/");
  12390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12391. EXPECT_EQ(StatusCode::OK_200, res->status);
  12392. EXPECT_EQ("/a+b", res->body);
  12393. }
  12394. }
  12395. #ifdef CPPHTTPLIB_SSL_ENABLED
  12396. TEST(RedirectTest, Issue2185_Online) {
  12397. SSLClient client("github.com");
  12398. client.set_follow_location(true);
  12399. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12400. "Coollab-Windows.zip");
  12401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12402. EXPECT_EQ(StatusCode::OK_200, res->status);
  12403. EXPECT_EQ(9920427U, res->body.size());
  12404. }
  12405. #endif
  12406. TEST(VulnerabilityTest, CRLFInjection) {
  12407. Server svr;
  12408. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12409. res.set_content("Hello 1", "text/plain");
  12410. });
  12411. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12412. res.set_content("Hello 2", "text/plain");
  12413. });
  12414. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12415. res.set_content("Hello 3", "text/plain");
  12416. });
  12417. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12418. res.set_content("Hello 4", "text/plain");
  12419. });
  12420. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12421. for (const auto &x : req.headers) {
  12422. auto key = x.first;
  12423. EXPECT_STRNE("evil", key.c_str());
  12424. }
  12425. });
  12426. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12427. auto se = detail::scope_exit([&] {
  12428. svr.stop();
  12429. thread.join();
  12430. ASSERT_FALSE(svr.is_running());
  12431. });
  12432. svr.wait_until_ready();
  12433. {
  12434. Client cli(HOST, PORT);
  12435. cli.Post("/test1", "A=B",
  12436. "application/x-www-form-urlencoded\r\nevil: hello1");
  12437. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12438. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12439. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12440. }
  12441. }
  12442. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12443. auto server_thread = std::thread([] {
  12444. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12445. default_socket_options(srv);
  12446. sockaddr_in addr{};
  12447. addr.sin_family = AF_INET;
  12448. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12449. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12450. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12451. ::listen(srv, 1);
  12452. sockaddr_in cli_addr{};
  12453. socklen_t cli_len = sizeof(cli_addr);
  12454. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12455. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12456. std::string buf_all;
  12457. char buf[2048];
  12458. ssize_t n;
  12459. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12460. buf_all.append(buf, static_cast<size_t>(n));
  12461. size_t pos;
  12462. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12463. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12464. auto e = request_block.find("\r\n");
  12465. if (e != std::string::npos) {
  12466. auto request_line = request_block.substr(0, e);
  12467. std::string msg =
  12468. "CRLF injection detected in request line: '" + request_line + "'";
  12469. EXPECT_FALSE(true) << msg;
  12470. }
  12471. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12472. ::send(cli,
  12473. #ifdef _WIN32
  12474. static_cast<const char *>(resp.c_str()),
  12475. static_cast<int>(resp.size()),
  12476. #else
  12477. resp.c_str(), resp.size(),
  12478. #endif
  12479. 0);
  12480. buf_all.erase(0, pos + 4);
  12481. }
  12482. }
  12483. detail::close_socket(cli);
  12484. detail::close_socket(srv);
  12485. });
  12486. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12487. auto cli = Client("127.0.0.1", PORT + 1);
  12488. auto headers = Headers{
  12489. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12490. {"Connection", "keep-alive"}};
  12491. auto res = cli.Get("/hi", headers);
  12492. EXPECT_FALSE(res);
  12493. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12494. server_thread.join();
  12495. }
  12496. TEST(PathParamsTest, StaticMatch) {
  12497. const auto pattern = "/users/all";
  12498. detail::PathParamsMatcher matcher(pattern);
  12499. Request request;
  12500. request.path = "/users/all";
  12501. ASSERT_TRUE(matcher.match(request));
  12502. std::unordered_map<std::string, std::string> expected_params = {};
  12503. EXPECT_EQ(request.path_params, expected_params);
  12504. }
  12505. TEST(PathParamsTest, StaticMismatch) {
  12506. const auto pattern = "/users/all";
  12507. detail::PathParamsMatcher matcher(pattern);
  12508. Request request;
  12509. request.path = "/users/1";
  12510. ASSERT_FALSE(matcher.match(request));
  12511. }
  12512. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12513. const auto pattern = "/users/:id/subscriptions";
  12514. detail::PathParamsMatcher matcher(pattern);
  12515. Request request;
  12516. request.path = "/users/42/subscriptions";
  12517. ASSERT_TRUE(matcher.match(request));
  12518. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12519. EXPECT_EQ(request.path_params, expected_params);
  12520. }
  12521. TEST(PathParamsTest, SingleParamInTheEnd) {
  12522. const auto pattern = "/users/:id";
  12523. detail::PathParamsMatcher matcher(pattern);
  12524. Request request;
  12525. request.path = "/users/24";
  12526. ASSERT_TRUE(matcher.match(request));
  12527. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12528. EXPECT_EQ(request.path_params, expected_params);
  12529. }
  12530. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12531. const auto pattern = "/users/:id/";
  12532. detail::PathParamsMatcher matcher(pattern);
  12533. Request request;
  12534. request.path = "/users/42/";
  12535. ASSERT_TRUE(matcher.match(request));
  12536. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12537. EXPECT_EQ(request.path_params, expected_params);
  12538. }
  12539. TEST(PathParamsTest, EmptyParam) {
  12540. const auto pattern = "/users/:id/";
  12541. detail::PathParamsMatcher matcher(pattern);
  12542. Request request;
  12543. request.path = "/users//";
  12544. ASSERT_TRUE(matcher.match(request));
  12545. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12546. EXPECT_EQ(request.path_params, expected_params);
  12547. }
  12548. TEST(PathParamsTest, FragmentMismatch) {
  12549. const auto pattern = "/users/:id/";
  12550. detail::PathParamsMatcher matcher(pattern);
  12551. Request request;
  12552. request.path = "/admins/24/";
  12553. ASSERT_FALSE(matcher.match(request));
  12554. }
  12555. TEST(PathParamsTest, ExtraFragments) {
  12556. const auto pattern = "/users/:id";
  12557. detail::PathParamsMatcher matcher(pattern);
  12558. Request request;
  12559. request.path = "/users/42/subscriptions";
  12560. ASSERT_FALSE(matcher.match(request));
  12561. }
  12562. TEST(PathParamsTest, MissingTrailingParam) {
  12563. const auto pattern = "/users/:id";
  12564. detail::PathParamsMatcher matcher(pattern);
  12565. Request request;
  12566. request.path = "/users";
  12567. ASSERT_FALSE(matcher.match(request));
  12568. }
  12569. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12570. const auto pattern = "/users/:id/subscriptions";
  12571. detail::PathParamsMatcher matcher(pattern);
  12572. Request request;
  12573. request.path = "/users/subscriptions";
  12574. ASSERT_FALSE(matcher.match(request));
  12575. }
  12576. TEST(PathParamsTest, MultipleParams) {
  12577. const auto pattern = "/users/:userid/subscriptions/:subid";
  12578. detail::PathParamsMatcher matcher(pattern);
  12579. Request request;
  12580. request.path = "/users/42/subscriptions/2";
  12581. ASSERT_TRUE(matcher.match(request));
  12582. std::unordered_map<std::string, std::string> expected_params = {
  12583. {"userid", "42"}, {"subid", "2"}};
  12584. EXPECT_EQ(request.path_params, expected_params);
  12585. }
  12586. TEST(PathParamsTest, SequenceOfParams) {
  12587. const auto pattern = "/values/:x/:y/:z";
  12588. detail::PathParamsMatcher matcher(pattern);
  12589. Request request;
  12590. request.path = "/values/1/2/3";
  12591. ASSERT_TRUE(matcher.match(request));
  12592. std::unordered_map<std::string, std::string> expected_params = {
  12593. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12594. EXPECT_EQ(request.path_params, expected_params);
  12595. }
  12596. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12597. const auto pattern = "/prefix:suffix";
  12598. detail::PathParamsMatcher matcher(pattern);
  12599. Request request;
  12600. request.path = "/prefix:suffix";
  12601. ASSERT_TRUE(matcher.match(request));
  12602. const std::unordered_map<std::string, std::string> expected_params = {};
  12603. EXPECT_EQ(request.path_params, expected_params);
  12604. }
  12605. TEST(ParseUrlTest, VariousPatterns) {
  12606. {
  12607. detail::UrlComponents uc;
  12608. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12609. EXPECT_EQ("http", uc.scheme);
  12610. EXPECT_EQ("example.com", uc.host);
  12611. EXPECT_EQ("8080", uc.port);
  12612. EXPECT_EQ("/path", uc.path);
  12613. EXPECT_EQ("?q=1", uc.query);
  12614. }
  12615. {
  12616. detail::UrlComponents uc;
  12617. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12618. EXPECT_EQ("https", uc.scheme);
  12619. EXPECT_EQ("example.com", uc.host);
  12620. EXPECT_TRUE(uc.port.empty());
  12621. EXPECT_EQ("/path", uc.path);
  12622. }
  12623. {
  12624. detail::UrlComponents uc;
  12625. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12626. EXPECT_EQ("::1", uc.host);
  12627. EXPECT_EQ("8080", uc.port);
  12628. EXPECT_EQ("/path", uc.path);
  12629. }
  12630. {
  12631. detail::UrlComponents uc;
  12632. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12633. }
  12634. {
  12635. detail::UrlComponents uc;
  12636. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12637. EXPECT_TRUE(uc.scheme.empty());
  12638. EXPECT_EQ("example.com", uc.host);
  12639. EXPECT_EQ("/path", uc.path);
  12640. EXPECT_EQ("?q=1", uc.query);
  12641. }
  12642. {
  12643. detail::UrlComponents uc;
  12644. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12645. EXPECT_TRUE(uc.host.empty());
  12646. EXPECT_EQ("/path", uc.path);
  12647. EXPECT_EQ("?q=1", uc.query);
  12648. }
  12649. {
  12650. detail::UrlComponents uc;
  12651. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12652. EXPECT_EQ("example.com", uc.host);
  12653. EXPECT_EQ("8080", uc.port);
  12654. }
  12655. {
  12656. // Unix socket path — must not be parsed as host
  12657. detail::UrlComponents uc;
  12658. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12659. EXPECT_TRUE(uc.host.empty());
  12660. }
  12661. {
  12662. detail::UrlComponents uc;
  12663. ASSERT_TRUE(detail::parse_url("", uc));
  12664. EXPECT_TRUE(uc.host.empty());
  12665. EXPECT_TRUE(uc.path.empty());
  12666. }
  12667. {
  12668. detail::UrlComponents uc;
  12669. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12670. }
  12671. {
  12672. detail::UrlComponents uc;
  12673. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12674. }
  12675. {
  12676. // Accepted by parse_url; callers restrict to http/https
  12677. detail::UrlComponents uc;
  12678. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12679. EXPECT_EQ("ftp", uc.scheme);
  12680. }
  12681. {
  12682. detail::UrlComponents uc;
  12683. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12684. }
  12685. {
  12686. detail::UrlComponents uc;
  12687. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12688. }
  12689. }
  12690. TEST(ParseUrlTest, FragmentHandling) {
  12691. {
  12692. detail::UrlComponents uc;
  12693. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12694. EXPECT_EQ("/path", uc.path);
  12695. EXPECT_TRUE(uc.query.empty());
  12696. }
  12697. {
  12698. detail::UrlComponents uc;
  12699. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12700. EXPECT_TRUE(uc.path.empty());
  12701. EXPECT_TRUE(uc.query.empty());
  12702. }
  12703. }
  12704. TEST(ParseUrlTest, UserinfoHandling) {
  12705. // Userinfo with @ but no colon — host includes @
  12706. detail::UrlComponents uc;
  12707. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12708. EXPECT_EQ("user@host.com", uc.host);
  12709. EXPECT_EQ("/path", uc.path);
  12710. }
  12711. TEST(ParseUrlTest, IPv6EdgeCases) {
  12712. {
  12713. detail::UrlComponents uc;
  12714. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12715. EXPECT_TRUE(uc.scheme.empty());
  12716. EXPECT_EQ("::1", uc.host);
  12717. EXPECT_EQ("8080", uc.port);
  12718. }
  12719. {
  12720. // Zone ID '%25' is not in [a-fA-F0-9:]
  12721. detail::UrlComponents uc;
  12722. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12723. }
  12724. }
  12725. TEST(ParseUrlTest, SchemeEdgeCases) {
  12726. {
  12727. detail::UrlComponents uc;
  12728. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12729. }
  12730. {
  12731. detail::UrlComponents uc;
  12732. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12733. }
  12734. {
  12735. detail::UrlComponents uc;
  12736. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12737. }
  12738. }
  12739. TEST(ParseUrlTest, PortEdgeCases) {
  12740. {
  12741. detail::UrlComponents uc;
  12742. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12743. EXPECT_TRUE(uc.port.empty());
  12744. EXPECT_EQ("/path", uc.path);
  12745. }
  12746. {
  12747. // parse_url accepts any port string; validation is done by parse_port
  12748. detail::UrlComponents uc;
  12749. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12750. EXPECT_EQ("abc", uc.port);
  12751. }
  12752. }
  12753. TEST(ParseUrlTest, WebSocketPatterns) {
  12754. {
  12755. detail::UrlComponents uc;
  12756. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12757. EXPECT_EQ("ws", uc.scheme);
  12758. EXPECT_EQ("echo.example.com", uc.host);
  12759. EXPECT_EQ("8080", uc.port);
  12760. EXPECT_EQ("/ws", uc.path);
  12761. }
  12762. {
  12763. detail::UrlComponents uc;
  12764. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12765. EXPECT_EQ("wss", uc.scheme);
  12766. EXPECT_EQ("echo.example.com", uc.host);
  12767. EXPECT_TRUE(uc.port.empty());
  12768. EXPECT_EQ("/ws", uc.path);
  12769. }
  12770. }
  12771. TEST(ParseUrlTest, QueryOnly) {
  12772. detail::UrlComponents uc;
  12773. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12774. EXPECT_TRUE(uc.host.empty());
  12775. EXPECT_TRUE(uc.path.empty());
  12776. EXPECT_EQ("?q=1&r=2", uc.query);
  12777. }
  12778. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12779. detail::UrlComponents uc;
  12780. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12781. EXPECT_TRUE(uc.scheme.empty());
  12782. EXPECT_EQ("example.com", uc.host);
  12783. EXPECT_EQ("443", uc.port);
  12784. EXPECT_EQ("/path", uc.path);
  12785. }
  12786. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12787. // If ipv6 regex working, regex match codepath is taken.
  12788. // else port will default to 80 in Client impl
  12789. int clientImplMagicPort = 80;
  12790. int port = 4321;
  12791. // above ports must be different to avoid false negative
  12792. EXPECT_NE(clientImplMagicPort, port);
  12793. std::string ipV6TestURL = "http://[ff06::c3]";
  12794. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12795. CLIENT_PRIVATE_KEY_FILE);
  12796. EXPECT_EQ(cli.port(), port);
  12797. }
  12798. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12799. auto file_path = "./www/dir/index.html";
  12800. auto dir_path = "./www/dir";
  12801. detail::FileStat stat_file(file_path);
  12802. EXPECT_TRUE(stat_file.is_file());
  12803. EXPECT_FALSE(stat_file.is_dir());
  12804. detail::FileStat stat_dir(dir_path);
  12805. EXPECT_FALSE(stat_dir.is_file());
  12806. EXPECT_TRUE(stat_dir.is_dir());
  12807. }
  12808. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12809. // IPv4 with default HTTP port (80)
  12810. EXPECT_EQ("example.com",
  12811. detail::make_host_and_port_string("example.com", 80, false));
  12812. // IPv4 with default HTTPS port (443)
  12813. EXPECT_EQ("example.com",
  12814. detail::make_host_and_port_string("example.com", 443, true));
  12815. // IPv4 with non-default HTTP port
  12816. EXPECT_EQ("example.com:8080",
  12817. detail::make_host_and_port_string("example.com", 8080, false));
  12818. // IPv4 with non-default HTTPS port
  12819. EXPECT_EQ("example.com:8443",
  12820. detail::make_host_and_port_string("example.com", 8443, true));
  12821. // IPv6 with default HTTP port (80)
  12822. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12823. // IPv6 with default HTTPS port (443)
  12824. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12825. // IPv6 with non-default HTTP port
  12826. EXPECT_EQ("[::1]:8080",
  12827. detail::make_host_and_port_string("::1", 8080, false));
  12828. // IPv6 with non-default HTTPS port
  12829. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12830. // IPv6 full address with default port
  12831. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12832. detail::make_host_and_port_string(
  12833. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12834. // IPv6 full address with non-default port
  12835. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12836. detail::make_host_and_port_string(
  12837. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12838. // IPv6 localhost with non-default port
  12839. EXPECT_EQ("[::1]:3000",
  12840. detail::make_host_and_port_string("::1", 3000, false));
  12841. // IPv6 with zone ID (link-local address) with default port
  12842. EXPECT_EQ("[fe80::1%eth0]",
  12843. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12844. // IPv6 with zone ID (link-local address) with non-default port
  12845. EXPECT_EQ("[fe80::1%eth0]:8080",
  12846. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12847. // Edge case: Port 443 with is_ssl=false (should add port)
  12848. EXPECT_EQ("example.com:443",
  12849. detail::make_host_and_port_string("example.com", 443, false));
  12850. // Edge case: Port 80 with is_ssl=true (should add port)
  12851. EXPECT_EQ("example.com:80",
  12852. detail::make_host_and_port_string("example.com", 80, true));
  12853. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12854. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12855. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12856. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12857. // Security fix: Already bracketed IPv6 should not get double brackets
  12858. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12859. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12860. EXPECT_EQ("[::1]:8080",
  12861. detail::make_host_and_port_string("[::1]", 8080, false));
  12862. EXPECT_EQ("[2001:db8::1]:8080",
  12863. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12864. EXPECT_EQ("[fe80::1%eth0]",
  12865. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12866. EXPECT_EQ("[fe80::1%eth0]:8080",
  12867. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12868. // Edge case: Empty host (should return as-is)
  12869. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12870. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12871. // This is a known limitation but shouldn't crash
  12872. EXPECT_EQ("[host:name]",
  12873. detail::make_host_and_port_string("host:name", 80, false));
  12874. // Port number edge cases (no validation, but should not crash)
  12875. EXPECT_EQ("example.com:0",
  12876. detail::make_host_and_port_string("example.com", 0, false));
  12877. EXPECT_EQ("example.com:-1",
  12878. detail::make_host_and_port_string("example.com", -1, false));
  12879. EXPECT_EQ("example.com:65535",
  12880. detail::make_host_and_port_string("example.com", 65535, false));
  12881. EXPECT_EQ("example.com:65536",
  12882. detail::make_host_and_port_string("example.com", 65536, false));
  12883. }
  12884. #ifdef CPPHTTPLIB_SSL_ENABLED
  12885. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12886. httplib::SSLClient cli("roblox.com", 443);
  12887. cli.set_follow_location(true);
  12888. auto res = cli.Get("/");
  12889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12890. EXPECT_EQ(StatusCode::OK_200, res->status);
  12891. }
  12892. #endif
  12893. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12894. Server svr;
  12895. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12896. EXPECT_EQ(res.status, 400);
  12897. });
  12898. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12899. auto se = detail::scope_exit([&] {
  12900. svr.stop();
  12901. thread.join();
  12902. ASSERT_FALSE(svr.is_running());
  12903. });
  12904. svr.wait_until_ready();
  12905. Client cli(HOST, PORT);
  12906. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12907. }
  12908. TEST(InvalidHeaderCharsTest, is_field_name) {
  12909. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12910. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12911. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12912. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12913. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12914. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12915. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12916. EXPECT_FALSE(detail::fields::is_field_name(""));
  12917. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12918. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12919. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12920. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12921. }
  12922. TEST(InvalidHeaderCharsTest, is_field_value) {
  12923. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12924. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12925. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12926. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12927. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12928. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12929. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12930. EXPECT_TRUE(detail::fields::is_field_value(""));
  12931. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12932. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12933. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12934. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12935. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12936. }
  12937. TEST(InvalidHeaderCharsTest, OnServer) {
  12938. Server svr;
  12939. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12940. std::string header = "Not Set";
  12941. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12942. res.set_header(header, "value");
  12943. res.set_content("Page Content Page Content", "text/plain");
  12944. });
  12945. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12946. std::string header = "Not Set";
  12947. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12948. res.set_header("X-Test", header);
  12949. res.set_content("Page Content Page Content", "text/plain");
  12950. });
  12951. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12952. auto se = detail::scope_exit([&] {
  12953. svr.stop();
  12954. thread.join();
  12955. ASSERT_FALSE(svr.is_running());
  12956. });
  12957. svr.wait_until_ready();
  12958. Client cli(HOST, PORT);
  12959. {
  12960. auto res = cli.Get(
  12961. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12963. EXPECT_EQ("Page Content Page Content", res->body);
  12964. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12965. }
  12966. {
  12967. auto res = cli.Get(
  12968. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12970. EXPECT_EQ("Page Content Page Content", res->body);
  12971. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12972. }
  12973. }
  12974. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12975. auto handled = false;
  12976. Server svr;
  12977. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12978. thread t = thread([&] { svr.listen(HOST, PORT); });
  12979. auto se = detail::scope_exit([&] {
  12980. svr.stop();
  12981. t.join();
  12982. ASSERT_FALSE(svr.is_running());
  12983. ASSERT_FALSE(handled);
  12984. });
  12985. svr.wait_until_ready();
  12986. auto req = "POST /test HTTP/1.1\r\n"
  12987. "Content-Length: x\r\n"
  12988. "\r\n";
  12989. std::string response;
  12990. ASSERT_TRUE(send_request(1, req, &response));
  12991. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12992. response.substr(0, response.find("\r\n")));
  12993. }
  12994. #ifndef _WIN32
  12995. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12996. static constexpr char reject[] = "Unauthorized";
  12997. static constexpr char accept[] = "Upload accepted";
  12998. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12999. Server svr;
  13000. svr.set_expect_100_continue_handler(
  13001. [](const Request & /*req*/, Response &res) {
  13002. res.status = StatusCode::Unauthorized_401;
  13003. res.set_content(reject, "text/plain");
  13004. return res.status;
  13005. });
  13006. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13007. res.set_content(accept, "text/plain");
  13008. });
  13009. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13010. auto se = detail::scope_exit([&] {
  13011. svr.stop();
  13012. thread.join();
  13013. ASSERT_FALSE(svr.is_running());
  13014. });
  13015. svr.wait_until_ready();
  13016. {
  13017. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13018. curl_easy_init(), &curl_easy_cleanup};
  13019. ASSERT_NE(curl, nullptr);
  13020. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13021. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13022. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13023. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13024. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13025. &curl_slist_free_all};
  13026. ASSERT_NE(list, nullptr);
  13027. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13028. struct read_data {
  13029. size_t read_size;
  13030. size_t total_size;
  13031. } data = {0, total_size};
  13032. using read_callback_t =
  13033. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13034. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13035. void *userdata) -> size_t {
  13036. read_data *d = (read_data *)userdata;
  13037. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13038. std::fill_n(ptr, size * nmemb, 'A');
  13039. d->read_size += size * nmemb;
  13040. return size * nmemb;
  13041. };
  13042. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13043. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13044. std::vector<char> buffer;
  13045. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13046. using write_callback_t =
  13047. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13048. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13049. void *userdata) -> size_t {
  13050. std::vector<char> *buf = (std::vector<char> *)userdata;
  13051. buf->reserve(buf->size() + size * nmemb + 1);
  13052. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13053. return size * nmemb;
  13054. };
  13055. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13056. {
  13057. const auto res = curl_easy_perform(curl.get());
  13058. ASSERT_EQ(res, CURLE_OK);
  13059. }
  13060. {
  13061. auto response_code = long{};
  13062. const auto res =
  13063. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13064. ASSERT_EQ(res, CURLE_OK);
  13065. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13066. }
  13067. {
  13068. auto dl = curl_off_t{};
  13069. const auto res =
  13070. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13071. ASSERT_EQ(res, CURLE_OK);
  13072. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13073. }
  13074. {
  13075. buffer.push_back('\0');
  13076. ASSERT_STRCASEEQ(buffer.data(), reject);
  13077. }
  13078. }
  13079. }
  13080. #endif
  13081. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13082. // Regression test for #2458.
  13083. //
  13084. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13085. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13086. // ticket can make the client socket spuriously readable during the
  13087. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13088. // the client withholds the body and then blocks reading a response that never
  13089. // comes, failing with `Failed to read connection`.
  13090. //
  13091. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13092. // within the timeout. This raw OpenSSL server deliberately never sends
  13093. // `100 Continue`; the client must still deliver the body and receive 200.
  13094. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13095. signal(SIGPIPE, SIG_IGN);
  13096. const auto port = PORT + 4;
  13097. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13098. ASSERT_NE(srv, INVALID_SOCKET);
  13099. int opt = 1;
  13100. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13101. sockaddr_in addr{};
  13102. addr.sin_family = AF_INET;
  13103. addr.sin_port = htons(static_cast<uint16_t>(port));
  13104. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13105. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13106. ASSERT_EQ(0, ::listen(srv, 1));
  13107. std::atomic<size_t> server_body_bytes{0};
  13108. auto server_thread = std::thread([&] {
  13109. sockaddr_in cli_addr{};
  13110. socklen_t cli_len = sizeof(cli_addr);
  13111. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13112. if (cli == INVALID_SOCKET) { return; }
  13113. // Bound the lifetime of the server side so a buggy client (which never
  13114. // sends the body) cannot make this thread block forever on join.
  13115. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13116. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13117. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13118. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13119. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13120. SSL *ssl = SSL_new(ctx);
  13121. SSL_set_fd(ssl, static_cast<int>(cli));
  13122. if (SSL_accept(ssl) > 0) {
  13123. // Read the request headers. Reading here also flushes the TLS 1.3
  13124. // session tickets to the client. Deliberately do NOT send
  13125. // `100 Continue`.
  13126. std::string buf;
  13127. char tmp[1024];
  13128. while (buf.find("\r\n\r\n") == std::string::npos) {
  13129. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13130. if (n <= 0) { break; }
  13131. buf.append(tmp, static_cast<size_t>(n));
  13132. }
  13133. // A correct client sends the body now; count what arrives.
  13134. auto pos = buf.find("\r\n\r\n");
  13135. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13136. while (body < 4096) {
  13137. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13138. if (n <= 0) { break; }
  13139. body += static_cast<size_t>(n);
  13140. }
  13141. server_body_bytes = body;
  13142. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13143. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13144. SSL_shutdown(ssl);
  13145. }
  13146. SSL_free(ssl);
  13147. detail::close_socket(cli);
  13148. SSL_CTX_free(ctx);
  13149. });
  13150. auto se = detail::scope_exit([&] {
  13151. server_thread.join();
  13152. detail::close_socket(srv);
  13153. });
  13154. SSLClient cli("127.0.0.1", port);
  13155. cli.enable_server_certificate_verification(false);
  13156. cli.set_connection_timeout(5, 0);
  13157. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13158. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13159. std::string body(4096, 'A');
  13160. auto res = cli.Put("/api/test", body, "application/json");
  13161. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13162. EXPECT_EQ(StatusCode::OK_200, res->status);
  13163. EXPECT_EQ(body.size(), server_body_bytes.load());
  13164. }
  13165. #endif
  13166. template <typename S, typename C>
  13167. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13168. svr.Get("/stream", [&](const Request &, Response &res) {
  13169. auto data = new std::string("01234567890123456789");
  13170. res.set_content_provider(
  13171. data->size(), "text/plain",
  13172. [&, data](size_t offset, size_t length, DataSink &sink) {
  13173. const size_t DATA_CHUNK_SIZE = 4;
  13174. const auto &d = *data;
  13175. std::this_thread::sleep_for(std::chrono::seconds(1));
  13176. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13177. return true;
  13178. },
  13179. [data](bool success) {
  13180. EXPECT_FALSE(success);
  13181. delete data;
  13182. });
  13183. });
  13184. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13185. auto i = new size_t(0);
  13186. res.set_content_provider(
  13187. "text/plain",
  13188. [i](size_t, DataSink &sink) {
  13189. if (*i < 5) {
  13190. std::this_thread::sleep_for(std::chrono::seconds(1));
  13191. sink.write("abcd", 4);
  13192. (*i)++;
  13193. } else {
  13194. sink.done();
  13195. }
  13196. return true;
  13197. },
  13198. [i](bool success) {
  13199. EXPECT_FALSE(success);
  13200. delete i;
  13201. });
  13202. });
  13203. svr.Get("/chunked", [&](const Request &, Response &res) {
  13204. auto i = new size_t(0);
  13205. res.set_chunked_content_provider(
  13206. "text/plain",
  13207. [i](size_t, DataSink &sink) {
  13208. if (*i < 5) {
  13209. std::this_thread::sleep_for(std::chrono::seconds(1));
  13210. sink.os << "abcd";
  13211. (*i)++;
  13212. } else {
  13213. sink.done();
  13214. }
  13215. return true;
  13216. },
  13217. [i](bool success) {
  13218. EXPECT_FALSE(success);
  13219. delete i;
  13220. });
  13221. });
  13222. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13223. auto se = detail::scope_exit([&] {
  13224. svr.stop();
  13225. listen_thread.join();
  13226. ASSERT_FALSE(svr.is_running());
  13227. });
  13228. svr.wait_until_ready();
  13229. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13230. {
  13231. auto start = std::chrono::steady_clock::now();
  13232. auto res = cli.Get("/stream");
  13233. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13234. std::chrono::steady_clock::now() - start)
  13235. .count();
  13236. ASSERT_FALSE(res);
  13237. EXPECT_EQ(Error::Read, res.error());
  13238. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13239. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13240. }
  13241. {
  13242. auto start = std::chrono::steady_clock::now();
  13243. auto res = cli.Get("/stream_without_length");
  13244. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13245. std::chrono::steady_clock::now() - start)
  13246. .count();
  13247. ASSERT_FALSE(res);
  13248. EXPECT_EQ(Error::Read, res.error());
  13249. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13250. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13251. }
  13252. {
  13253. auto start = std::chrono::steady_clock::now();
  13254. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13255. EXPECT_EQ("abcd", string(data, data_length));
  13256. return true;
  13257. });
  13258. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13259. std::chrono::steady_clock::now() - start)
  13260. .count();
  13261. ASSERT_FALSE(res);
  13262. EXPECT_EQ(Error::Read, res.error());
  13263. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13264. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13265. }
  13266. }
  13267. TEST(MaxTimeoutTest, ContentStream) {
  13268. time_t timeout = 2000;
  13269. time_t threshold = 200;
  13270. Server svr;
  13271. Client cli("localhost", PORT);
  13272. max_timeout_test(svr, cli, timeout, threshold);
  13273. }
  13274. #ifdef CPPHTTPLIB_SSL_ENABLED
  13275. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13276. time_t timeout = 2000;
  13277. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13278. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13279. SSLClient cli("localhost", PORT);
  13280. cli.enable_server_certificate_verification(false);
  13281. max_timeout_test(svr, cli, timeout, threshold);
  13282. }
  13283. #endif
  13284. class EventDispatcher {
  13285. public:
  13286. EventDispatcher() {}
  13287. bool wait_event(DataSink *sink) {
  13288. unique_lock<mutex> lk(m_);
  13289. int id = id_;
  13290. // Wait with timeout to prevent hanging if client disconnects
  13291. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13292. [&] { return cid_ == id; })) {
  13293. return false; // Timeout occurred
  13294. }
  13295. sink->write(message_.data(), message_.size());
  13296. return true;
  13297. }
  13298. void send_event(const string &message) {
  13299. lock_guard<mutex> lk(m_);
  13300. cid_ = id_++;
  13301. message_ = message;
  13302. cv_.notify_all();
  13303. }
  13304. private:
  13305. mutex m_;
  13306. condition_variable cv_;
  13307. atomic_int id_{0};
  13308. atomic_int cid_{-1};
  13309. string message_;
  13310. };
  13311. TEST(ClientInThreadTest, Issue2068) {
  13312. EventDispatcher ed;
  13313. Server svr;
  13314. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13315. res.set_chunked_content_provider("text/event-stream",
  13316. [&](size_t /*offset*/, DataSink &sink) {
  13317. return ed.wait_event(&sink);
  13318. });
  13319. });
  13320. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13321. svr.wait_until_ready();
  13322. thread event_thread([&] {
  13323. int id = 0;
  13324. while (svr.is_running()) {
  13325. this_thread::sleep_for(chrono::milliseconds(500));
  13326. std::stringstream ss;
  13327. ss << "data: " << id << "\n\n";
  13328. ed.send_event(ss.str());
  13329. id++;
  13330. }
  13331. });
  13332. auto se = detail::scope_exit([&] {
  13333. svr.stop();
  13334. listen_thread.join();
  13335. event_thread.join();
  13336. ASSERT_FALSE(svr.is_running());
  13337. });
  13338. {
  13339. auto client = detail::make_unique<Client>(HOST, PORT);
  13340. client->set_read_timeout(std::chrono::minutes(10));
  13341. std::atomic<bool> stop{false};
  13342. std::thread t([&] {
  13343. client->Get("/event1",
  13344. [&](const char *, size_t) -> bool { return !stop; });
  13345. });
  13346. std::this_thread::sleep_for(std::chrono::seconds(2));
  13347. stop = true;
  13348. client->stop();
  13349. t.join();
  13350. // Reset client after thread has finished
  13351. client.reset();
  13352. }
  13353. }
  13354. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13355. auto handled = false;
  13356. Server svr;
  13357. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13358. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13359. auto se = detail::scope_exit([&] {
  13360. svr.stop();
  13361. t.join();
  13362. ASSERT_FALSE(svr.is_running());
  13363. ASSERT_FALSE(handled);
  13364. });
  13365. svr.wait_until_ready();
  13366. // Two Content-Length headers with different values — must be rejected
  13367. auto req = "POST /test HTTP/1.1\r\n"
  13368. "Content-Length: 5\r\n"
  13369. "Content-Length: 10\r\n"
  13370. "\r\n"
  13371. "hello";
  13372. std::string response;
  13373. ASSERT_TRUE(send_request(1, req, &response));
  13374. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13375. response.substr(0, response.find("\r\n")));
  13376. }
  13377. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13378. auto handled = false;
  13379. Server svr;
  13380. svr.Post("/test", [&](const Request &, Response &res) {
  13381. handled = true;
  13382. res.set_content("ok", "text/plain");
  13383. });
  13384. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13385. auto se = detail::scope_exit([&] {
  13386. svr.stop();
  13387. t.join();
  13388. ASSERT_FALSE(svr.is_running());
  13389. ASSERT_TRUE(handled);
  13390. });
  13391. svr.wait_until_ready();
  13392. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13393. auto req = "POST /test HTTP/1.1\r\n"
  13394. "Content-Length: 5\r\n"
  13395. "Content-Length: 5\r\n"
  13396. "\r\n"
  13397. "hello";
  13398. std::string response;
  13399. ASSERT_TRUE(send_request(1, req, &response));
  13400. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13401. }
  13402. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13403. Server svr;
  13404. svr.Get("/", [](const Request &req, Response &res) {
  13405. EXPECT_EQ(2U, req.trailers.size());
  13406. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13407. // Denied
  13408. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13409. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13410. // Accepted
  13411. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13412. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13413. EXPECT_TRUE(req.has_trailer("X-World"));
  13414. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13415. res.set_content("ok", "text/plain");
  13416. });
  13417. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13418. auto se = detail::scope_exit([&] {
  13419. svr.stop();
  13420. t.join();
  13421. ASSERT_FALSE(svr.is_running());
  13422. });
  13423. svr.wait_until_ready();
  13424. const std::string req = "GET / HTTP/1.1\r\n"
  13425. "Transfer-Encoding: chunked\r\n"
  13426. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13427. "\r\n"
  13428. "0\r\n"
  13429. "Content-Length: 10\r\n"
  13430. "Host: internal.local\r\n"
  13431. "Content-Type: malicious/content\r\n"
  13432. "Cookie: any\r\n"
  13433. "Set-Cookie: any\r\n"
  13434. "X-Forwarded-For: attacker.com\r\n"
  13435. "X-Real-Ip: 1.1.1.1\r\n"
  13436. "X-Hello: hello\r\n"
  13437. "X-World: world\r\n"
  13438. "\r\n";
  13439. std::string res;
  13440. ASSERT_TRUE(send_request(1, req, &res));
  13441. }
  13442. // A direct client that is not listed in trusted_proxies must not be able to
  13443. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13444. // the peer address on the actual TCP connection determines whether the
  13445. // header is honored.
  13446. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13447. Server svr;
  13448. // Deliberately does NOT include the loopback address the test client
  13449. // actually connects from, so the direct connection is not a trusted proxy.
  13450. svr.set_trusted_proxies({"203.0.113.66"});
  13451. std::string observed_remote_addr;
  13452. svr.Get("/ip", [&](const Request &req, Response &res) {
  13453. observed_remote_addr = req.remote_addr;
  13454. res.set_content("ok", "text/plain");
  13455. });
  13456. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13457. auto se = detail::scope_exit([&] {
  13458. svr.stop();
  13459. t.join();
  13460. ASSERT_FALSE(svr.is_running());
  13461. });
  13462. svr.wait_until_ready();
  13463. Client cli(HOST, PORT);
  13464. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13466. EXPECT_EQ(StatusCode::OK_200, res->status);
  13467. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13468. // ignored entirely and the real connection-level address retained.
  13469. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13470. observed_remote_addr == "127.0.0.1");
  13471. }
  13472. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13473. Server svr;
  13474. std::string observed_remote_addr;
  13475. std::string observed_xff;
  13476. svr.Get("/ip", [&](const Request &req, Response &res) {
  13477. observed_remote_addr = req.remote_addr;
  13478. observed_xff = req.get_header_value("X-Forwarded-For");
  13479. res.set_content("ok", "text/plain");
  13480. });
  13481. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13482. auto se = detail::scope_exit([&] {
  13483. svr.stop();
  13484. t.join();
  13485. ASSERT_FALSE(svr.is_running());
  13486. });
  13487. svr.wait_until_ready();
  13488. Client cli(HOST, PORT);
  13489. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13491. EXPECT_EQ(StatusCode::OK_200, res->status);
  13492. EXPECT_EQ(observed_xff, "203.0.113.66");
  13493. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13494. observed_remote_addr == "127.0.0.1");
  13495. }
  13496. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13497. Server svr;
  13498. svr.set_trusted_proxies({"203.0.113.66"});
  13499. std::string observed_remote_addr;
  13500. std::string observed_xff;
  13501. svr.Get("/ip", [&](const Request &req, Response &res) {
  13502. observed_remote_addr = req.remote_addr;
  13503. observed_xff = req.get_header_value("X-Forwarded-For");
  13504. res.set_content("ok", "text/plain");
  13505. });
  13506. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13507. auto se = detail::scope_exit([&] {
  13508. svr.stop();
  13509. t.join();
  13510. ASSERT_FALSE(svr.is_running());
  13511. });
  13512. svr.wait_until_ready();
  13513. Client cli(HOST, PORT);
  13514. auto res = cli.Get("/ip");
  13515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13516. EXPECT_EQ(StatusCode::OK_200, res->status);
  13517. EXPECT_EQ(observed_xff, "");
  13518. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13519. observed_remote_addr == "127.0.0.1");
  13520. }
  13521. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13522. Server svr;
  13523. // Include the loopback address the test client actually connects from, so
  13524. // the direct connection itself is recognized as the trusted proxy hop.
  13525. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13526. std::string observed_remote_addr;
  13527. std::string observed_xff;
  13528. svr.Get("/ip", [&](const Request &req, Response &res) {
  13529. observed_remote_addr = req.remote_addr;
  13530. observed_xff = req.get_header_value("X-Forwarded-For");
  13531. res.set_content("ok", "text/plain");
  13532. });
  13533. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13534. auto se = detail::scope_exit([&] {
  13535. svr.stop();
  13536. t.join();
  13537. ASSERT_FALSE(svr.is_running());
  13538. });
  13539. svr.wait_until_ready();
  13540. Client cli(HOST, PORT);
  13541. auto res = cli.Get(
  13542. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13544. EXPECT_EQ(StatusCode::OK_200, res->status);
  13545. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13546. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13547. }
  13548. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13549. Server svr;
  13550. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13551. std::string observed_remote_addr;
  13552. std::string observed_xff;
  13553. svr.Get("/ip", [&](const Request &req, Response &res) {
  13554. observed_remote_addr = req.remote_addr;
  13555. observed_xff = req.get_header_value("X-Forwarded-For");
  13556. res.set_content("ok", "text/plain");
  13557. });
  13558. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13559. auto se = detail::scope_exit([&] {
  13560. svr.stop();
  13561. t.join();
  13562. ASSERT_FALSE(svr.is_running());
  13563. });
  13564. svr.wait_until_ready();
  13565. Client cli(HOST, PORT);
  13566. auto res = cli.Get(
  13567. "/ip",
  13568. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13570. EXPECT_EQ(StatusCode::OK_200, res->status);
  13571. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13572. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13573. }
  13574. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13575. Server svr;
  13576. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13577. std::string observed_remote_addr;
  13578. std::string observed_xff;
  13579. svr.Get("/ip", [&](const Request &req, Response &res) {
  13580. observed_remote_addr = req.remote_addr;
  13581. observed_xff = req.get_header_value("X-Forwarded-For");
  13582. res.set_content("ok", "text/plain");
  13583. });
  13584. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13585. auto se = detail::scope_exit([&] {
  13586. svr.stop();
  13587. t.join();
  13588. ASSERT_FALSE(svr.is_running());
  13589. });
  13590. svr.wait_until_ready();
  13591. Client cli(HOST, PORT);
  13592. auto res = cli.Get(
  13593. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13595. EXPECT_EQ(StatusCode::OK_200, res->status);
  13596. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13597. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13598. // and must not be selected.
  13599. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13600. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13601. }
  13602. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13603. Server svr;
  13604. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13605. std::string observed_remote_addr;
  13606. svr.Get("/ip", [&](const Request &req, Response &res) {
  13607. observed_remote_addr = req.remote_addr;
  13608. res.set_content("ok", "text/plain");
  13609. });
  13610. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13611. auto se = detail::scope_exit([&] {
  13612. svr.stop();
  13613. t.join();
  13614. ASSERT_FALSE(svr.is_running());
  13615. });
  13616. svr.wait_until_ready();
  13617. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13618. // a forged address and the trusted proxy's own address; the forged value must
  13619. // not win over the address the trusted proxy actually recorded.
  13620. Client cli(HOST, PORT);
  13621. auto res = cli.Get(
  13622. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13624. EXPECT_EQ(StatusCode::OK_200, res->status);
  13625. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13626. }
  13627. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13628. Server svr;
  13629. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13630. std::string observed_remote_addr;
  13631. std::string observed_xff;
  13632. svr.Get("/ip", [&](const Request &req, Response &res) {
  13633. observed_remote_addr = req.remote_addr;
  13634. observed_xff = req.get_header_value("X-Forwarded-For");
  13635. res.set_content("ok", "text/plain");
  13636. });
  13637. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13638. auto se = detail::scope_exit([&] {
  13639. svr.stop();
  13640. t.join();
  13641. ASSERT_FALSE(svr.is_running());
  13642. });
  13643. svr.wait_until_ready();
  13644. Client cli(HOST, PORT);
  13645. auto res = cli.Get(
  13646. "/ip",
  13647. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13649. EXPECT_EQ(StatusCode::OK_200, res->status);
  13650. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13651. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13652. }
  13653. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13654. Server svr;
  13655. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13656. std::string observed_remote_addr;
  13657. std::string observed_xff;
  13658. svr.Get("/ip", [&](const Request &req, Response &res) {
  13659. observed_remote_addr = req.remote_addr;
  13660. observed_xff = req.get_header_value("X-Forwarded-For");
  13661. res.set_content("ok", "text/plain");
  13662. });
  13663. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13664. auto se = detail::scope_exit([&] {
  13665. svr.stop();
  13666. t.join();
  13667. ASSERT_FALSE(svr.is_running());
  13668. });
  13669. svr.wait_until_ready();
  13670. std::string raw_req =
  13671. "GET /ip HTTP/1.1\r\n"
  13672. "Host: localhost\r\n"
  13673. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13674. "Connection: close\r\n"
  13675. "\r\n";
  13676. std::string out;
  13677. ASSERT_TRUE(send_request(5, raw_req, &out));
  13678. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13679. // Header parser trims surrounding whitespace of the header value
  13680. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13681. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13682. }
  13683. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13684. // crash the server (it used to call front() on an empty vector inside
  13685. // get_client_ip). The connection-level remote address must be retained instead.
  13686. static void run_malformed_xff_test(const std::string &xff_value) {
  13687. Server svr;
  13688. svr.set_trusted_proxies({"192.0.2.45"});
  13689. std::string observed_remote_addr;
  13690. svr.Get("/ip", [&](const Request &req, Response &res) {
  13691. observed_remote_addr = req.remote_addr;
  13692. res.set_content("ok", "text/plain");
  13693. });
  13694. int port = 0;
  13695. thread t = thread([&]() {
  13696. port = svr.bind_to_any_port(HOST);
  13697. svr.listen_after_bind();
  13698. });
  13699. auto se = detail::scope_exit([&] {
  13700. svr.stop();
  13701. t.join();
  13702. ASSERT_FALSE(svr.is_running());
  13703. });
  13704. svr.wait_until_ready();
  13705. Client cli(HOST, port);
  13706. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13708. EXPECT_EQ(StatusCode::OK_200, res->status);
  13709. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13710. observed_remote_addr == "127.0.0.1");
  13711. }
  13712. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13713. run_malformed_xff_test("");
  13714. }
  13715. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13716. run_malformed_xff_test(",");
  13717. }
  13718. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13719. run_malformed_xff_test(", , ,");
  13720. }
  13721. #ifndef _WIN32
  13722. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13723. Server svr;
  13724. svr.Post("/post", [&](const Request &req, Response &res) {
  13725. res.set_content(req.body, "text/plain");
  13726. });
  13727. svr.Put("/put", [&](const Request &req, Response &res) {
  13728. res.set_content(req.body, "text/plain");
  13729. });
  13730. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13731. res.set_content(req.body, "text/plain");
  13732. });
  13733. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13734. res.set_content(req.body, "text/plain");
  13735. });
  13736. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13737. auto se = detail::scope_exit([&] {
  13738. svr.stop();
  13739. t.join();
  13740. ASSERT_FALSE(svr.is_running());
  13741. });
  13742. svr.wait_until_ready();
  13743. std::string resp;
  13744. // POST without Content-Length
  13745. ASSERT_TRUE(send_request(5,
  13746. "POST /post HTTP/1.1\r\n"
  13747. "Host: localhost\r\n"
  13748. "Connection: close\r\n"
  13749. "\r\n",
  13750. &resp));
  13751. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13752. // PUT without Content-Length
  13753. resp.clear();
  13754. ASSERT_TRUE(send_request(5,
  13755. "PUT /put HTTP/1.1\r\n"
  13756. "Host: localhost\r\n"
  13757. "Connection: close\r\n"
  13758. "\r\n",
  13759. &resp));
  13760. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13761. // PATCH without Content-Length
  13762. resp.clear();
  13763. ASSERT_TRUE(send_request(5,
  13764. "PATCH /patch HTTP/1.1\r\n"
  13765. "Host: localhost\r\n"
  13766. "Connection: close\r\n"
  13767. "\r\n",
  13768. &resp));
  13769. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13770. // DELETE without Content-Length
  13771. resp.clear();
  13772. ASSERT_TRUE(send_request(5,
  13773. "DELETE /delete HTTP/1.1\r\n"
  13774. "Host: localhost\r\n"
  13775. "Connection: close\r\n"
  13776. "\r\n",
  13777. &resp));
  13778. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13779. }
  13780. #endif
  13781. //==============================================================================
  13782. // open_stream() Tests
  13783. //==============================================================================
  13784. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13785. std::string result;
  13786. char buf[8192];
  13787. ssize_t n;
  13788. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13789. result.append(buf, static_cast<size_t>(n));
  13790. }
  13791. return result;
  13792. }
  13793. // Mock stream for unit tests
  13794. class MockStream : public Stream {
  13795. public:
  13796. std::string data;
  13797. size_t pos = 0;
  13798. ssize_t error_after = -1; // -1 = no error
  13799. explicit MockStream(const std::string &d, ssize_t err = -1)
  13800. : data(d), error_after(err) {}
  13801. bool is_readable() const override { return true; }
  13802. bool wait_readable() const override { return true; }
  13803. bool wait_writable() const override { return true; }
  13804. ssize_t read(char *ptr, size_t size) override {
  13805. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13806. if (pos >= data.size()) return 0;
  13807. size_t limit =
  13808. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13809. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13810. std::memcpy(ptr, data.data() + pos, to_read);
  13811. pos += to_read;
  13812. return static_cast<ssize_t>(to_read);
  13813. }
  13814. ssize_t write(const char *, size_t) override { return -1; }
  13815. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13816. ip = "127.0.0.1";
  13817. port = 0;
  13818. }
  13819. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13820. ip = "127.0.0.1";
  13821. port = 0;
  13822. }
  13823. socket_t socket() const override { return INVALID_SOCKET; }
  13824. time_t duration() const override { return 0; }
  13825. };
  13826. TEST(StreamHandleTest, Basic) {
  13827. ClientImpl::StreamHandle handle;
  13828. EXPECT_FALSE(handle.is_valid());
  13829. handle.response = detail::make_unique<Response>();
  13830. handle.error = Error::Connection;
  13831. EXPECT_FALSE(handle.is_valid());
  13832. handle.error = Error::Success;
  13833. EXPECT_TRUE(handle.is_valid());
  13834. }
  13835. TEST(BodyReaderTest, Basic) {
  13836. MockStream stream("Hello, World!");
  13837. detail::BodyReader reader;
  13838. reader.stream = &stream;
  13839. reader.content_length = 13;
  13840. char buf[32];
  13841. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13842. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13843. EXPECT_TRUE(reader.eof);
  13844. }
  13845. TEST(BodyReaderTest, NoStream) {
  13846. detail::BodyReader reader;
  13847. char buf[32];
  13848. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13849. EXPECT_EQ(Error::Connection, reader.last_error);
  13850. }
  13851. TEST(BodyReaderTest, Error) {
  13852. MockStream stream("Hello, World!", 5);
  13853. detail::BodyReader reader;
  13854. reader.stream = &stream;
  13855. reader.content_length = 13;
  13856. char buf[32];
  13857. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13858. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13859. EXPECT_EQ(Error::Read, reader.last_error);
  13860. }
  13861. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13862. // Mock-based StreamHandle tests relying on private internals are removed.
  13863. class OpenStreamTest : public ::testing::Test {
  13864. protected:
  13865. void SetUp() override {
  13866. svr_.Get("/hello", [](const Request &, Response &res) {
  13867. res.set_content("Hello World!", "text/plain");
  13868. });
  13869. svr_.Get("/large", [](const Request &, Response &res) {
  13870. res.set_content(std::string(10000, 'X'), "text/plain");
  13871. });
  13872. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  13873. res.set_content("Hello World!", "image/jpeg");
  13874. res.set_header("Content-Encoding", "UTF-8");
  13875. });
  13876. svr_.Get("/chunked", [](const Request &, Response &res) {
  13877. res.set_chunked_content_provider("text/plain",
  13878. [](size_t offset, DataSink &sink) {
  13879. if (offset < 15) {
  13880. sink.write("chunk", 5);
  13881. return true;
  13882. }
  13883. sink.done();
  13884. return true;
  13885. });
  13886. });
  13887. svr_.Get("/compressible", [](const Request &, Response &res) {
  13888. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13889. DataSink &sink) {
  13890. if (offset < 100 * 1024) {
  13891. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13892. sink.write(chunk.data(), chunk.size());
  13893. return true;
  13894. }
  13895. sink.done();
  13896. return true;
  13897. });
  13898. });
  13899. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13900. [](const Request & /*req*/, Response &res) {
  13901. auto i = new int(0);
  13902. res.set_header("Trailer", "Content-Length, X-Allowed");
  13903. res.set_chunked_content_provider(
  13904. "text/plain",
  13905. [i](size_t /*offset*/, DataSink &sink) {
  13906. switch (*i) {
  13907. case 0: sink.os << "123"; break;
  13908. case 1: sink.os << "456"; break;
  13909. case 2: sink.os << "789"; break;
  13910. case 3: {
  13911. sink.done_with_trailer(
  13912. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13913. } break;
  13914. }
  13915. (*i)++;
  13916. return true;
  13917. },
  13918. [i](bool success) {
  13919. EXPECT_TRUE(success);
  13920. delete i;
  13921. });
  13922. });
  13923. // Echo headers endpoint for header-related tests
  13924. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13925. std::string body;
  13926. for (const auto &h : req.headers) {
  13927. body.append(h.first);
  13928. body.push_back(':');
  13929. body.append(h.second);
  13930. body.push_back('\n');
  13931. }
  13932. res.set_content(body, "text/plain");
  13933. });
  13934. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13935. std::string body;
  13936. for (const auto &h : req.headers) {
  13937. body.append(h.first);
  13938. body.push_back(':');
  13939. body.append(h.second);
  13940. body.push_back('\n');
  13941. }
  13942. res.set_content(body, "text/plain");
  13943. });
  13944. port_ = svr_.bind_to_any_port("127.0.0.1");
  13945. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13946. svr_.wait_until_ready();
  13947. }
  13948. void TearDown() override {
  13949. svr_.stop();
  13950. if (thread_.joinable()) thread_.join();
  13951. }
  13952. Server svr_;
  13953. std::thread thread_;
  13954. int port_ = 0;
  13955. };
  13956. TEST_F(OpenStreamTest, Basic) {
  13957. Client cli("127.0.0.1", port_);
  13958. auto handle = cli.open_stream("GET", "/hello");
  13959. EXPECT_TRUE(handle.is_valid());
  13960. EXPECT_EQ("Hello World!", read_all(handle));
  13961. }
  13962. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  13963. Client cli("127.0.0.1", port_);
  13964. auto handle = cli.open_stream("GET", "/unknown-encoding");
  13965. ASSERT_TRUE(handle.is_valid());
  13966. EXPECT_EQ("Hello World!", read_all(handle));
  13967. }
  13968. TEST_F(OpenStreamTest, SmallBuffer) {
  13969. Client cli("127.0.0.1", port_);
  13970. auto handle = cli.open_stream("GET", "/hello");
  13971. std::string result;
  13972. char buf[4];
  13973. ssize_t n;
  13974. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13975. result.append(buf, static_cast<size_t>(n));
  13976. EXPECT_EQ("Hello World!", result);
  13977. }
  13978. TEST_F(OpenStreamTest, DefaultHeaders) {
  13979. Client cli("127.0.0.1", port_);
  13980. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13981. {
  13982. auto handle = cli.open_stream("GET", "/echo-headers");
  13983. ASSERT_TRUE(handle.is_valid());
  13984. auto body = read_all(handle);
  13985. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13986. std::string::npos);
  13987. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13988. std::string::npos);
  13989. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13990. }
  13991. // open_stream POST with body and no explicit content_type should NOT add
  13992. // text/plain Content-Type (behavior differs from non-streaming path), but
  13993. // should include Content-Length
  13994. {
  13995. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13996. ASSERT_TRUE(handle.is_valid());
  13997. auto body = read_all(handle);
  13998. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13999. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  14000. }
  14001. // open_stream POST with explicit Content-Type should preserve it
  14002. {
  14003. auto handle = cli.open_stream("POST", "/echo-headers", {},
  14004. {{"Content-Type", "application/custom"}},
  14005. "{}", "application/custom");
  14006. ASSERT_TRUE(handle.is_valid());
  14007. auto body = read_all(handle);
  14008. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  14009. }
  14010. // User-specified User-Agent must not be overwritten for stream API
  14011. {
  14012. auto handle = cli.open_stream("GET", "/echo-headers", {},
  14013. {{"User-Agent", "MyAgent/1.2"}});
  14014. ASSERT_TRUE(handle.is_valid());
  14015. auto body = read_all(handle);
  14016. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  14017. }
  14018. }
  14019. TEST_F(OpenStreamTest, Large) {
  14020. Client cli("127.0.0.1", port_);
  14021. auto handle = cli.open_stream("GET", "/large");
  14022. EXPECT_EQ(10000u, read_all(handle).size());
  14023. }
  14024. TEST_F(OpenStreamTest, ConnectionError) {
  14025. Client cli("127.0.0.1", 9999);
  14026. auto handle = cli.open_stream("GET", "/hello");
  14027. EXPECT_FALSE(handle.is_valid());
  14028. }
  14029. TEST_F(OpenStreamTest, Chunked) {
  14030. Client cli("127.0.0.1", port_);
  14031. auto handle = cli.open_stream("GET", "/chunked");
  14032. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14033. "Transfer-Encoding") == "chunked");
  14034. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  14035. }
  14036. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  14037. Client cli("127.0.0.1", port_);
  14038. auto handle =
  14039. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  14040. ASSERT_TRUE(handle.is_valid());
  14041. // Consume body to allow trailers to be received/parsed
  14042. auto body = read_all(handle);
  14043. // Explicitly parse trailers (ensure trailers are available for assertion)
  14044. handle.parse_trailers_if_needed();
  14045. EXPECT_EQ(std::string("123456789"), body);
  14046. // The response should include a Trailer header declaring both names
  14047. ASSERT_TRUE(handle.response);
  14048. EXPECT_TRUE(handle.response->has_header("Trailer"));
  14049. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  14050. handle.response->get_header_value("Trailer"));
  14051. // Prohibited trailer must not be present
  14052. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  14053. // Allowed trailer should be present
  14054. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  14055. EXPECT_EQ(std::string("yes"),
  14056. handle.response->get_trailer_value("X-Allowed"));
  14057. // Verify trailers are NOT present as regular headers
  14058. EXPECT_EQ(std::string(""),
  14059. handle.response->get_header_value("Content-Length"));
  14060. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  14061. }
  14062. static std::thread serve_single_response(std::promise<int> &port_promise,
  14063. const std::string &response) {
  14064. return std::thread([&port_promise, response] {
  14065. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14066. default_socket_options(srv);
  14067. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14068. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14069. sockaddr_in addr{};
  14070. addr.sin_family = AF_INET;
  14071. addr.sin_port = htons(0); // Let OS assign a free port
  14072. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14073. int opt = 1;
  14074. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14075. #ifdef _WIN32
  14076. reinterpret_cast<const char *>(&opt),
  14077. #else
  14078. &opt,
  14079. #endif
  14080. sizeof(opt));
  14081. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  14082. ::listen(srv, 1) != 0) {
  14083. port_promise.set_value(-1);
  14084. detail::close_socket(srv);
  14085. return;
  14086. }
  14087. socklen_t addr_len = sizeof(addr);
  14088. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  14089. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  14090. sockaddr_in cli_addr{};
  14091. socklen_t cli_len = sizeof(cli_addr);
  14092. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14093. if (cli != INVALID_SOCKET) {
  14094. // Read the complete HTTP request (until the blank line that terminates
  14095. // headers) before sending the response. If the server closes the socket
  14096. // while the client's request data is still unread in the kernel receive
  14097. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  14098. // connection on both sides: it discards the client's receive buffer
  14099. // (which already holds our response) and causes any in-progress write on
  14100. // the client to fail with ECONNRESET. Reading all request data first
  14101. // ensures close() emits a graceful FIN.
  14102. {
  14103. char rbuf[256];
  14104. std::string req;
  14105. while (req.find("\r\n\r\n") == std::string::npos) {
  14106. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  14107. if (n <= 0) { break; }
  14108. req.append(rbuf, static_cast<size_t>(n));
  14109. }
  14110. }
  14111. ::send(cli,
  14112. #ifdef _WIN32
  14113. static_cast<const char *>(response.c_str()),
  14114. static_cast<int>(response.size()),
  14115. #else
  14116. response.c_str(), response.size(),
  14117. #endif
  14118. 0);
  14119. detail::close_socket(cli);
  14120. }
  14121. detail::close_socket(srv);
  14122. });
  14123. }
  14124. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  14125. #ifndef _WIN32
  14126. signal(SIGPIPE, SIG_IGN);
  14127. #endif
  14128. std::promise<int> port_promise;
  14129. auto port_future = port_promise.get_future();
  14130. auto server_thread =
  14131. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  14132. "Content-Type: text/plain\r\n"
  14133. "Content-Length: not-a-number\r\n"
  14134. "Connection: close\r\n"
  14135. "\r\n"
  14136. "hello");
  14137. auto port = port_future.get();
  14138. ASSERT_GT(port, 0);
  14139. Client cli("127.0.0.1", port);
  14140. auto handle = cli.open_stream("GET", "/");
  14141. EXPECT_FALSE(handle.is_valid());
  14142. server_thread.join();
  14143. }
  14144. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  14145. #ifndef _WIN32
  14146. signal(SIGPIPE, SIG_IGN);
  14147. #endif
  14148. std::promise<int> port_promise;
  14149. auto port_future = port_promise.get_future();
  14150. auto server_thread = serve_single_response(
  14151. port_promise, "HTTP/1.1 200 OK\r\n"
  14152. "Content-Type: text/plain\r\n"
  14153. "Content-Length: 99999999999999999999999999\r\n"
  14154. "Connection: close\r\n"
  14155. "\r\n"
  14156. "hello");
  14157. auto port = port_future.get();
  14158. ASSERT_GT(port, 0);
  14159. // Historically std::stoull would throw std::out_of_range here and crash
  14160. // the process, then parsing silently clamped to a bogus framing length and
  14161. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  14162. // so the stream fails to open, matching the not-a-number case above. The
  14163. // process still must NOT terminate.
  14164. Client cli("127.0.0.1", port);
  14165. auto handle = cli.open_stream("GET", "/");
  14166. EXPECT_FALSE(handle.is_valid());
  14167. server_thread.join();
  14168. }
  14169. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14170. TEST_F(OpenStreamTest, Gzip) {
  14171. Client cli("127.0.0.1", port_);
  14172. auto handle = cli.open_stream("GET", "/compressible", {},
  14173. {{"Accept-Encoding", "gzip"}});
  14174. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  14175. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14176. }
  14177. #endif
  14178. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14179. TEST_F(OpenStreamTest, Brotli) {
  14180. Client cli("127.0.0.1", port_);
  14181. auto handle =
  14182. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  14183. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  14184. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14185. }
  14186. #endif
  14187. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14188. TEST_F(OpenStreamTest, Zstd) {
  14189. Client cli("127.0.0.1", port_);
  14190. auto handle = cli.open_stream("GET", "/compressible", {},
  14191. {{"Accept-Encoding", "zstd"}});
  14192. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  14193. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14194. }
  14195. #endif
  14196. #ifdef CPPHTTPLIB_SSL_ENABLED
  14197. class SSLOpenStreamTest : public ::testing::Test {
  14198. protected:
  14199. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  14200. void SetUp() override {
  14201. svr_.Get("/hello", [](const Request &, Response &res) {
  14202. res.set_content("Hello SSL World!", "text/plain");
  14203. });
  14204. svr_.Get("/chunked", [](const Request &, Response &res) {
  14205. res.set_chunked_content_provider("text/plain",
  14206. [](size_t offset, DataSink &sink) {
  14207. if (offset < 15) {
  14208. sink.write("chunk", 5);
  14209. return true;
  14210. }
  14211. sink.done();
  14212. return true;
  14213. });
  14214. });
  14215. svr_.Post("/echo", [](const Request &req, Response &res) {
  14216. res.set_content(req.body, req.get_header_value("Content-Type"));
  14217. });
  14218. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  14219. std::string body = req.body;
  14220. res.set_chunked_content_provider(
  14221. "text/plain", [body](size_t offset, DataSink &sink) {
  14222. if (offset < body.size()) {
  14223. sink.write(body.data() + offset, body.size() - offset);
  14224. }
  14225. sink.done();
  14226. return true;
  14227. });
  14228. });
  14229. port_ = svr_.bind_to_any_port("127.0.0.1");
  14230. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14231. svr_.wait_until_ready();
  14232. }
  14233. void TearDown() override {
  14234. svr_.stop();
  14235. if (thread_.joinable()) thread_.join();
  14236. }
  14237. SSLServer svr_;
  14238. std::thread thread_;
  14239. int port_ = 0;
  14240. };
  14241. TEST_F(SSLOpenStreamTest, Basic) {
  14242. SSLClient cli("127.0.0.1", port_);
  14243. cli.enable_server_certificate_verification(false);
  14244. auto handle = cli.open_stream("GET", "/hello");
  14245. ASSERT_TRUE(handle.is_valid());
  14246. EXPECT_EQ("Hello SSL World!", read_all(handle));
  14247. }
  14248. TEST_F(SSLOpenStreamTest, Chunked) {
  14249. SSLClient cli("127.0.0.1", port_);
  14250. cli.enable_server_certificate_verification(false);
  14251. auto handle = cli.open_stream("GET", "/chunked");
  14252. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14253. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14254. "Transfer-Encoding") == "chunked");
  14255. auto body = read_all(handle);
  14256. EXPECT_EQ("chunkchunkchunk", body);
  14257. }
  14258. TEST_F(SSLOpenStreamTest, Post) {
  14259. SSLClient cli("127.0.0.1", port_);
  14260. cli.enable_server_certificate_verification(false);
  14261. auto handle =
  14262. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  14263. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14264. EXPECT_EQ(200, handle.response->status);
  14265. auto body = read_all(handle);
  14266. EXPECT_EQ("Hello SSL POST", body);
  14267. }
  14268. TEST_F(SSLOpenStreamTest, PostChunked) {
  14269. SSLClient cli("127.0.0.1", port_);
  14270. cli.enable_server_certificate_verification(false);
  14271. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  14272. "Chunked SSL Data", "text/plain");
  14273. ASSERT_TRUE(handle.is_valid());
  14274. EXPECT_EQ(200, handle.response->status);
  14275. auto body = read_all(handle);
  14276. EXPECT_EQ("Chunked SSL Data", body);
  14277. }
  14278. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  14279. // Content-Length is terminated by the server closing the connection. When the
  14280. // SSL peer sends a close_notify after the body, the client must treat it as a
  14281. // clean EOF and return a successful response rather than an error.
  14282. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  14283. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14284. ASSERT_TRUE(svr.is_valid());
  14285. svr.set_keep_alive_max_count(1);
  14286. const std::string expected_body = "Hello from connection-close response!";
  14287. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  14288. res.set_content_provider("text/plain",
  14289. [&](size_t offset, DataSink &sink) -> bool {
  14290. if (offset < expected_body.size()) {
  14291. sink.write(expected_body.data() + offset,
  14292. expected_body.size() - offset);
  14293. }
  14294. sink.done();
  14295. return true;
  14296. });
  14297. });
  14298. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  14299. auto se = detail::scope_exit([&] {
  14300. svr.stop();
  14301. listen_thread.join();
  14302. ASSERT_FALSE(svr.is_running());
  14303. });
  14304. svr.wait_until_ready();
  14305. SSLClient cli(HOST, PORT);
  14306. cli.enable_server_certificate_verification(false);
  14307. auto res = cli.Get("/no-content-length");
  14308. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  14309. EXPECT_EQ(StatusCode::OK_200, res->status);
  14310. EXPECT_EQ(expected_body, res->body);
  14311. }
  14312. #endif // CPPHTTPLIB_SSL_ENABLED
  14313. //==============================================================================
  14314. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  14315. // results for various scenarios.
  14316. //==============================================================================
  14317. TEST(ParityTest, GetVsOpenStream) {
  14318. Server svr;
  14319. const std::string path = "/parity";
  14320. const std::string content = "Parity test content: hello world";
  14321. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14322. res.set_content(content, "text/plain");
  14323. });
  14324. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14325. auto se = detail::scope_exit([&] {
  14326. svr.stop();
  14327. t.join();
  14328. ASSERT_FALSE(svr.is_running());
  14329. });
  14330. svr.wait_until_ready();
  14331. Client cli(HOST, PORT);
  14332. // Non-stream path
  14333. auto r1 = cli.Get(path);
  14334. ASSERT_TRUE(r1);
  14335. EXPECT_EQ(StatusCode::OK_200, r1->status);
  14336. // Stream path
  14337. auto h = cli.open_stream("GET", path);
  14338. ASSERT_TRUE(h.is_valid());
  14339. EXPECT_EQ(r1->body, read_all(h));
  14340. }
  14341. // Helper to compress data with provided compressor type T
  14342. template <typename Compressor>
  14343. static std::string compress_payload_for_parity(const std::string &in) {
  14344. std::string out;
  14345. Compressor compressor;
  14346. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  14347. [&](const char *data, size_t n) {
  14348. out.append(data, n);
  14349. return true;
  14350. });
  14351. EXPECT_TRUE(ok);
  14352. return out;
  14353. }
  14354. // Helper function for compression parity tests
  14355. template <typename Compressor>
  14356. static void test_compression_parity(const std::string &original,
  14357. const std::string &path,
  14358. const std::string &encoding) {
  14359. const std::string compressed =
  14360. compress_payload_for_parity<Compressor>(original);
  14361. Server svr;
  14362. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14363. res.set_content(compressed, "application/octet-stream");
  14364. res.set_header("Content-Encoding", encoding);
  14365. });
  14366. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  14367. auto se = detail::scope_exit([&] {
  14368. svr.stop();
  14369. t.join();
  14370. ASSERT_FALSE(svr.is_running());
  14371. });
  14372. svr.wait_until_ready();
  14373. Client cli(HOST, PORT);
  14374. // Non-streaming
  14375. {
  14376. auto res = cli.Get(path);
  14377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14378. EXPECT_EQ(StatusCode::OK_200, res->status);
  14379. EXPECT_EQ(original, res->body);
  14380. }
  14381. // Streaming
  14382. {
  14383. auto h = cli.open_stream("GET", path);
  14384. ASSERT_TRUE(h.is_valid());
  14385. EXPECT_EQ(original, read_all(h));
  14386. }
  14387. }
  14388. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14389. TEST(ParityTest, Gzip) {
  14390. test_compression_parity<detail::gzip_compressor>(
  14391. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  14392. }
  14393. #endif
  14394. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14395. TEST(ParityTest, Brotli) {
  14396. test_compression_parity<detail::brotli_compressor>(
  14397. "Hello, brotli parity test payload", "/parity-br", "br");
  14398. }
  14399. #endif
  14400. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14401. TEST(ParityTest, Zstd) {
  14402. test_compression_parity<detail::zstd_compressor>(
  14403. "Zstandard parity test payload", "/parity-zstd", "zstd");
  14404. }
  14405. #endif
  14406. //==============================================================================
  14407. // New Stream API Tests
  14408. //==============================================================================
  14409. inline std::string read_body(httplib::stream::Result &result) {
  14410. std::string body;
  14411. while (result.next()) {
  14412. body.append(result.data(), result.size());
  14413. }
  14414. return body;
  14415. }
  14416. TEST(ClientConnectionTest, Basic) {
  14417. httplib::ClientConnection conn;
  14418. EXPECT_FALSE(conn.is_open());
  14419. conn.sock = 1;
  14420. EXPECT_TRUE(conn.is_open());
  14421. httplib::ClientConnection conn2(std::move(conn));
  14422. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14423. conn2.sock = INVALID_SOCKET;
  14424. }
  14425. // Unified test server for all stream::* tests
  14426. class StreamApiTest : public ::testing::Test {
  14427. protected:
  14428. void SetUp() override {
  14429. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14430. res.set_content("Hello World!", "text/plain");
  14431. });
  14432. svr_.Get("/echo-params",
  14433. [](const httplib::Request &req, httplib::Response &res) {
  14434. std::string r;
  14435. for (const auto &p : req.params) {
  14436. if (!r.empty()) r += "&";
  14437. r += p.first + "=" + p.second;
  14438. }
  14439. res.set_content(r, "text/plain");
  14440. });
  14441. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14442. res.set_content(req.body, req.get_header_value("Content-Type"));
  14443. });
  14444. svr_.Post("/echo-headers",
  14445. [](const httplib::Request &req, httplib::Response &res) {
  14446. std::string r;
  14447. for (const auto &h : req.headers)
  14448. r += h.first + ": " + h.second + "\n";
  14449. res.set_content(r, "text/plain");
  14450. });
  14451. svr_.Post("/echo-params",
  14452. [](const httplib::Request &req, httplib::Response &res) {
  14453. std::string r = "params:";
  14454. for (const auto &p : req.params)
  14455. r += p.first + "=" + p.second + ";";
  14456. res.set_content(r + " body:" + req.body, "text/plain");
  14457. });
  14458. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14459. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14460. });
  14461. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14462. res.set_content("PUT:" + req.body, "text/plain");
  14463. });
  14464. svr_.Patch("/echo",
  14465. [](const httplib::Request &req, httplib::Response &res) {
  14466. res.set_content("PATCH:" + req.body, "text/plain");
  14467. });
  14468. svr_.Delete(
  14469. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14470. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14471. "text/plain");
  14472. });
  14473. svr_.Get("/head-test",
  14474. [](const httplib::Request &, httplib::Response &res) {
  14475. res.set_content("body for HEAD", "text/plain");
  14476. });
  14477. svr_.Options("/options",
  14478. [](const httplib::Request &, httplib::Response &res) {
  14479. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14480. });
  14481. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14482. svr_.wait_until_ready();
  14483. }
  14484. void TearDown() override {
  14485. svr_.stop();
  14486. if (thread_.joinable()) thread_.join();
  14487. }
  14488. httplib::Server svr_;
  14489. std::thread thread_;
  14490. };
  14491. // stream::Get tests
  14492. TEST_F(StreamApiTest, GetBasic) {
  14493. httplib::Client cli(HOST, PORT);
  14494. auto result = httplib::stream::Get(cli, "/hello");
  14495. ASSERT_TRUE(result.is_valid());
  14496. EXPECT_EQ(200, result.status());
  14497. EXPECT_EQ("Hello World!", read_body(result));
  14498. }
  14499. TEST_F(StreamApiTest, GetWithParams) {
  14500. httplib::Client cli(HOST, PORT);
  14501. httplib::Params params{{"foo", "bar"}};
  14502. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14503. ASSERT_TRUE(result.is_valid());
  14504. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14505. }
  14506. TEST_F(StreamApiTest, GetConnectionError) {
  14507. httplib::Client cli(HOST, 9999);
  14508. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14509. }
  14510. TEST_F(StreamApiTest, Get404) {
  14511. httplib::Client cli(HOST, PORT);
  14512. auto result = httplib::stream::Get(cli, "/nonexistent");
  14513. EXPECT_TRUE(result.is_valid());
  14514. EXPECT_EQ(404, result.status());
  14515. }
  14516. // stream::Post tests
  14517. TEST_F(StreamApiTest, PostBasic) {
  14518. httplib::Client cli(HOST, PORT);
  14519. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14520. "application/json");
  14521. ASSERT_TRUE(result.is_valid());
  14522. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14523. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14524. }
  14525. TEST_F(StreamApiTest, PostWithHeaders) {
  14526. httplib::Client cli(HOST, PORT);
  14527. httplib::Headers headers{{"X-Custom", "value"}};
  14528. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14529. "text/plain");
  14530. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14531. }
  14532. TEST_F(StreamApiTest, PostWithParams) {
  14533. httplib::Client cli(HOST, PORT);
  14534. httplib::Params params{{"k", "v"}};
  14535. auto result =
  14536. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14537. auto body = read_body(result);
  14538. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14539. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14540. }
  14541. TEST_F(StreamApiTest, PostLarge) {
  14542. httplib::Client cli(HOST, PORT);
  14543. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14544. size_t total = 0;
  14545. while (result.next()) {
  14546. total += result.size();
  14547. }
  14548. EXPECT_EQ(100u * 1024u, total);
  14549. }
  14550. // stream::Put/Patch tests
  14551. TEST_F(StreamApiTest, PutAndPatch) {
  14552. httplib::Client cli(HOST, PORT);
  14553. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14554. EXPECT_EQ("PUT:test", read_body(put));
  14555. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14556. EXPECT_EQ("PATCH:test", read_body(patch));
  14557. }
  14558. // stream::Delete tests
  14559. TEST_F(StreamApiTest, Delete) {
  14560. httplib::Client cli(HOST, PORT);
  14561. auto del1 = httplib::stream::Delete(cli, "/resource");
  14562. EXPECT_EQ("Deleted", read_body(del1));
  14563. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14564. EXPECT_EQ("Deleted:data", read_body(del2));
  14565. }
  14566. // stream::Head/Options tests
  14567. TEST_F(StreamApiTest, HeadAndOptions) {
  14568. httplib::Client cli(HOST, PORT);
  14569. auto head = httplib::stream::Head(cli, "/head-test");
  14570. EXPECT_TRUE(head.is_valid());
  14571. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14572. auto opts = httplib::stream::Options(cli, "/options");
  14573. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14574. }
  14575. // SSL stream::* tests
  14576. #ifdef CPPHTTPLIB_SSL_ENABLED
  14577. class SSLStreamApiTest : public ::testing::Test {
  14578. protected:
  14579. void SetUp() override {
  14580. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14581. res.set_content("Hello SSL!", "text/plain");
  14582. });
  14583. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14584. res.set_content(req.body, "text/plain");
  14585. });
  14586. port_ = svr_.bind_to_any_port("127.0.0.1");
  14587. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14588. svr_.wait_until_ready();
  14589. }
  14590. void TearDown() override {
  14591. svr_.stop();
  14592. if (thread_.joinable()) thread_.join();
  14593. }
  14594. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14595. std::thread thread_;
  14596. int port_ = 0;
  14597. };
  14598. TEST_F(SSLStreamApiTest, GetAndPost) {
  14599. httplib::SSLClient cli("127.0.0.1", port_);
  14600. cli.enable_server_certificate_verification(false);
  14601. auto get = httplib::stream::Get(cli, "/hello");
  14602. EXPECT_EQ("Hello SSL!", read_body(get));
  14603. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14604. EXPECT_EQ("test", read_body(post));
  14605. }
  14606. #endif
  14607. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14608. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14609. // BodyReader
  14610. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14611. // Test that read timeout during streaming is detected
  14612. // Use a large content-length response where server delays mid-stream
  14613. Server svr;
  14614. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14615. // Send a large response with delay in the middle
  14616. res.set_content_provider(
  14617. 1000, // content_length
  14618. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14619. if (offset < 100) {
  14620. // Send first 100 bytes immediately
  14621. std::string data(100, 'A');
  14622. sink.write(data.c_str(), data.size());
  14623. return true;
  14624. }
  14625. // Then delay longer than client timeout
  14626. std::this_thread::sleep_for(std::chrono::seconds(3));
  14627. std::string data(900, 'B');
  14628. sink.write(data.c_str(), data.size());
  14629. return true;
  14630. });
  14631. });
  14632. auto port = 8091;
  14633. std::thread t([&]() { svr.listen("localhost", port); });
  14634. svr.wait_until_ready();
  14635. Client cli("localhost", port);
  14636. cli.set_read_timeout(1, 0); // 1 second timeout
  14637. auto handle = cli.open_stream("GET", "/slow-stream");
  14638. ASSERT_TRUE(handle.is_valid());
  14639. char buf[256];
  14640. ssize_t total = 0;
  14641. ssize_t n;
  14642. bool got_error = false;
  14643. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14644. total += n;
  14645. }
  14646. if (n < 0) {
  14647. got_error = true;
  14648. // Should be timeout or read error
  14649. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14650. handle.get_read_error() == Error::Read)
  14651. << "Actual error: " << to_string(handle.get_read_error());
  14652. }
  14653. // Either we got an error, or we got less data than expected
  14654. EXPECT_TRUE(got_error || total < 1000)
  14655. << "Expected timeout but got all " << total << " bytes";
  14656. svr.stop();
  14657. t.join();
  14658. }
  14659. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14660. // Test connection closed detection via BodyReader
  14661. Server svr;
  14662. std::atomic<bool> close_now{false};
  14663. svr.Get("/will-close", [&](const Request &, Response &res) {
  14664. res.set_content_provider(
  14665. 10000, // Large content_length that we won't fully send
  14666. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14667. if (offset < 100) {
  14668. std::string data(100, 'X');
  14669. sink.write(data.c_str(), data.size());
  14670. return true;
  14671. }
  14672. // Wait for signal then abort
  14673. while (!close_now) {
  14674. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14675. }
  14676. return false; // Abort - server will close connection
  14677. });
  14678. });
  14679. auto port = 8092;
  14680. std::thread t([&]() { svr.listen("localhost", port); });
  14681. svr.wait_until_ready();
  14682. Client cli("localhost", port);
  14683. auto handle = cli.open_stream("GET", "/will-close");
  14684. ASSERT_TRUE(handle.is_valid());
  14685. char buf[256];
  14686. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14687. EXPECT_GT(n, 0) << "First read should succeed";
  14688. // Signal server to close
  14689. close_now = true;
  14690. // Keep reading until error or EOF
  14691. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14692. // Keep reading
  14693. }
  14694. // Should get an error since content_length wasn't satisfied
  14695. if (n < 0) {
  14696. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14697. handle.get_read_error() == Error::Read)
  14698. << "Actual error: " << to_string(handle.get_read_error());
  14699. }
  14700. svr.stop();
  14701. t.join();
  14702. }
  14703. #ifdef CPPHTTPLIB_SSL_ENABLED
  14704. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14705. // Test that read timeout during SSL streaming is detected
  14706. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14707. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14708. res.set_content_provider(
  14709. 1000, "text/plain",
  14710. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14711. if (offset < 100) {
  14712. std::string data(100, 'A');
  14713. sink.write(data.c_str(), data.size());
  14714. return true;
  14715. }
  14716. std::this_thread::sleep_for(std::chrono::seconds(3));
  14717. std::string data(900, 'B');
  14718. sink.write(data.c_str(), data.size());
  14719. return true;
  14720. });
  14721. });
  14722. auto port = 8093;
  14723. std::thread t([&]() { svr.listen("localhost", port); });
  14724. svr.wait_until_ready();
  14725. SSLClient cli("localhost", port);
  14726. cli.enable_server_certificate_verification(false);
  14727. cli.set_read_timeout(1, 0); // 1 second timeout
  14728. auto handle = cli.open_stream("GET", "/slow-stream");
  14729. ASSERT_TRUE(handle.is_valid());
  14730. char buf[256];
  14731. ssize_t total = 0;
  14732. ssize_t n;
  14733. bool got_error = false;
  14734. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14735. total += n;
  14736. }
  14737. if (n < 0) {
  14738. got_error = true;
  14739. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14740. handle.get_read_error() == Error::Read)
  14741. << "Actual error: " << to_string(handle.get_read_error());
  14742. }
  14743. EXPECT_TRUE(got_error || total < 1000)
  14744. << "Expected timeout but got all " << total << " bytes";
  14745. svr.stop();
  14746. t.join();
  14747. }
  14748. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14749. // Test SSL connection closed detection
  14750. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14751. std::atomic<bool> close_now{false};
  14752. svr.Get("/will-close", [&](const Request &, Response &res) {
  14753. res.set_content_provider(
  14754. 10000, "text/plain",
  14755. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14756. if (offset < 100) {
  14757. std::string data(100, 'X');
  14758. sink.write(data.c_str(), data.size());
  14759. return true;
  14760. }
  14761. while (!close_now) {
  14762. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14763. }
  14764. return false;
  14765. });
  14766. });
  14767. auto port = 8094;
  14768. std::thread t([&]() { svr.listen("localhost", port); });
  14769. svr.wait_until_ready();
  14770. SSLClient cli("localhost", port);
  14771. cli.enable_server_certificate_verification(false);
  14772. auto handle = cli.open_stream("GET", "/will-close");
  14773. ASSERT_TRUE(handle.is_valid());
  14774. char buf[256];
  14775. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14776. EXPECT_GT(n, 0);
  14777. // Signal server to close
  14778. close_now = true;
  14779. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14780. // Keep reading
  14781. }
  14782. if (n < 0) {
  14783. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14784. handle.get_read_error() == Error::Read)
  14785. << "Actual error: " << to_string(handle.get_read_error());
  14786. }
  14787. svr.stop();
  14788. t.join();
  14789. }
  14790. #endif
  14791. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14792. using namespace httplib;
  14793. // Create a test file
  14794. const char *fname = "etag_testfile.txt";
  14795. const char *content = "etag-content";
  14796. {
  14797. std::ofstream ofs(fname);
  14798. ofs << content;
  14799. ASSERT_TRUE(ofs.good());
  14800. }
  14801. Server svr;
  14802. svr.set_mount_point("/static", ".");
  14803. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14804. svr.wait_until_ready();
  14805. Client cli(HOST, PORT);
  14806. // First request: should get 200 with ETag header
  14807. auto res1 = cli.Get("/static/etag_testfile.txt");
  14808. ASSERT_TRUE(res1);
  14809. ASSERT_EQ(200, res1->status);
  14810. ASSERT_TRUE(res1->has_header("ETag"));
  14811. std::string etag = res1->get_header_value("ETag");
  14812. EXPECT_FALSE(etag.empty());
  14813. // Verify ETag format: W/"hex-hex"
  14814. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14815. EXPECT_EQ('W', etag[0]);
  14816. EXPECT_EQ('/', etag[1]);
  14817. EXPECT_EQ('"', etag[2]);
  14818. EXPECT_EQ('"', etag.back());
  14819. // Exact match: expect 304 Not Modified
  14820. Headers h2 = {{"If-None-Match", etag}};
  14821. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14822. ASSERT_TRUE(res2);
  14823. EXPECT_EQ(304, res2->status);
  14824. // Wildcard match: expect 304 Not Modified
  14825. Headers h3 = {{"If-None-Match", "*"}};
  14826. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14827. ASSERT_TRUE(res3);
  14828. EXPECT_EQ(304, res3->status);
  14829. // Non-matching ETag: expect 200
  14830. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14831. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14832. ASSERT_TRUE(res4);
  14833. EXPECT_EQ(200, res4->status);
  14834. // Multiple ETags with one matching: expect 304
  14835. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14836. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14837. ASSERT_TRUE(res5);
  14838. EXPECT_EQ(304, res5->status);
  14839. svr.stop();
  14840. t.join();
  14841. std::remove(fname);
  14842. }
  14843. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14844. using namespace httplib;
  14845. Server svr;
  14846. svr.set_mount_point("/static", ".");
  14847. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14848. svr.wait_until_ready();
  14849. Client cli(HOST, PORT);
  14850. // Send If-None-Match: * to a non-existent file
  14851. Headers h = {{"If-None-Match", "*"}};
  14852. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14854. EXPECT_EQ(404, res->status);
  14855. svr.stop();
  14856. t.join();
  14857. }
  14858. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14859. using namespace httplib;
  14860. // Create a test file
  14861. const char *fname = "etag_boundary_testfile.txt";
  14862. const char *content = "boundary-test";
  14863. {
  14864. std::ofstream ofs(fname);
  14865. ofs << content;
  14866. ASSERT_TRUE(ofs.good());
  14867. }
  14868. Server svr;
  14869. svr.set_mount_point("/static", ".");
  14870. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14871. svr.wait_until_ready();
  14872. Client cli(HOST, PORT);
  14873. // Get the actual ETag
  14874. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14875. ASSERT_TRUE(res1);
  14876. ASSERT_EQ(200, res1->status);
  14877. ASSERT_TRUE(res1->has_header("ETag"));
  14878. std::string etag = res1->get_header_value("ETag");
  14879. // Test 1: Very long ETag value (longer than actual ETag)
  14880. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14881. Headers h1 = {{"If-None-Match", "W/"
  14882. "\"very-long-etag-value-that-is-much-longer-"
  14883. "than-the-actual-etag-value\""}};
  14884. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14885. ASSERT_TRUE(res2);
  14886. EXPECT_EQ(200, res2->status); // Should not match
  14887. // Test 2: Long string followed by wildcard
  14888. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14889. // string)
  14890. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14891. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14892. ASSERT_TRUE(res3);
  14893. EXPECT_EQ(304, res3->status); // Should match on "*"
  14894. // Test 3: Wildcard followed by long string
  14895. // Should match on "*" immediately and return 304
  14896. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14897. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14898. ASSERT_TRUE(res4);
  14899. EXPECT_EQ(304, res4->status); // Should match on "*"
  14900. // Test 4: Multiple long non-matching values
  14901. // Should NOT match and return 200 (test that all comparisons are safe)
  14902. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14903. "W/\"second-long-non-matching-value\", "
  14904. "W/\"third-long-non-matching-value\""}};
  14905. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14906. ASSERT_TRUE(res5);
  14907. EXPECT_EQ(200, res5->status); // Should not match
  14908. // Test 5: Single character that is not "*" (edge case)
  14909. Headers h5 = {{"If-None-Match", "X"}};
  14910. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14911. ASSERT_TRUE(res6);
  14912. EXPECT_EQ(200, res6->status); // Should not match
  14913. svr.stop();
  14914. t.join();
  14915. std::remove(fname);
  14916. }
  14917. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14918. using namespace httplib;
  14919. // Create a test file
  14920. const char *fname = "ims_testfile.txt";
  14921. const char *content = "if-modified-since-test";
  14922. {
  14923. std::ofstream ofs(fname);
  14924. ofs << content;
  14925. ASSERT_TRUE(ofs.good());
  14926. }
  14927. Server svr;
  14928. svr.set_mount_point("/static", ".");
  14929. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14930. svr.wait_until_ready();
  14931. Client cli(HOST, PORT);
  14932. // First request: should get 200 with Last-Modified header
  14933. auto res1 = cli.Get("/static/ims_testfile.txt");
  14934. ASSERT_TRUE(res1);
  14935. ASSERT_EQ(200, res1->status);
  14936. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14937. std::string last_modified = res1->get_header_value("Last-Modified");
  14938. EXPECT_FALSE(last_modified.empty());
  14939. // If-Modified-Since with same time: expect 304
  14940. Headers h2 = {{"If-Modified-Since", last_modified}};
  14941. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14942. ASSERT_TRUE(res2);
  14943. EXPECT_EQ(304, res2->status);
  14944. // If-Modified-Since with future time: expect 304
  14945. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14946. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14947. ASSERT_TRUE(res3);
  14948. EXPECT_EQ(304, res3->status);
  14949. // If-Modified-Since with past time: expect 200
  14950. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14951. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14952. ASSERT_TRUE(res4);
  14953. EXPECT_EQ(200, res4->status);
  14954. // If-None-Match takes precedence over If-Modified-Since
  14955. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14956. ASSERT_TRUE(res1->has_header("ETag"));
  14957. std::string etag = res1->get_header_value("ETag");
  14958. Headers h5 = {{"If-None-Match", etag},
  14959. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14960. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14961. ASSERT_TRUE(res5);
  14962. EXPECT_EQ(304, res5->status);
  14963. svr.stop();
  14964. t.join();
  14965. std::remove(fname);
  14966. }
  14967. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14968. using namespace httplib;
  14969. Server svr;
  14970. // Endpoint that returns compressible content
  14971. svr.Get("/compressible", [](const Request &, Response &res) {
  14972. // Return a large enough body to trigger compression
  14973. std::string body(1000, 'a');
  14974. res.set_content(body, "text/plain");
  14975. });
  14976. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14977. svr.wait_until_ready();
  14978. Client cli(HOST, PORT);
  14979. // Request with gzip support: should get Vary header when compressed
  14980. cli.set_compress(true);
  14981. auto res1 = cli.Get("/compressible");
  14982. ASSERT_TRUE(res1);
  14983. EXPECT_EQ(200, res1->status);
  14984. // If Content-Encoding is set, Vary should also be set
  14985. if (res1->has_header("Content-Encoding")) {
  14986. EXPECT_TRUE(res1->has_header("Vary"));
  14987. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14988. }
  14989. // Request without Accept-Encoding header: should not have compression
  14990. Headers h_no_compress;
  14991. auto res2 = cli.Get("/compressible", h_no_compress);
  14992. ASSERT_TRUE(res2);
  14993. EXPECT_EQ(200, res2->status);
  14994. // Verify Vary header is present when compression is applied
  14995. // (the exact behavior depends on server configuration)
  14996. svr.stop();
  14997. t.join();
  14998. }
  14999. TEST(ETagTest, IfRangeWithETag) {
  15000. using namespace httplib;
  15001. // Create a test file with known content
  15002. const char *fname = "if_range_testfile.txt";
  15003. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  15004. {
  15005. std::ofstream ofs(fname);
  15006. ofs << content;
  15007. ASSERT_TRUE(ofs.good());
  15008. }
  15009. Server svr;
  15010. svr.set_mount_point("/static", ".");
  15011. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15012. svr.wait_until_ready();
  15013. Client cli(HOST, PORT);
  15014. // First request: get ETag
  15015. auto res1 = cli.Get("/static/if_range_testfile.txt");
  15016. ASSERT_TRUE(res1);
  15017. ASSERT_EQ(200, res1->status);
  15018. ASSERT_TRUE(res1->has_header("ETag"));
  15019. std::string etag = res1->get_header_value("ETag");
  15020. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  15021. // Since our server generates weak ETags (W/"..."), If-Range with our
  15022. // ETag should NOT result in partial content - it should return full content.
  15023. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  15024. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  15025. ASSERT_TRUE(res2);
  15026. // Weak ETag in If-Range -> full content (200), not partial (206)
  15027. EXPECT_EQ(200, res2->status);
  15028. EXPECT_EQ(content, res2->body);
  15029. EXPECT_FALSE(res2->has_header("Content-Range"));
  15030. // Range request with non-matching If-Range (ETag): should get 200 (full
  15031. // content)
  15032. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  15033. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  15034. ASSERT_TRUE(res3);
  15035. EXPECT_EQ(200, res3->status);
  15036. EXPECT_EQ(content, res3->body);
  15037. EXPECT_FALSE(res3->has_header("Content-Range"));
  15038. // Range request with strong ETag (hypothetical - our server doesn't generate
  15039. // strong ETags, but if client sends a strong ETag that doesn't match, it
  15040. // should return full content)
  15041. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  15042. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  15043. ASSERT_TRUE(res4);
  15044. EXPECT_EQ(200, res4->status);
  15045. EXPECT_EQ(content, res4->body);
  15046. EXPECT_FALSE(res4->has_header("Content-Range"));
  15047. svr.stop();
  15048. t.join();
  15049. std::remove(fname);
  15050. }
  15051. TEST(ETagTest, IfRangeWithDate) {
  15052. using namespace httplib;
  15053. // Create a test file
  15054. const char *fname = "if_range_date_testfile.txt";
  15055. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  15056. {
  15057. std::ofstream ofs(fname);
  15058. ofs << content;
  15059. ASSERT_TRUE(ofs.good());
  15060. }
  15061. Server svr;
  15062. svr.set_mount_point("/static", ".");
  15063. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15064. svr.wait_until_ready();
  15065. Client cli(HOST, PORT);
  15066. // First request: get Last-Modified
  15067. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  15068. ASSERT_TRUE(res1);
  15069. ASSERT_EQ(200, res1->status);
  15070. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15071. std::string last_modified = res1->get_header_value("Last-Modified");
  15072. // Range request with matching If-Range (date): should get 206
  15073. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  15074. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  15075. ASSERT_TRUE(res2);
  15076. EXPECT_EQ(206, res2->status);
  15077. EXPECT_EQ("FGHIJ", res2->body);
  15078. // Range request with old If-Range date: should get 200 (full content)
  15079. Headers h3 = {{"Range", "bytes=5-9"},
  15080. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15081. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  15082. ASSERT_TRUE(res3);
  15083. EXPECT_EQ(200, res3->status);
  15084. EXPECT_EQ(content, res3->body);
  15085. // Range request with future If-Range date: should get 206
  15086. Headers h4 = {{"Range", "bytes=0-4"},
  15087. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15088. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  15089. ASSERT_TRUE(res4);
  15090. EXPECT_EQ(206, res4->status);
  15091. EXPECT_EQ("ABCDE", res4->body);
  15092. svr.stop();
  15093. t.join();
  15094. std::remove(fname);
  15095. }
  15096. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  15097. using namespace httplib;
  15098. const char *fname = "etag_malformed.txt";
  15099. const char *content = "malformed-etag";
  15100. {
  15101. std::ofstream ofs(fname);
  15102. ofs << content;
  15103. ASSERT_TRUE(ofs.good());
  15104. }
  15105. Server svr;
  15106. svr.set_mount_point("/static", ".");
  15107. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15108. svr.wait_until_ready();
  15109. Client cli(HOST, PORT);
  15110. // baseline: should get 200 and an ETag
  15111. auto res1 = cli.Get("/static/etag_malformed.txt");
  15112. ASSERT_TRUE(res1);
  15113. ASSERT_EQ(200, res1->status);
  15114. ASSERT_TRUE(res1->has_header("ETag"));
  15115. // Malformed ETag value (missing quotes) should be treated as non-matching
  15116. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  15117. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  15118. ASSERT_TRUE(res_bad);
  15119. EXPECT_EQ(200, res_bad->status);
  15120. // Whitespace-only header value should be considered invalid / non-matching
  15121. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  15122. "Host: localhost\r\n"
  15123. "If-None-Match: \r\n"
  15124. "Connection: close\r\n"
  15125. "\r\n";
  15126. std::string out;
  15127. ASSERT_TRUE(send_request(5, raw_req, &out));
  15128. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15129. svr.stop();
  15130. t.join();
  15131. std::remove(fname);
  15132. }
  15133. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  15134. using namespace httplib;
  15135. const char *fname = "ims_invalid_format.txt";
  15136. const char *content = "ims-bad-format";
  15137. {
  15138. std::ofstream ofs(fname);
  15139. ofs << content;
  15140. ASSERT_TRUE(ofs.good());
  15141. }
  15142. Server svr;
  15143. svr.set_mount_point("/static", ".");
  15144. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15145. svr.wait_until_ready();
  15146. Client cli(HOST, PORT);
  15147. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  15148. ASSERT_TRUE(res1);
  15149. ASSERT_EQ(200, res1->status);
  15150. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15151. // If-Modified-Since with invalid format should not result in 304
  15152. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  15153. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  15154. ASSERT_TRUE(res_bad);
  15155. EXPECT_EQ(200, res_bad->status);
  15156. // If-Range with invalid date format should be treated as mismatch -> full
  15157. // content (200)
  15158. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  15159. {"If-Range", "invalid-date"}};
  15160. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  15161. ASSERT_TRUE(res_ifrange);
  15162. EXPECT_EQ(200, res_ifrange->status);
  15163. svr.stop();
  15164. t.join();
  15165. std::remove(fname);
  15166. }
  15167. TEST(ETagTest, IfRangeWithMalformedETag) {
  15168. using namespace httplib;
  15169. const char *fname = "ifrange_malformed.txt";
  15170. const std::string content = "0123456789";
  15171. {
  15172. std::ofstream ofs(fname);
  15173. ofs << content;
  15174. ASSERT_TRUE(ofs.good());
  15175. }
  15176. Server svr;
  15177. svr.set_mount_point("/static", ".");
  15178. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15179. svr.wait_until_ready();
  15180. Client cli(HOST, PORT);
  15181. // First request: get ETag
  15182. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  15183. ASSERT_TRUE(res1);
  15184. ASSERT_EQ(200, res1->status);
  15185. ASSERT_TRUE(res1->has_header("ETag"));
  15186. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  15187. // full content (200)
  15188. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  15189. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  15190. ASSERT_TRUE(res2);
  15191. EXPECT_EQ(200, res2->status);
  15192. EXPECT_EQ(content, res2->body);
  15193. svr.stop();
  15194. t.join();
  15195. std::remove(fname);
  15196. }
  15197. TEST(ETagTest, ExtremeLargeDateValues) {
  15198. using namespace httplib;
  15199. const char *fname = "ims_extreme_date.txt";
  15200. const char *content = "ims-extreme-date";
  15201. {
  15202. std::ofstream ofs(fname);
  15203. ofs << content;
  15204. ASSERT_TRUE(ofs.good());
  15205. }
  15206. Server svr;
  15207. svr.set_mount_point("/static", ".");
  15208. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15209. svr.wait_until_ready();
  15210. Client cli(HOST, PORT);
  15211. auto res1 = cli.Get(std::string("/static/") + fname);
  15212. ASSERT_TRUE(res1);
  15213. ASSERT_EQ(200, res1->status);
  15214. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15215. // Extremely large year that may overflow date parsing routines.
  15216. Headers h_large_date = {
  15217. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15218. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  15219. ASSERT_TRUE(res_bad);
  15220. // Expect server to treat this as invalid/mismatch and return full content
  15221. EXPECT_EQ(200, res_bad->status);
  15222. // If-Range with extremely large date should be treated as mismatch -> full
  15223. // content (200)
  15224. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  15225. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15226. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  15227. ASSERT_TRUE(res_ifrange);
  15228. EXPECT_EQ(200, res_ifrange->status);
  15229. svr.stop();
  15230. t.join();
  15231. std::remove(fname);
  15232. }
  15233. TEST(ETagTest, NegativeFileModificationTime) {
  15234. using namespace httplib;
  15235. const char *fname = "ims_negative_mtime.txt";
  15236. const std::string content = "negative-mtime";
  15237. {
  15238. std::ofstream ofs(fname);
  15239. ofs << content;
  15240. ASSERT_TRUE(ofs.good());
  15241. }
  15242. // Try to set file mtime to a negative value. This may fail on some
  15243. // platforms/filesystems; if it fails, the test will still verify server
  15244. // behaves safely by performing a regular conditional request.
  15245. #if defined(__APPLE__) || defined(__linux__)
  15246. bool set_negative = false;
  15247. do {
  15248. struct timeval times[2];
  15249. // access time: now
  15250. times[0].tv_sec = time(nullptr);
  15251. times[0].tv_usec = 0;
  15252. // modification time: negative (e.g., -1)
  15253. times[1].tv_sec = -1;
  15254. times[1].tv_usec = 0;
  15255. if (utimes(fname, times) == 0) { set_negative = true; }
  15256. } while (0);
  15257. #else
  15258. bool set_negative = false;
  15259. #endif
  15260. Server svr;
  15261. svr.set_mount_point("/static", ".");
  15262. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15263. svr.wait_until_ready();
  15264. Client cli(HOST, PORT);
  15265. auto res1 = cli.Get(std::string("/static/") + fname);
  15266. ASSERT_TRUE(res1);
  15267. ASSERT_EQ(200, res1->status);
  15268. bool has_last_modified = res1->has_header("Last-Modified");
  15269. std::string last_modified;
  15270. if (has_last_modified) {
  15271. last_modified = res1->get_header_value("Last-Modified");
  15272. }
  15273. if (set_negative) {
  15274. // If we successfully set a negative mtime, ensure server returns a
  15275. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  15276. // with an old date and ensure server handles it without crash.
  15277. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  15278. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  15279. ASSERT_TRUE(res2);
  15280. // Behavior may vary; at minimum ensure server responds (200 or 304).
  15281. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  15282. } else {
  15283. // Could not set negative mtime on this platform; fall back to verifying
  15284. // that normal invalid/malformed dates are treated safely (non-304).
  15285. Headers h_bad_date = {
  15286. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15287. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  15288. ASSERT_TRUE(res_bad);
  15289. EXPECT_EQ(200, res_bad->status);
  15290. }
  15291. svr.stop();
  15292. t.join();
  15293. std::remove(fname);
  15294. }
  15295. //==============================================================================
  15296. // SSE Parsing Tests
  15297. //==============================================================================
  15298. class SSEParsingTest : public ::testing::Test {
  15299. protected:
  15300. // Test helper that mimics SSE parsing behavior
  15301. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  15302. int &retry_ms) {
  15303. // Blank line signals end of event
  15304. if (line.empty() || line == "\r") { return true; }
  15305. // Lines starting with ':' are comments (ignored)
  15306. if (!line.empty() && line[0] == ':') { return false; }
  15307. // Find the colon separator
  15308. auto colon_pos = line.find(':');
  15309. if (colon_pos == std::string::npos) {
  15310. // Line with no colon is treated as field name with empty value
  15311. return false;
  15312. }
  15313. std::string field = line.substr(0, colon_pos);
  15314. std::string value;
  15315. // Value starts after colon, skip optional single space
  15316. if (colon_pos + 1 < line.size()) {
  15317. size_t value_start = colon_pos + 1;
  15318. if (line[value_start] == ' ') { value_start++; }
  15319. value = line.substr(value_start);
  15320. // Remove trailing \r if present
  15321. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  15322. }
  15323. // Handle known fields
  15324. if (field == "event") {
  15325. msg.event = value;
  15326. } else if (field == "data") {
  15327. // Multiple data lines are concatenated with newlines
  15328. if (!msg.data.empty()) { msg.data += "\n"; }
  15329. msg.data += value;
  15330. } else if (field == "id") {
  15331. // Empty id is valid (clears the last event ID)
  15332. msg.id = value;
  15333. } else if (field == "retry") {
  15334. // Parse retry interval in milliseconds
  15335. {
  15336. int v = 0;
  15337. auto res =
  15338. detail::from_chars(value.data(), value.data() + value.size(), v);
  15339. if (res.ec == std::errc{}) { retry_ms = v; }
  15340. }
  15341. }
  15342. // Unknown fields are ignored per SSE spec
  15343. return false;
  15344. }
  15345. };
  15346. // Test: Single-line data
  15347. TEST_F(SSEParsingTest, SingleLineData) {
  15348. sse::SSEMessage msg;
  15349. int retry_ms = 3000;
  15350. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  15351. EXPECT_EQ(msg.data, "hello");
  15352. EXPECT_EQ(msg.event, "message");
  15353. // Blank line ends event
  15354. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15355. }
  15356. // Test: Multi-line data
  15357. TEST_F(SSEParsingTest, MultiLineData) {
  15358. sse::SSEMessage msg;
  15359. int retry_ms = 3000;
  15360. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  15361. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  15362. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  15363. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  15364. }
  15365. // Test: Custom event types
  15366. TEST_F(SSEParsingTest, CustomEventType) {
  15367. sse::SSEMessage msg;
  15368. int retry_ms = 3000;
  15369. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  15370. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  15371. EXPECT_EQ(msg.event, "update");
  15372. EXPECT_EQ(msg.data, "payload");
  15373. }
  15374. // Test: Event ID handling
  15375. TEST_F(SSEParsingTest, EventIdHandling) {
  15376. sse::SSEMessage msg;
  15377. int retry_ms = 3000;
  15378. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  15379. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  15380. EXPECT_EQ(msg.id, "12345");
  15381. }
  15382. // Test: Empty event ID (clears last event ID)
  15383. TEST_F(SSEParsingTest, EmptyEventId) {
  15384. sse::SSEMessage msg;
  15385. msg.id = "previous";
  15386. int retry_ms = 3000;
  15387. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  15388. EXPECT_EQ(msg.id, "");
  15389. }
  15390. // Test: Retry field parsing
  15391. TEST_F(SSEParsingTest, RetryFieldParsing) {
  15392. sse::SSEMessage msg;
  15393. int retry_ms = 3000;
  15394. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  15395. EXPECT_EQ(retry_ms, 5000);
  15396. }
  15397. // Test: Invalid retry value
  15398. TEST_F(SSEParsingTest, InvalidRetryValue) {
  15399. sse::SSEMessage msg;
  15400. int retry_ms = 3000;
  15401. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  15402. EXPECT_EQ(retry_ms, 3000); // Unchanged
  15403. }
  15404. // Test: Comments (lines starting with :)
  15405. TEST_F(SSEParsingTest, CommentsIgnored) {
  15406. sse::SSEMessage msg;
  15407. int retry_ms = 3000;
  15408. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  15409. EXPECT_EQ(msg.data, "");
  15410. EXPECT_EQ(msg.event, "message");
  15411. }
  15412. // Test: Colon in value
  15413. TEST_F(SSEParsingTest, ColonInValue) {
  15414. sse::SSEMessage msg;
  15415. int retry_ms = 3000;
  15416. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15417. EXPECT_EQ(msg.data, "hello:world:test");
  15418. }
  15419. // Test: Line with no colon (field name only)
  15420. TEST_F(SSEParsingTest, FieldNameOnly) {
  15421. sse::SSEMessage msg;
  15422. int retry_ms = 3000;
  15423. // According to SSE spec, this is treated as field name with empty value
  15424. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15425. // Since we don't recognize "data" without colon, data should be empty
  15426. EXPECT_EQ(msg.data, "");
  15427. }
  15428. // Test: Trailing \r handling
  15429. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15430. sse::SSEMessage msg;
  15431. int retry_ms = 3000;
  15432. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15433. EXPECT_EQ(msg.data, "hello");
  15434. }
  15435. // Test: Unknown fields ignored
  15436. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15437. sse::SSEMessage msg;
  15438. int retry_ms = 3000;
  15439. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15440. EXPECT_EQ(msg.data, "");
  15441. EXPECT_EQ(msg.event, "message");
  15442. }
  15443. // Test: Space after colon is optional
  15444. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15445. sse::SSEMessage msg1, msg2;
  15446. int retry_ms = 3000;
  15447. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15448. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15449. EXPECT_EQ(msg1.data, "hello");
  15450. EXPECT_EQ(msg2.data, "hello");
  15451. }
  15452. // Test: SSEMessage clear
  15453. TEST_F(SSEParsingTest, MessageClear) {
  15454. sse::SSEMessage msg;
  15455. msg.event = "custom";
  15456. msg.data = "some data";
  15457. msg.id = "123";
  15458. msg.clear();
  15459. EXPECT_EQ(msg.event, "message");
  15460. EXPECT_EQ(msg.data, "");
  15461. EXPECT_EQ(msg.id, "");
  15462. }
  15463. // Test: Complete event parsing
  15464. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15465. sse::SSEMessage msg;
  15466. int retry_ms = 3000;
  15467. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15468. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15469. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15470. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15471. // Blank line ends event
  15472. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15473. EXPECT_EQ(msg.event, "notification");
  15474. EXPECT_EQ(msg.id, "evt-42");
  15475. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15476. EXPECT_EQ(retry_ms, 1000);
  15477. }
  15478. //==============================================================================
  15479. // Integration Tests with Server
  15480. //==============================================================================
  15481. class SSEIntegrationTest : public ::testing::Test {
  15482. protected:
  15483. void SetUp() override {
  15484. stop_server_.store(false);
  15485. events_.clear();
  15486. server_ = httplib::detail::make_unique<Server>();
  15487. setup_server();
  15488. start_server();
  15489. }
  15490. void TearDown() override {
  15491. stop_server_.store(true);
  15492. event_cv_.notify_all();
  15493. server_->stop();
  15494. if (server_thread_.joinable()) { server_thread_.join(); }
  15495. }
  15496. void setup_server() {
  15497. // Simple SSE endpoint
  15498. server_->Get("/events", [this](const Request &req, Response &res) {
  15499. auto last_id = req.get_header_value("Last-Event-ID");
  15500. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15501. res.set_chunked_content_provider(
  15502. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15503. std::unique_lock<std::mutex> lock(event_mutex_);
  15504. if (event_cv_.wait_for(
  15505. lock, std::chrono::milliseconds(200), [this] {
  15506. return !events_.empty() || stop_server_.load();
  15507. })) {
  15508. if (stop_server_.load()) { return false; }
  15509. if (!events_.empty()) {
  15510. std::string event = events_.front();
  15511. events_.erase(events_.begin());
  15512. sink.write(event.data(), event.size());
  15513. return true;
  15514. }
  15515. }
  15516. return !stop_server_.load();
  15517. });
  15518. });
  15519. // Endpoint that returns error
  15520. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15521. res.status = 500;
  15522. res.set_content("Internal Server Error", "text/plain");
  15523. });
  15524. // Endpoint for custom event types
  15525. server_->Get("/custom-events", [](const Request &, Response &res) {
  15526. res.set_chunked_content_provider(
  15527. "text/event-stream", [](size_t offset, DataSink &sink) {
  15528. if (offset == 0) {
  15529. std::string event = "event: update\ndata: updated\n\n"
  15530. "event: delete\ndata: deleted\n\n";
  15531. sink.write(event.data(), event.size());
  15532. }
  15533. return false; // End stream after sending
  15534. });
  15535. });
  15536. }
  15537. void start_server() {
  15538. port_ = server_->bind_to_any_port(HOST);
  15539. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15540. // Wait for server to start
  15541. while (!server_->is_running()) {
  15542. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15543. }
  15544. }
  15545. int get_port() const { return port_; }
  15546. void send_event(const std::string &event) {
  15547. std::lock_guard<std::mutex> lock(event_mutex_);
  15548. events_.push_back(event);
  15549. event_cv_.notify_all();
  15550. }
  15551. std::unique_ptr<Server> server_;
  15552. std::thread server_thread_;
  15553. std::mutex event_mutex_;
  15554. std::condition_variable event_cv_;
  15555. std::vector<std::string> events_;
  15556. std::atomic<bool> stop_server_{false};
  15557. std::string last_received_event_id_;
  15558. int port_ = 0;
  15559. };
  15560. // Test: Successful connection and on_open callback
  15561. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15562. // Add a simple endpoint that sends one event and closes
  15563. server_->Get("/simple-event", [](const Request &, Response &res) {
  15564. res.set_chunked_content_provider(
  15565. "text/event-stream", [](size_t offset, DataSink &sink) {
  15566. if (offset == 0) {
  15567. std::string event = "data: hello\n\n";
  15568. sink.write(event.data(), event.size());
  15569. }
  15570. return false; // Close stream after sending
  15571. });
  15572. });
  15573. Client client("localhost", get_port());
  15574. sse::SSEClient sse(client, "/simple-event");
  15575. std::atomic<bool> open_called{false};
  15576. std::atomic<bool> message_received{false};
  15577. sse.on_open([&open_called]() { open_called.store(true); });
  15578. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15579. if (msg.data == "hello") { message_received.store(true); }
  15580. });
  15581. sse.set_reconnect_interval(100);
  15582. sse.set_max_reconnect_attempts(1);
  15583. // Start async
  15584. sse.start_async();
  15585. // Wait for message to be processed
  15586. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15587. sse.stop();
  15588. EXPECT_TRUE(open_called.load());
  15589. EXPECT_TRUE(message_received.load());
  15590. }
  15591. // Test: on_message callback
  15592. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15593. // Endpoint that sends multiple events then closes
  15594. server_->Get("/multi-event", [](const Request &, Response &res) {
  15595. res.set_chunked_content_provider(
  15596. "text/event-stream", [](size_t offset, DataSink &sink) {
  15597. if (offset == 0) {
  15598. std::string events = "data: message1\n\ndata: message2\n\n";
  15599. sink.write(events.data(), events.size());
  15600. }
  15601. return false;
  15602. });
  15603. });
  15604. Client client("localhost", get_port());
  15605. sse::SSEClient sse(client, "/multi-event");
  15606. std::vector<std::string> received_messages;
  15607. std::mutex messages_mutex;
  15608. sse.on_message([&](const sse::SSEMessage &msg) {
  15609. std::lock_guard<std::mutex> lock(messages_mutex);
  15610. received_messages.push_back(msg.data);
  15611. });
  15612. sse.set_reconnect_interval(100);
  15613. sse.set_max_reconnect_attempts(1);
  15614. sse.start_async();
  15615. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15616. sse.stop();
  15617. std::lock_guard<std::mutex> lock(messages_mutex);
  15618. EXPECT_GE(received_messages.size(), 2u);
  15619. if (received_messages.size() >= 2) {
  15620. EXPECT_EQ(received_messages[0], "message1");
  15621. EXPECT_EQ(received_messages[1], "message2");
  15622. }
  15623. }
  15624. // Test: on_event for specific types
  15625. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15626. Client client("localhost", get_port());
  15627. sse::SSEClient sse(client, "/custom-events");
  15628. std::atomic<bool> update_received{false};
  15629. std::atomic<bool> delete_received{false};
  15630. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15631. if (msg.data == "updated") { update_received.store(true); }
  15632. });
  15633. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15634. if (msg.data == "deleted") { delete_received.store(true); }
  15635. });
  15636. sse.set_max_reconnect_attempts(1);
  15637. sse.start_async();
  15638. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15639. sse.stop();
  15640. EXPECT_TRUE(update_received.load());
  15641. EXPECT_TRUE(delete_received.load());
  15642. }
  15643. // Test: on_error callback on connection failure
  15644. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15645. // Connect to a non-existent port
  15646. Client client("localhost", 59999);
  15647. sse::SSEClient sse(client, "/events");
  15648. std::atomic<bool> error_called{false};
  15649. Error received_error = Error::Success;
  15650. sse.on_error([&](Error err) {
  15651. error_called.store(true);
  15652. received_error = err;
  15653. });
  15654. sse.set_reconnect_interval(50);
  15655. sse.set_max_reconnect_attempts(1);
  15656. sse.start_async();
  15657. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15658. sse.stop();
  15659. EXPECT_TRUE(error_called.load());
  15660. EXPECT_NE(received_error, Error::Success);
  15661. }
  15662. // Test: Last-Event-ID header sent on reconnect
  15663. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15664. // Endpoint that sends event with ID
  15665. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15666. res.set_chunked_content_provider(
  15667. "text/event-stream", [](size_t offset, DataSink &sink) {
  15668. if (offset == 0) {
  15669. std::string event = "id: evt-123\ndata: test\n\n";
  15670. sink.write(event.data(), event.size());
  15671. }
  15672. return false;
  15673. });
  15674. });
  15675. Client client("localhost", get_port());
  15676. sse::SSEClient sse(client, "/event-with-id");
  15677. std::atomic<bool> id_received{false};
  15678. sse.on_message([&](const sse::SSEMessage &msg) {
  15679. if (!msg.id.empty()) { id_received.store(true); }
  15680. });
  15681. sse.set_reconnect_interval(100);
  15682. sse.set_max_reconnect_attempts(1);
  15683. sse.start_async();
  15684. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15685. sse.stop();
  15686. EXPECT_TRUE(id_received.load());
  15687. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15688. }
  15689. // Test: Manual stop
  15690. TEST_F(SSEIntegrationTest, ManualStop) {
  15691. // Endpoint that sends one event and stays open briefly
  15692. std::atomic<bool> handler_running{true};
  15693. server_->Get("/stay-open", [&handler_running](const Request &,
  15694. Response &res) {
  15695. res.set_chunked_content_provider(
  15696. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15697. if (offset == 0) {
  15698. std::string event = "data: connected\n\n";
  15699. sink.write(event.data(), event.size());
  15700. }
  15701. // Keep connection open while handler_running is true
  15702. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15703. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15704. }
  15705. return false;
  15706. });
  15707. });
  15708. Client client("localhost", get_port());
  15709. sse::SSEClient sse(client, "/stay-open");
  15710. std::atomic<bool> connected{false};
  15711. sse.on_open([&connected]() { connected.store(true); });
  15712. sse.set_reconnect_interval(100);
  15713. sse.set_max_reconnect_attempts(1);
  15714. sse.start_async();
  15715. // Wait for connection to establish
  15716. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15717. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15718. }
  15719. EXPECT_TRUE(connected.load());
  15720. EXPECT_TRUE(sse.is_connected());
  15721. // Signal handler to stop
  15722. handler_running.store(false);
  15723. // Stop SSE client
  15724. sse.stop();
  15725. EXPECT_FALSE(sse.is_connected());
  15726. }
  15727. // Test: SSEClient with custom headers
  15728. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15729. // Setup a server endpoint that checks for custom header
  15730. std::atomic<bool> header_received{false};
  15731. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15732. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15733. header_received.store(true);
  15734. }
  15735. res.set_chunked_content_provider("text/event-stream",
  15736. [](size_t, DataSink &) { return false; });
  15737. });
  15738. Client client("localhost", get_port());
  15739. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15740. sse::SSEClient sse(client, "/header-check", headers);
  15741. sse.set_max_reconnect_attempts(1);
  15742. sse.start_async();
  15743. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15744. sse.stop();
  15745. EXPECT_TRUE(header_received.load());
  15746. }
  15747. // Test: Reconnect interval configuration
  15748. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15749. Client client("localhost", get_port());
  15750. sse::SSEClient sse(client, "/events");
  15751. auto &result = sse.set_reconnect_interval(500);
  15752. // Builder pattern should return reference to self
  15753. EXPECT_EQ(&result, &sse);
  15754. }
  15755. // Test: Max reconnect attempts
  15756. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15757. // Connect to non-existent port to force reconnects
  15758. Client client("localhost", 59998);
  15759. sse::SSEClient sse(client, "/events");
  15760. std::atomic<int> error_count{0};
  15761. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15762. sse.set_reconnect_interval(50);
  15763. sse.set_max_reconnect_attempts(2);
  15764. auto start = std::chrono::steady_clock::now();
  15765. sse.start(); // Blocking call
  15766. auto end = std::chrono::steady_clock::now();
  15767. // Should have stopped after 2 failed attempts
  15768. EXPECT_GE(error_count.load(), 2);
  15769. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15770. auto duration =
  15771. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15772. #ifdef _WIN32
  15773. // Windows is much slower for socket connection failures
  15774. EXPECT_LT(duration.count(), 7000);
  15775. #else
  15776. EXPECT_LT(duration.count(), 1000);
  15777. #endif
  15778. }
  15779. // Test: Multi-line data in integration
  15780. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15781. // Endpoint with multi-line data
  15782. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15783. res.set_chunked_content_provider(
  15784. "text/event-stream", [](size_t offset, DataSink &sink) {
  15785. if (offset == 0) {
  15786. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15787. sink.write(event.data(), event.size());
  15788. }
  15789. return false;
  15790. });
  15791. });
  15792. Client client("localhost", get_port());
  15793. sse::SSEClient sse(client, "/multiline-data");
  15794. std::string received_data;
  15795. std::mutex data_mutex;
  15796. sse.on_message([&](const sse::SSEMessage &msg) {
  15797. std::lock_guard<std::mutex> lock(data_mutex);
  15798. received_data = msg.data;
  15799. });
  15800. sse.set_reconnect_interval(100);
  15801. sse.set_max_reconnect_attempts(1);
  15802. sse.start_async();
  15803. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15804. sse.stop();
  15805. std::lock_guard<std::mutex> lock(data_mutex);
  15806. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15807. }
  15808. // Test: Auto-reconnect after server disconnection
  15809. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15810. std::atomic<int> connection_count{0};
  15811. std::atomic<int> message_count{0};
  15812. // Endpoint that sends one event and closes, forcing reconnect
  15813. server_->Get("/reconnect-test",
  15814. [&connection_count](const Request &, Response &res) {
  15815. connection_count.fetch_add(1);
  15816. res.set_chunked_content_provider(
  15817. "text/event-stream", [](size_t offset, DataSink &sink) {
  15818. if (offset == 0) {
  15819. std::string event = "data: hello\n\n";
  15820. sink.write(event.data(), event.size());
  15821. }
  15822. return false; // Close connection after sending
  15823. });
  15824. });
  15825. Client client("localhost", get_port());
  15826. sse::SSEClient sse(client, "/reconnect-test");
  15827. sse.on_message([&message_count](const sse::SSEMessage &) {
  15828. message_count.fetch_add(1);
  15829. });
  15830. sse.set_reconnect_interval(100);
  15831. sse.set_max_reconnect_attempts(3);
  15832. sse.start_async();
  15833. // Wait long enough for multiple reconnects
  15834. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15835. sse.stop();
  15836. // Should have connected multiple times (initial + reconnects)
  15837. EXPECT_GE(connection_count.load(), 2);
  15838. // Should have received messages from multiple connections
  15839. EXPECT_GE(message_count.load(), 2);
  15840. }
  15841. // Test: Last-Event-ID sent on reconnect
  15842. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15843. std::atomic<int> connection_count{0};
  15844. std::vector<std::string> received_last_event_ids;
  15845. std::mutex id_mutex;
  15846. // Endpoint that checks Last-Event-ID header and sends event with ID
  15847. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15848. int conn = connection_count.fetch_add(1);
  15849. // Capture the Last-Event-ID header from each connection
  15850. {
  15851. std::lock_guard<std::mutex> lock(id_mutex);
  15852. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15853. }
  15854. res.set_chunked_content_provider(
  15855. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15856. if (offset == 0) {
  15857. std::string event =
  15858. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15859. sink.write(event.data(), event.size());
  15860. }
  15861. return false;
  15862. });
  15863. });
  15864. Client client("localhost", get_port());
  15865. sse::SSEClient sse(client, "/reconnect-with-id");
  15866. sse.set_reconnect_interval(100);
  15867. sse.set_max_reconnect_attempts(3);
  15868. sse.start_async();
  15869. // Wait for at least 2 connections
  15870. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15871. sse.stop();
  15872. // Verify behavior
  15873. std::lock_guard<std::mutex> lock(id_mutex);
  15874. EXPECT_GE(received_last_event_ids.size(), 2u);
  15875. // First connection should have no Last-Event-ID
  15876. if (!received_last_event_ids.empty()) {
  15877. EXPECT_EQ(received_last_event_ids[0], "");
  15878. }
  15879. // Second connection should have Last-Event-ID from first connection
  15880. if (received_last_event_ids.size() >= 2) {
  15881. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15882. }
  15883. }
  15884. // Test: set_headers updates headers used on reconnect
  15885. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15886. std::vector<std::string> received_tokens;
  15887. std::mutex token_mutex;
  15888. // Endpoint that captures Authorization header
  15889. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15890. {
  15891. std::lock_guard<std::mutex> lock(token_mutex);
  15892. received_tokens.push_back(req.get_header_value("Authorization"));
  15893. }
  15894. res.set_chunked_content_provider(
  15895. "text/event-stream", [](size_t offset, DataSink &sink) {
  15896. if (offset == 0) {
  15897. std::string event = "data: hello\n\n";
  15898. sink.write(event.data(), event.size());
  15899. }
  15900. return false; // Close connection to trigger reconnect
  15901. });
  15902. });
  15903. Client client("localhost", get_port());
  15904. Headers headers = {{"Authorization", "Bearer old-token"}};
  15905. sse::SSEClient sse(client, "/auth-check", headers);
  15906. // Update headers on each successful connection
  15907. sse.on_open(
  15908. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15909. sse.set_reconnect_interval(100);
  15910. sse.set_max_reconnect_attempts(3);
  15911. sse.start_async();
  15912. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15913. sse.stop();
  15914. std::lock_guard<std::mutex> lock(token_mutex);
  15915. ASSERT_GE(received_tokens.size(), 2u);
  15916. // First connection uses original header
  15917. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15918. // Second connection uses updated header from set_headers
  15919. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15920. }
  15921. // Test: 401 allows reconnection (so on_error can refresh headers)
  15922. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15923. std::atomic<int> connection_count{0};
  15924. // Endpoint: returns 401 on first attempt, 200 on second
  15925. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15926. int conn = connection_count.fetch_add(1);
  15927. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15928. res.status = StatusCode::Unauthorized_401;
  15929. res.set_content("Unauthorized", "text/plain");
  15930. return;
  15931. }
  15932. res.set_chunked_content_provider(
  15933. "text/event-stream", [](size_t offset, DataSink &sink) {
  15934. if (offset == 0) {
  15935. std::string event = "data: authenticated\n\n";
  15936. sink.write(event.data(), event.size());
  15937. }
  15938. return false;
  15939. });
  15940. });
  15941. Client client("localhost", get_port());
  15942. Headers headers = {{"Authorization", "Bearer expired"}};
  15943. sse::SSEClient sse(client, "/auth-retry", headers);
  15944. std::atomic<bool> message_received{false};
  15945. // Refresh token on error
  15946. sse.on_error(
  15947. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15948. sse.on_message([&](const sse::SSEMessage &msg) {
  15949. if (msg.data == "authenticated") { message_received.store(true); }
  15950. });
  15951. sse.set_reconnect_interval(100);
  15952. sse.set_max_reconnect_attempts(3);
  15953. sse.start_async();
  15954. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15955. sse.stop();
  15956. // Should have reconnected after 401 and succeeded with new token
  15957. EXPECT_GE(connection_count.load(), 2);
  15958. EXPECT_TRUE(message_received.load());
  15959. }
  15960. TEST(Issue2318Test, EmptyHostString) {
  15961. {
  15962. httplib::Client cli_empty("", PORT);
  15963. auto res = cli_empty.Get("/");
  15964. ASSERT_FALSE(res);
  15965. EXPECT_EQ(httplib::Error::Connection, res.error());
  15966. }
  15967. {
  15968. httplib::Client cli(" ", PORT);
  15969. auto res = cli.Get("/");
  15970. ASSERT_FALSE(res);
  15971. EXPECT_EQ(httplib::Error::Connection, res.error());
  15972. }
  15973. }
  15974. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15975. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15976. Server svr;
  15977. // Set a small payload limit (1KB)
  15978. svr.set_payload_max_length(1024);
  15979. svr.Post("/test", [&](const Request &req, Response &res) {
  15980. res.set_content("Body size: " + std::to_string(req.body.size()),
  15981. "text/plain");
  15982. });
  15983. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15984. auto se = detail::scope_exit([&] {
  15985. svr.stop();
  15986. listen_thread.join();
  15987. });
  15988. svr.wait_until_ready();
  15989. // Create data that compresses well but exceeds limit when decompressed
  15990. // 8KB of repeated null bytes compresses to a very small size
  15991. std::string original_data(8 * 1024, '\0');
  15992. // Compress the data using gzip
  15993. std::string compressed_data;
  15994. detail::gzip_compressor compressor;
  15995. compressor.compress(original_data.data(), original_data.size(), true,
  15996. [&](const char *data, size_t size) {
  15997. compressed_data.append(data, size);
  15998. return true;
  15999. });
  16000. // Verify compression worked (compressed should be much smaller)
  16001. ASSERT_LT(compressed_data.size(), original_data.size());
  16002. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  16003. // Send compressed data with Content-Encoding: gzip
  16004. Client cli(HOST, PORT);
  16005. Headers headers = {{"Content-Encoding", "gzip"}};
  16006. auto res =
  16007. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  16008. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  16009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16010. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  16011. }
  16012. #endif
  16013. // ============================================================================
  16014. // OpenSSL-Specific Tests
  16015. // ============================================================================
  16016. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16017. X509 *readCertificate(const std::string &strFileName) {
  16018. std::ifstream inStream(strFileName);
  16019. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  16020. std::istreambuf_iterator<char>());
  16021. if (strCertPEM.empty()) return (nullptr);
  16022. BIO *pbCert = BIO_new(BIO_s_mem());
  16023. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  16024. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  16025. BIO_free(pbCert);
  16026. return (pCert);
  16027. }
  16028. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  16029. std::ifstream inStream(strFileName);
  16030. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  16031. std::istreambuf_iterator<char>());
  16032. if (strPrivateKeyPEM.empty()) return (nullptr);
  16033. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  16034. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  16035. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  16036. BIO_free(pbPrivKey);
  16037. return (pPrivateKey);
  16038. }
  16039. TEST(BindServerTest, UpdateCerts) {
  16040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16041. int port = svr.bind_to_any_port("0.0.0.0");
  16042. ASSERT_TRUE(svr.is_valid());
  16043. ASSERT_TRUE(port > 0);
  16044. X509 *cert = readCertificate(SERVER_CERT_FILE);
  16045. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  16046. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  16047. ASSERT_TRUE(cert != nullptr);
  16048. ASSERT_TRUE(ca_cert != nullptr);
  16049. ASSERT_TRUE(key != nullptr);
  16050. X509_STORE *cert_store = X509_STORE_new();
  16051. X509_STORE_add_cert(cert_store, ca_cert);
  16052. // svr.update_certs(cert, key, cert_store); // deprecated
  16053. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  16054. CLIENT_CA_CERT_FILE);
  16055. ASSERT_TRUE(svr.is_valid());
  16056. svr.stop();
  16057. X509_STORE_free(cert_store);
  16058. X509_free(cert);
  16059. X509_free(ca_cert);
  16060. EVP_PKEY_free(key);
  16061. }
  16062. // Test that update_certs() updates client CA list correctly
  16063. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  16064. // Start with file-based constructor
  16065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16066. ASSERT_TRUE(svr.is_valid());
  16067. // Initially no client CA list should be set
  16068. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16069. ASSERT_TRUE(ssl_ctx != nullptr);
  16070. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  16071. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  16072. EXPECT_EQ(0, count_before);
  16073. // Now update with client CA (PEM string)
  16074. std::string cert_pem, key_pem, ca_pem;
  16075. read_file(SERVER_CERT_FILE, cert_pem);
  16076. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  16077. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  16078. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  16079. ASSERT_TRUE(svr.is_valid());
  16080. // Now client CA list should be set
  16081. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  16082. ASSERT_TRUE(ca_list_after != nullptr);
  16083. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  16084. }
  16085. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  16086. // Test that the file-path SSLServer constructor properly sets the client CA
  16087. // list that is sent to clients during the TLS handshake (CertificateRequest)
  16088. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16089. ASSERT_TRUE(svr.is_valid());
  16090. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16091. ASSERT_TRUE(ssl_ctx != nullptr);
  16092. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  16093. ASSERT_TRUE(ca_list != nullptr);
  16094. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  16095. }
  16096. #endif
  16097. // ============================================================================
  16098. // MbedTLS-Specific Tests
  16099. // ============================================================================
  16100. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  16101. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  16102. using namespace httplib::tls;
  16103. // Track if callback was invoked
  16104. bool callback_invoked = false;
  16105. // The callback receives void* ctx which is actually MbedTlsContext*
  16106. // We can access the mbedtls_ssl_config via the context
  16107. auto setup_callback = [&callback_invoked](void *ctx) {
  16108. callback_invoked = true;
  16109. // Cast to MbedTlsContext* to access the ssl config
  16110. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  16111. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  16112. // Use static variables to hold certificate data (simplified for test)
  16113. static mbedtls_x509_crt own_cert;
  16114. static mbedtls_pk_context own_key;
  16115. static mbedtls_x509_crt ca_chain;
  16116. static bool initialized = false;
  16117. if (!initialized) {
  16118. mbedtls_x509_crt_init(&own_cert);
  16119. mbedtls_pk_init(&own_key);
  16120. mbedtls_x509_crt_init(&ca_chain);
  16121. // Load server certificate
  16122. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  16123. return false;
  16124. }
  16125. // Load server private key.
  16126. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  16127. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  16128. #if MBEDTLS_VERSION_MAJOR == 3
  16129. ,
  16130. mbedtls_ctr_drbg_random, nullptr
  16131. #endif
  16132. ) != 0) {
  16133. return false;
  16134. }
  16135. // Load CA chain for client verification
  16136. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  16137. return false;
  16138. }
  16139. initialized = true;
  16140. }
  16141. // Configure the SSL config
  16142. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  16143. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  16144. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  16145. // Set minimum TLS version using mbedTLS native API
  16146. #if MBEDTLS_VERSION_MAJOR >= 3
  16147. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  16148. #else
  16149. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  16150. MBEDTLS_SSL_MINOR_VERSION_3);
  16151. #endif
  16152. return true;
  16153. };
  16154. SSLServer svr(setup_callback);
  16155. ASSERT_TRUE(svr.is_valid());
  16156. ASSERT_TRUE(callback_invoked);
  16157. svr.Get("/test", [&](const Request &req, Response &res) {
  16158. res.set_content("test", "text/plain");
  16159. auto cert = req.peer_cert();
  16160. ASSERT_TRUE(static_cast<bool>(cert));
  16161. auto common_name = cert.subject_cn();
  16162. EXPECT_EQ("Common Name", common_name);
  16163. });
  16164. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16165. auto se = detail::scope_exit([&] {
  16166. svr.stop();
  16167. t.join();
  16168. ASSERT_FALSE(svr.is_running());
  16169. });
  16170. svr.wait_until_ready();
  16171. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16172. cli.enable_server_certificate_verification(false);
  16173. cli.set_connection_timeout(30);
  16174. auto res = cli.Get("/test");
  16175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16176. ASSERT_EQ(StatusCode::OK_200, res->status);
  16177. }
  16178. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  16179. // context (owning mbedtls_ssl_config) before shutting down a still-open
  16180. // keep-alive SSL session, which reads through that config in
  16181. // mbedtls_ssl_close_notify.
  16182. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  16183. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16184. ASSERT_TRUE(svr.is_valid());
  16185. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16186. res.set_content("test", "text/plain");
  16187. });
  16188. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16189. auto se = detail::scope_exit([&] {
  16190. svr.stop();
  16191. t.join();
  16192. ASSERT_FALSE(svr.is_running());
  16193. });
  16194. svr.wait_until_ready();
  16195. {
  16196. SSLClient cli(HOST, PORT);
  16197. cli.enable_server_certificate_verification(false);
  16198. cli.set_keep_alive(true);
  16199. auto res = cli.Get("/test");
  16200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16201. ASSERT_EQ(StatusCode::OK_200, res->status);
  16202. // cli is destructed here with the keep-alive SSL session still open.
  16203. }
  16204. }
  16205. #endif
  16206. // WebSocket Tests
  16207. TEST(WebSocketTest, RSVBitsMustBeZero) {
  16208. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  16209. // defining the meaning of these bits has been negotiated.
  16210. auto make_frame = [](uint8_t first_byte) {
  16211. std::string frame;
  16212. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  16213. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  16214. frame += "Hello";
  16215. return frame;
  16216. };
  16217. // RSV1 set (0x40)
  16218. {
  16219. detail::BufferStream strm;
  16220. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  16221. ws::Opcode opcode;
  16222. std::string payload;
  16223. bool fin;
  16224. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16225. false, 1024));
  16226. }
  16227. // RSV2 set (0x20)
  16228. {
  16229. detail::BufferStream strm;
  16230. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  16231. ws::Opcode opcode;
  16232. std::string payload;
  16233. bool fin;
  16234. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16235. false, 1024));
  16236. }
  16237. // RSV3 set (0x10)
  16238. {
  16239. detail::BufferStream strm;
  16240. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  16241. ws::Opcode opcode;
  16242. std::string payload;
  16243. bool fin;
  16244. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16245. false, 1024));
  16246. }
  16247. // No RSV bits set - should succeed
  16248. {
  16249. detail::BufferStream strm;
  16250. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  16251. ws::Opcode opcode;
  16252. std::string payload;
  16253. bool fin;
  16254. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16255. false, 1024));
  16256. EXPECT_EQ(ws::Opcode::Text, opcode);
  16257. EXPECT_EQ("Hello", payload);
  16258. EXPECT_TRUE(fin);
  16259. }
  16260. }
  16261. TEST(WebSocketTest, ControlFrameValidation) {
  16262. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  16263. // payload length <= 125.
  16264. // Ping with FIN=0 - must be rejected
  16265. {
  16266. detail::BufferStream strm;
  16267. std::string frame;
  16268. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  16269. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16270. strm.write(frame.data(), frame.size());
  16271. ws::Opcode opcode;
  16272. std::string payload;
  16273. bool fin;
  16274. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16275. false, 1024));
  16276. }
  16277. // Close with FIN=0 - must be rejected
  16278. {
  16279. detail::BufferStream strm;
  16280. std::string frame;
  16281. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  16282. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16283. strm.write(frame.data(), frame.size());
  16284. ws::Opcode opcode;
  16285. std::string payload;
  16286. bool fin;
  16287. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16288. false, 1024));
  16289. }
  16290. // Ping with payload_len=126 (extended length) - must be rejected
  16291. {
  16292. detail::BufferStream strm;
  16293. std::string frame;
  16294. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16295. frame += static_cast<char>(126); // payload_len=126 (>125)
  16296. frame += static_cast<char>(0x00); // extended length high byte
  16297. frame += static_cast<char>(126); // extended length low byte
  16298. frame += std::string(126, 'x');
  16299. strm.write(frame.data(), frame.size());
  16300. ws::Opcode opcode;
  16301. std::string payload;
  16302. bool fin;
  16303. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16304. false, 1024));
  16305. }
  16306. // Ping with FIN=1 and payload_len=125 - should succeed
  16307. {
  16308. detail::BufferStream strm;
  16309. std::string frame;
  16310. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16311. frame += static_cast<char>(125); // payload_len=125
  16312. frame += std::string(125, 'x');
  16313. strm.write(frame.data(), frame.size());
  16314. ws::Opcode opcode;
  16315. std::string payload;
  16316. bool fin;
  16317. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16318. false, 1024));
  16319. EXPECT_EQ(ws::Opcode::Ping, opcode);
  16320. EXPECT_EQ(125u, payload.size());
  16321. EXPECT_TRUE(fin);
  16322. }
  16323. }
  16324. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  16325. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  16326. // length MUST be 0.
  16327. // MSB set - must be rejected
  16328. {
  16329. detail::BufferStream strm;
  16330. std::string frame;
  16331. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16332. frame += static_cast<char>(127); // 64-bit extended length
  16333. frame += static_cast<char>(0x80); // MSB set (invalid)
  16334. frame += std::string(7, '\0'); // remaining 7 bytes of length
  16335. strm.write(frame.data(), frame.size());
  16336. ws::Opcode opcode;
  16337. std::string payload;
  16338. bool fin;
  16339. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16340. false, 1024));
  16341. }
  16342. // MSB clear - should pass length parsing (will be rejected by max_len,
  16343. // but that's a different check; use a small length to verify)
  16344. {
  16345. detail::BufferStream strm;
  16346. std::string frame;
  16347. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16348. frame += static_cast<char>(127); // 64-bit extended length
  16349. frame += std::string(7, '\0'); // high bytes = 0
  16350. frame += static_cast<char>(0x03); // length = 3
  16351. frame += "abc";
  16352. strm.write(frame.data(), frame.size());
  16353. ws::Opcode opcode;
  16354. std::string payload;
  16355. bool fin;
  16356. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16357. false, 1024));
  16358. EXPECT_EQ(ws::Opcode::Text, opcode);
  16359. EXPECT_EQ("abc", payload);
  16360. }
  16361. }
  16362. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  16363. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  16364. // Valid UTF-8
  16365. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  16366. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  16367. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  16368. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  16369. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  16370. // Invalid UTF-8
  16371. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  16372. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  16373. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  16374. EXPECT_FALSE(
  16375. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  16376. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  16377. }
  16378. TEST(WebSocketTest, ConnectAndDisconnect) {
  16379. Server svr;
  16380. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16381. std::string msg;
  16382. while (ws.read(msg)) {}
  16383. });
  16384. auto port = svr.bind_to_any_port(HOST);
  16385. std::thread t([&]() { svr.listen_after_bind(); });
  16386. svr.wait_until_ready();
  16387. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16388. ASSERT_TRUE(client.connect());
  16389. EXPECT_TRUE(client.is_open());
  16390. client.close();
  16391. EXPECT_FALSE(client.is_open());
  16392. svr.stop();
  16393. t.join();
  16394. }
  16395. TEST(WebSocketTest, ValidURL) {
  16396. ws::WebSocketClient ws1("ws://localhost:8080/path");
  16397. EXPECT_TRUE(ws1.is_valid());
  16398. ws::WebSocketClient ws2("ws://example.com/path");
  16399. EXPECT_TRUE(ws2.is_valid());
  16400. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  16401. EXPECT_TRUE(ws3.is_valid());
  16402. #ifdef CPPHTTPLIB_SSL_ENABLED
  16403. ws::WebSocketClient wss1("wss://example.com/path");
  16404. EXPECT_TRUE(wss1.is_valid());
  16405. ws::WebSocketClient wss2("wss://example.com:443/path");
  16406. EXPECT_TRUE(wss2.is_valid());
  16407. #endif
  16408. }
  16409. TEST(WebSocketTest, InvalidURL) {
  16410. // No scheme
  16411. ws::WebSocketClient ws1("localhost:8080/path");
  16412. EXPECT_FALSE(ws1.is_valid());
  16413. // No path
  16414. ws::WebSocketClient ws2("ws://localhost:8080");
  16415. EXPECT_FALSE(ws2.is_valid());
  16416. // Empty string
  16417. ws::WebSocketClient ws3("");
  16418. EXPECT_FALSE(ws3.is_valid());
  16419. // Missing host
  16420. ws::WebSocketClient ws4("ws://:8080/path");
  16421. EXPECT_FALSE(ws4.is_valid());
  16422. // Port number overflow — should not crash
  16423. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16424. EXPECT_FALSE(ws5.is_valid());
  16425. // Port out of range
  16426. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16427. EXPECT_FALSE(ws6.is_valid());
  16428. }
  16429. TEST(WebSocketTest, UnsupportedScheme) {
  16430. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16431. ws::WebSocketClient ws1("http://localhost:8080/path");
  16432. EXPECT_FALSE(ws1.is_valid());
  16433. ws::WebSocketClient ws2("https://localhost:8080/path");
  16434. EXPECT_FALSE(ws2.is_valid());
  16435. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16436. EXPECT_FALSE(ws3.is_valid());
  16437. #else
  16438. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16439. std::invalid_argument);
  16440. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16441. std::invalid_argument);
  16442. #endif
  16443. }
  16444. TEST(WebSocketTest, ConnectWhenInvalid) {
  16445. ws::WebSocketClient ws("not a valid url");
  16446. EXPECT_FALSE(ws.is_valid());
  16447. EXPECT_FALSE(ws.connect());
  16448. }
  16449. TEST(WebSocketTest, DefaultPort) {
  16450. ws::WebSocketClient ws1("ws://example.com/path");
  16451. EXPECT_TRUE(ws1.is_valid());
  16452. // ws:// defaults to port 80 (verified by successful parse)
  16453. #ifdef CPPHTTPLIB_SSL_ENABLED
  16454. ws::WebSocketClient ws2("wss://example.com/path");
  16455. EXPECT_TRUE(ws2.is_valid());
  16456. // wss:// defaults to port 443 (verified by successful parse)
  16457. #endif
  16458. }
  16459. TEST(WebSocketTest, IPv6LiteralAddress) {
  16460. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16461. EXPECT_TRUE(ws1.is_valid());
  16462. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16463. EXPECT_TRUE(ws2.is_valid());
  16464. }
  16465. TEST(WebSocketTest, ComplexPath) {
  16466. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16467. EXPECT_TRUE(ws1.is_valid());
  16468. ws::WebSocketClient ws2("ws://localhost:8080/");
  16469. EXPECT_TRUE(ws2.is_valid());
  16470. }
  16471. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16472. Server svr;
  16473. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16474. std::string msg;
  16475. while (ws.read(msg)) {}
  16476. });
  16477. auto port = svr.bind_to_any_port(HOST);
  16478. std::thread t([&]() { svr.listen_after_bind(); });
  16479. svr.wait_until_ready();
  16480. auto another_host = "example.com";
  16481. auto wrong_ip = "192.0.2.1";
  16482. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16483. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16484. ASSERT_TRUE(client.connect());
  16485. EXPECT_TRUE(client.is_open());
  16486. client.close();
  16487. svr.stop();
  16488. t.join();
  16489. }
  16490. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16491. Server svr;
  16492. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16493. std::string msg;
  16494. while (ws.read(msg)) {}
  16495. });
  16496. auto port = svr.bind_to_any_port(HOST);
  16497. std::thread t([&]() { svr.listen_after_bind(); });
  16498. svr.wait_until_ready();
  16499. auto wrong_ip = "192.0.2.1";
  16500. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16501. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16502. client.set_connection_timeout(1);
  16503. client.set_read_timeout(1);
  16504. client.set_write_timeout(1);
  16505. EXPECT_FALSE(client.connect());
  16506. EXPECT_FALSE(client.is_open());
  16507. svr.stop();
  16508. t.join();
  16509. }
  16510. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  16511. // A mapped value that is not an IP literal must be resolved. HOST resolves
  16512. // from the hosts file, so this test needs no external DNS. "target.invalid"
  16513. // (RFC 6761) is only a map key and the Host header value.
  16514. auto host = "target.invalid";
  16515. Server svr;
  16516. std::string received_host;
  16517. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16518. received_host = req.get_header_value("Host");
  16519. std::string msg;
  16520. while (ws.read(msg)) {}
  16521. });
  16522. auto port = svr.bind_to_any_port(HOST);
  16523. std::thread t([&]() { svr.listen_after_bind(); });
  16524. // ASSERT_* below returns from the test body, which would leave t joinable
  16525. // and make ~thread call std::terminate.
  16526. auto se = detail::scope_exit([&] {
  16527. svr.stop();
  16528. if (t.joinable()) { t.join(); }
  16529. });
  16530. svr.wait_until_ready();
  16531. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  16532. std::to_string(port) + "/ws");
  16533. client.set_hostname_addr_map({{host, HOST}});
  16534. ASSERT_TRUE(client.connect());
  16535. EXPECT_TRUE(client.is_open());
  16536. client.close();
  16537. svr.stop();
  16538. t.join();
  16539. // The mapping only redirects the connection; the identity stays host_.
  16540. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  16541. }
  16542. class WebSocketIntegrationTest : public ::testing::Test {
  16543. protected:
  16544. void SetUp() override {
  16545. server_ = httplib::detail::make_unique<Server>();
  16546. setup_server();
  16547. start_server();
  16548. }
  16549. void TearDown() override {
  16550. server_->stop();
  16551. if (server_thread_.joinable()) { server_thread_.join(); }
  16552. }
  16553. void setup_server() {
  16554. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16555. std::string msg;
  16556. ws::ReadResult ret;
  16557. while ((ret = ws.read(msg))) {
  16558. if (ret == ws::Binary) {
  16559. ws.send(msg.data(), msg.size());
  16560. } else {
  16561. ws.send(msg);
  16562. }
  16563. }
  16564. });
  16565. server_->WebSocket("/ws-echo-string",
  16566. [](const Request &, ws::WebSocket &ws) {
  16567. std::string msg;
  16568. while (ws.read(msg)) {
  16569. ws.send("echo: " + msg);
  16570. }
  16571. });
  16572. server_->WebSocket(
  16573. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16574. // Echo back request metadata
  16575. ws.send("path:" + req.path);
  16576. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16577. std::string msg;
  16578. while (ws.read(msg)) {}
  16579. });
  16580. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16581. std::string msg;
  16582. ws.read(msg); // wait for a message
  16583. ws.close();
  16584. });
  16585. server_->WebSocket("/ws-close-status",
  16586. [](const Request &, ws::WebSocket &ws) {
  16587. std::string msg;
  16588. ws.read(msg); // wait for a message
  16589. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  16590. });
  16591. server_->WebSocket(
  16592. "/ws-subprotocol",
  16593. [](const Request &, ws::WebSocket &ws) {
  16594. std::string msg;
  16595. while (ws.read(msg)) {
  16596. ws.send(msg);
  16597. }
  16598. },
  16599. [](const std::vector<std::string> &protocols) -> std::string {
  16600. for (const auto &p : protocols) {
  16601. if (p == "graphql-ws") { return p; }
  16602. }
  16603. return "";
  16604. });
  16605. }
  16606. void start_server() {
  16607. port_ = server_->bind_to_any_port(HOST);
  16608. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16609. server_->wait_until_ready();
  16610. }
  16611. std::unique_ptr<Server> server_;
  16612. std::thread server_thread_;
  16613. int port_ = 0;
  16614. };
  16615. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16616. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16617. "/ws-echo");
  16618. ASSERT_TRUE(client.connect());
  16619. ASSERT_TRUE(client.is_open());
  16620. ASSERT_TRUE(client.send("Hello WebSocket"));
  16621. std::string msg;
  16622. EXPECT_EQ(ws::Text, client.read(msg));
  16623. EXPECT_EQ("Hello WebSocket", msg);
  16624. client.close();
  16625. }
  16626. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16627. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16628. "/ws-echo");
  16629. ASSERT_TRUE(client.connect());
  16630. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16631. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16632. std::string msg;
  16633. EXPECT_EQ(ws::Binary, client.read(msg));
  16634. EXPECT_EQ(binary_data, msg);
  16635. client.close();
  16636. }
  16637. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16638. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16639. "/ws-echo");
  16640. ASSERT_TRUE(client.connect());
  16641. for (int i = 0; i < 10; i++) {
  16642. auto text = "message " + std::to_string(i);
  16643. ASSERT_TRUE(client.send(text));
  16644. std::string msg;
  16645. ASSERT_TRUE(client.read(msg));
  16646. EXPECT_EQ(text, msg);
  16647. }
  16648. client.close();
  16649. }
  16650. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16651. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16652. "/ws-close");
  16653. ASSERT_TRUE(client.connect());
  16654. // Send a message to trigger the server to close
  16655. ASSERT_TRUE(client.send("trigger close"));
  16656. // The server will close, so read should return false
  16657. std::string msg;
  16658. EXPECT_FALSE(client.read(msg));
  16659. EXPECT_FALSE(client.is_open());
  16660. }
  16661. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16662. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16663. "/ws-echo");
  16664. ASSERT_TRUE(client.connect());
  16665. // 128KB message
  16666. std::string large_data(128 * 1024, 'X');
  16667. ASSERT_TRUE(client.send(large_data));
  16668. std::string msg;
  16669. ASSERT_TRUE(client.read(msg));
  16670. EXPECT_EQ(large_data, msg);
  16671. client.close();
  16672. }
  16673. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16674. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16675. "/ws-echo");
  16676. ASSERT_TRUE(client.connect());
  16677. const int num_threads = 4;
  16678. std::vector<std::thread> threads;
  16679. std::atomic<int> send_count{0};
  16680. for (int t = 0; t < num_threads; t++) {
  16681. threads.emplace_back([&client, &send_count, t]() {
  16682. for (int i = 0; i < 5; i++) {
  16683. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16684. if (client.send(text)) { send_count++; }
  16685. }
  16686. });
  16687. }
  16688. for (auto &th : threads) {
  16689. th.join();
  16690. }
  16691. int received = 0;
  16692. std::string msg;
  16693. while (received < send_count.load()) {
  16694. if (!client.read(msg)) { break; }
  16695. received++;
  16696. }
  16697. EXPECT_EQ(send_count.load(), received);
  16698. client.close();
  16699. }
  16700. TEST_F(WebSocketIntegrationTest, ReadString) {
  16701. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16702. "/ws-echo-string");
  16703. ASSERT_TRUE(client.connect());
  16704. ASSERT_TRUE(client.send("hello"));
  16705. std::string msg;
  16706. ASSERT_TRUE(client.read(msg));
  16707. EXPECT_EQ("echo: hello", msg);
  16708. ASSERT_TRUE(client.send("world"));
  16709. ASSERT_TRUE(client.read(msg));
  16710. EXPECT_EQ("echo: world", msg);
  16711. client.close();
  16712. }
  16713. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16714. Headers headers = {{"X-Test-Header", "test-value"}};
  16715. ws::WebSocketClient client(
  16716. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16717. ASSERT_TRUE(client.connect());
  16718. std::string msg;
  16719. ASSERT_TRUE(client.read(msg));
  16720. EXPECT_EQ("path:/ws-request-info", msg);
  16721. ASSERT_TRUE(client.read(msg));
  16722. EXPECT_EQ("header:test-value", msg);
  16723. client.close();
  16724. }
  16725. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16726. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16727. "/ws-echo");
  16728. client.set_read_timeout(1, 0); // 1 second
  16729. ASSERT_TRUE(client.connect());
  16730. // Don't send anything — server echo handler waits for a message,
  16731. // so read() should time out and return false.
  16732. std::string msg;
  16733. EXPECT_FALSE(client.read(msg));
  16734. }
  16735. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16736. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16737. "/ws-echo");
  16738. client.set_read_timeout(5, 0);
  16739. ASSERT_TRUE(client.connect());
  16740. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16741. // The server should reject it and close the connection.
  16742. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16743. client.send(oversized);
  16744. // The server's read() should have failed due to payload limit,
  16745. // so our read() should return false (connection closed).
  16746. std::string msg;
  16747. EXPECT_FALSE(client.read(msg));
  16748. }
  16749. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16750. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16751. "/ws-echo");
  16752. client.set_read_timeout(10, 0);
  16753. ASSERT_TRUE(client.connect());
  16754. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16755. // This should succeed.
  16756. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16757. ASSERT_TRUE(client.send(at_limit));
  16758. std::string msg;
  16759. ASSERT_TRUE(client.read(msg));
  16760. EXPECT_EQ(at_limit.size(), msg.size());
  16761. client.close();
  16762. }
  16763. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16764. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16765. "/nonexistent");
  16766. EXPECT_FALSE(client.connect());
  16767. EXPECT_FALSE(client.is_open());
  16768. }
  16769. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16770. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16771. "/ws-echo");
  16772. ASSERT_TRUE(client.connect());
  16773. ASSERT_TRUE(client.send(""));
  16774. std::string msg;
  16775. EXPECT_EQ(ws::Text, client.read(msg));
  16776. EXPECT_EQ("", msg);
  16777. client.close();
  16778. }
  16779. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16780. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16781. "/ws-echo");
  16782. // First connection
  16783. ASSERT_TRUE(client.connect());
  16784. ASSERT_TRUE(client.send("first"));
  16785. std::string msg;
  16786. ASSERT_TRUE(client.read(msg));
  16787. EXPECT_EQ("first", msg);
  16788. client.close();
  16789. EXPECT_FALSE(client.is_open());
  16790. // Reconnect using the same client object
  16791. ASSERT_TRUE(client.connect());
  16792. ASSERT_TRUE(client.is_open());
  16793. ASSERT_TRUE(client.send("second"));
  16794. ASSERT_TRUE(client.read(msg));
  16795. EXPECT_EQ("second", msg);
  16796. client.close();
  16797. }
  16798. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16799. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16800. "/ws-close-status");
  16801. ASSERT_TRUE(client.connect());
  16802. // Trigger the server to close with GoingAway status
  16803. ASSERT_TRUE(client.send("trigger"));
  16804. // read() should return false after receiving the close frame
  16805. std::string msg;
  16806. EXPECT_FALSE(client.read(msg));
  16807. EXPECT_FALSE(client.is_open());
  16808. }
  16809. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16810. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16811. "/ws-echo");
  16812. ASSERT_TRUE(client.connect());
  16813. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16814. EXPECT_FALSE(client.is_open());
  16815. }
  16816. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16817. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16818. ws::WebSocketClient client(
  16819. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16820. ASSERT_TRUE(client.connect());
  16821. // Server should have selected graphql-ws
  16822. EXPECT_EQ("graphql-ws", client.subprotocol());
  16823. client.close();
  16824. }
  16825. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16826. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16827. ws::WebSocketClient client(
  16828. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16829. ASSERT_TRUE(client.connect());
  16830. // Server should not have selected any subprotocol
  16831. EXPECT_TRUE(client.subprotocol().empty());
  16832. client.close();
  16833. }
  16834. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16835. // Connect without requesting any subprotocol
  16836. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16837. "/ws-subprotocol");
  16838. ASSERT_TRUE(client.connect());
  16839. EXPECT_TRUE(client.subprotocol().empty());
  16840. client.close();
  16841. }
  16842. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16843. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16844. "/ws-echo");
  16845. client.set_tcp_nodelay(true);
  16846. client.set_connection_timeout(3, 0);
  16847. bool socket_options_called = false;
  16848. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16849. ASSERT_TRUE(client.connect());
  16850. ASSERT_TRUE(client.is_open());
  16851. EXPECT_TRUE(socket_options_called);
  16852. ASSERT_TRUE(client.send("hello"));
  16853. std::string msg;
  16854. auto result = client.read(msg);
  16855. EXPECT_EQ(result, ws::ReadResult::Text);
  16856. EXPECT_EQ(msg, "hello");
  16857. client.close();
  16858. }
  16859. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16860. Server svr;
  16861. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16862. if (!req.has_header("Authorization")) {
  16863. res.status = StatusCode::Unauthorized_401;
  16864. res.set_content("Unauthorized", "text/plain");
  16865. return Server::HandlerResponse::Handled;
  16866. }
  16867. return Server::HandlerResponse::Unhandled;
  16868. });
  16869. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16870. std::string msg;
  16871. while (ws.read(msg)) {
  16872. ws.send(msg);
  16873. }
  16874. });
  16875. auto port = svr.bind_to_any_port("localhost");
  16876. std::thread t([&]() { svr.listen_after_bind(); });
  16877. svr.wait_until_ready();
  16878. // Without Authorization header - should be rejected before upgrade
  16879. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16880. EXPECT_FALSE(client1.connect());
  16881. // With Authorization header - should succeed
  16882. Headers headers = {{"Authorization", "Bearer token123"}};
  16883. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16884. headers);
  16885. ASSERT_TRUE(client2.connect());
  16886. ASSERT_TRUE(client2.send("hello"));
  16887. std::string msg;
  16888. ASSERT_TRUE(client2.read(msg));
  16889. EXPECT_EQ("hello", msg);
  16890. client2.close();
  16891. svr.stop();
  16892. t.join();
  16893. }
  16894. TEST(WebSocketTest, QueryStringInHandshake) {
  16895. Server svr;
  16896. std::mutex mtx;
  16897. std::string received_target;
  16898. std::string received_token;
  16899. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16900. {
  16901. std::lock_guard<std::mutex> lock(mtx);
  16902. received_target = req.target;
  16903. if (req.has_param("token")) {
  16904. received_token = req.get_param_value("token");
  16905. }
  16906. }
  16907. std::string msg;
  16908. while (ws.read(msg)) {
  16909. ws.send(msg);
  16910. }
  16911. });
  16912. auto port = svr.bind_to_any_port("localhost");
  16913. std::thread t([&]() { svr.listen_after_bind(); });
  16914. svr.wait_until_ready();
  16915. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16916. "/ws?token=ABC&session=123");
  16917. ASSERT_TRUE(client.connect());
  16918. // Round-trip ensures the handler has run and captured the request.
  16919. ASSERT_TRUE(client.send("hello"));
  16920. std::string msg;
  16921. ASSERT_TRUE(client.read(msg));
  16922. EXPECT_EQ("hello", msg);
  16923. client.close();
  16924. {
  16925. std::lock_guard<std::mutex> lock(mtx);
  16926. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16927. EXPECT_EQ("ABC", received_token);
  16928. }
  16929. svr.stop();
  16930. t.join();
  16931. }
  16932. // Run a handshake against a throwaway server and hand the request the server
  16933. // received back to the caller, so tests can assert on the headers the client
  16934. // actually put on the wire.
  16935. static void capture_websocket_handshake_request(
  16936. const Headers &client_headers,
  16937. std::function<void(const Request &, int port)> verify) {
  16938. Server svr;
  16939. std::mutex mtx;
  16940. Request received;
  16941. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16942. {
  16943. std::lock_guard<std::mutex> lock(mtx);
  16944. received = req;
  16945. }
  16946. std::string msg;
  16947. while (ws.read(msg)) {
  16948. ws.send(msg);
  16949. }
  16950. });
  16951. auto port = svr.bind_to_any_port("localhost");
  16952. std::thread t([&]() { svr.listen_after_bind(); });
  16953. auto se = detail::scope_exit([&] {
  16954. svr.stop();
  16955. t.join();
  16956. });
  16957. svr.wait_until_ready();
  16958. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  16959. client_headers);
  16960. ASSERT_TRUE(client.connect());
  16961. ASSERT_TRUE(client.send("hello"));
  16962. std::string msg;
  16963. ASSERT_TRUE(client.read(msg));
  16964. client.close();
  16965. {
  16966. std::lock_guard<std::mutex> lock(mtx);
  16967. verify(received, port);
  16968. }
  16969. }
  16970. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  16971. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  16972. // Non-default port must be present in the Host header. Default ports
  16973. // (80/443) are omitted; that logic is covered by
  16974. // MakeHostAndPortStringTest.
  16975. EXPECT_EQ("localhost:" + std::to_string(port),
  16976. req.get_header_value("Host"));
  16977. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  16978. req.get_header_value("User-Agent"));
  16979. EXPECT_FALSE(req.has_header("Accept"));
  16980. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  16981. EXPECT_FALSE(req.has_header("Content-Length"));
  16982. });
  16983. }
  16984. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  16985. capture_websocket_handshake_request(
  16986. {{"Host", "example.com"},
  16987. {"User-Agent", "custom-agent"},
  16988. {"X-Custom", "value"}},
  16989. [](const Request &req, int) {
  16990. EXPECT_EQ("example.com", req.get_header_value("Host"));
  16991. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  16992. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  16993. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  16994. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  16995. });
  16996. }
  16997. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  16998. capture_websocket_handshake_request(
  16999. {{"Upgrade", "bogus"},
  17000. {"Connection", "close"},
  17001. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  17002. {"Sec-WebSocket-Version", "8"}},
  17003. [](const Request &req, int) {
  17004. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  17005. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  17006. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  17007. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  17008. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  17009. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  17010. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  17011. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  17012. req.get_header_value("Sec-WebSocket-Key"));
  17013. });
  17014. }
  17015. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  17016. // A header the client refuses to send must abort the handshake before any
  17017. // part of it reaches the wire; a lone request line would otherwise sit in
  17018. // the peer's buffer as a truncated request.
  17019. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17020. ASSERT_NE(INVALID_SOCKET, srv);
  17021. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  17022. sockaddr_in addr{};
  17023. addr.sin_family = AF_INET;
  17024. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  17025. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17026. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17027. ASSERT_EQ(0, ::listen(srv, 1));
  17028. sockaddr_in bound{};
  17029. socklen_t bound_len = sizeof(bound);
  17030. ASSERT_EQ(
  17031. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  17032. auto port = ntohs(bound.sin_port);
  17033. ssize_t received = -1;
  17034. std::thread t([&] {
  17035. // Bound every blocking call so a regression fails the test with a bad
  17036. // value instead of hanging the suite.
  17037. fd_set rfds;
  17038. FD_ZERO(&rfds);
  17039. FD_SET(srv, &rfds);
  17040. timeval tv{5, 0};
  17041. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  17042. 0) {
  17043. return;
  17044. }
  17045. sockaddr_in cli_addr{};
  17046. socklen_t cli_len = sizeof(cli_addr);
  17047. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17048. if (cli == INVALID_SOCKET) { return; }
  17049. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  17050. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17051. char buf[4096];
  17052. received = ::recv(cli, buf, sizeof(buf), 0);
  17053. });
  17054. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  17055. // connect() has already shut the socket down by the time it returns false,
  17056. // so the peer sees EOF without waiting for the client to be destroyed.
  17057. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  17058. {{"X-Bad", "a\r\nInjected: 1"}});
  17059. EXPECT_FALSE(client.connect());
  17060. t.join();
  17061. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  17062. EXPECT_EQ(0, received);
  17063. }
  17064. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  17065. // The socket path doubles as the URL host, so it must not contain '/'.
  17066. const char *shard = getenv("GTEST_SHARD_INDEX");
  17067. const std::string sock_path =
  17068. shard ? std::string("httplib-ws-") + shard + ".sock"
  17069. : std::string("httplib-ws.sock");
  17070. std::remove(sock_path.c_str());
  17071. Server svr;
  17072. std::mutex mtx;
  17073. std::string received_host;
  17074. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17075. {
  17076. std::lock_guard<std::mutex> lock(mtx);
  17077. received_host = req.get_header_value("Host");
  17078. }
  17079. std::string msg;
  17080. while (ws.read(msg)) {
  17081. ws.send(msg);
  17082. }
  17083. });
  17084. svr.set_address_family(AF_UNIX);
  17085. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  17086. auto se = detail::scope_exit([&] {
  17087. svr.stop();
  17088. t.join();
  17089. std::remove(sock_path.c_str());
  17090. });
  17091. svr.wait_until_ready();
  17092. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  17093. client.set_address_family(AF_UNIX);
  17094. ASSERT_TRUE(client.connect());
  17095. ASSERT_TRUE(client.send("hello"));
  17096. std::string msg;
  17097. ASSERT_TRUE(client.read(msg));
  17098. client.close();
  17099. {
  17100. std::lock_guard<std::mutex> lock(mtx);
  17101. // There is no host:port for a Unix socket, so the same "localhost"
  17102. // placeholder the HTTP client uses is expected.
  17103. EXPECT_EQ("localhost", received_host);
  17104. }
  17105. }
  17106. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17107. class WebSocketSSLIntegrationTest : public ::testing::Test {
  17108. protected:
  17109. void SetUp() override {
  17110. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  17111. SERVER_PRIVATE_KEY_FILE);
  17112. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17113. std::string msg;
  17114. ws::ReadResult ret;
  17115. while ((ret = ws.read(msg))) {
  17116. if (ret == ws::Binary) {
  17117. ws.send(msg.data(), msg.size());
  17118. } else {
  17119. ws.send(msg);
  17120. }
  17121. }
  17122. });
  17123. port_ = server_->bind_to_any_port(HOST);
  17124. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17125. server_->wait_until_ready();
  17126. }
  17127. void TearDown() override {
  17128. server_->stop();
  17129. if (server_thread_.joinable()) { server_thread_.join(); }
  17130. }
  17131. std::unique_ptr<SSLServer> server_;
  17132. std::thread server_thread_;
  17133. int port_ = 0;
  17134. };
  17135. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  17136. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17137. "/ws-echo");
  17138. client.enable_server_certificate_verification(false);
  17139. ASSERT_TRUE(client.connect());
  17140. ASSERT_TRUE(client.is_open());
  17141. ASSERT_TRUE(client.send("Hello WSS"));
  17142. std::string msg;
  17143. EXPECT_EQ(ws::Text, client.read(msg));
  17144. EXPECT_EQ("Hello WSS", msg);
  17145. client.close();
  17146. }
  17147. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  17148. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  17149. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  17150. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  17151. // client (without calling close() first) is the only path that runs
  17152. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  17153. // bug exactly.
  17154. //
  17155. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  17156. // when linked against an instrumented libssl; run under Valgrind to catch it
  17157. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  17158. // suite (the freed session otherwise stalls on the close handshake) — this test
  17159. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  17160. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  17161. {
  17162. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17163. "/ws-echo");
  17164. client.enable_server_certificate_verification(false);
  17165. client.set_read_timeout(2, 0);
  17166. client.set_write_timeout(2, 0);
  17167. ASSERT_TRUE(client.connect());
  17168. ASSERT_TRUE(client.is_open());
  17169. ASSERT_TRUE(client.send("still open"));
  17170. // Intentionally do NOT call client.close(): leaving scope runs
  17171. // shutdown_and_close() with the WebSocket still open, which must send the
  17172. // close frame while the TLS session is still alive.
  17173. }
  17174. }
  17175. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  17176. // shutdown_and_close() at the start of connect(), reproducing the same
  17177. // use-after-free within the test body rather than at scope exit. The second
  17178. // connect must succeed and echo, proving the close handshake ran over a live
  17179. // session. See the note above about memory-tool requirements.
  17180. TEST_F(WebSocketSSLIntegrationTest,
  17181. ReconnectWhileOpenSendsCloseOverLiveSession) {
  17182. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17183. "/ws-echo");
  17184. client.enable_server_certificate_verification(false);
  17185. client.set_read_timeout(2, 0);
  17186. client.set_write_timeout(2, 0);
  17187. ASSERT_TRUE(client.connect());
  17188. ASSERT_TRUE(client.is_open());
  17189. ASSERT_TRUE(client.send("still open"));
  17190. // Reconnect without closing first: connect() calls shutdown_and_close() on
  17191. // the still-open connection, which must not touch a freed TLS session.
  17192. ASSERT_TRUE(client.connect());
  17193. ASSERT_TRUE(client.is_open());
  17194. ASSERT_TRUE(client.send("after reconnect"));
  17195. std::string msg;
  17196. EXPECT_EQ(ws::Text, client.read(msg));
  17197. EXPECT_EQ("after reconnect", msg);
  17198. client.close();
  17199. }
  17200. #endif
  17201. #ifdef CPPHTTPLIB_SSL_ENABLED
  17202. class WebSocketSSLCATest : public ::testing::Test {
  17203. protected:
  17204. void SetUp() override {
  17205. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  17206. SERVER_PRIVATE_KEY_FILE);
  17207. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17208. std::string msg;
  17209. while (ws.read(msg)) {
  17210. ws.send(msg);
  17211. }
  17212. });
  17213. port_ = server_->bind_to_any_port("127.0.0.1");
  17214. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17215. server_->wait_until_ready();
  17216. }
  17217. void TearDown() override {
  17218. server_->stop();
  17219. if (server_thread_.joinable()) { server_thread_.join(); }
  17220. }
  17221. std::string url() const {
  17222. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  17223. }
  17224. std::unique_ptr<SSLServer> server_;
  17225. std::thread server_thread_;
  17226. int port_ = 0;
  17227. };
  17228. // A custom CA loaded as PEM verifies the server with full certificate
  17229. // verification enabled
  17230. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  17231. ws::WebSocketClient client(url());
  17232. std::string cert;
  17233. read_file(SERVER_CERT2_FILE, cert);
  17234. client.load_ca_cert_store(cert.c_str(), cert.size());
  17235. ASSERT_TRUE(client.connect());
  17236. ASSERT_TRUE(client.send("hello"));
  17237. std::string msg;
  17238. EXPECT_EQ(ws::Text, client.read(msg));
  17239. EXPECT_EQ("hello", msg);
  17240. client.close();
  17241. }
  17242. // A custom CA that does not cover the server must fail verification (the
  17243. // custom CA is exclusive; system certs are not loaded alongside it)
  17244. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  17245. ws::WebSocketClient client(url());
  17246. std::string cert;
  17247. read_file(CLIENT_CA_CERT_FILE, cert);
  17248. client.load_ca_cert_store(cert.c_str(), cert.size());
  17249. ASSERT_FALSE(client.connect());
  17250. }
  17251. // Regression test: reconnecting with a native custom CA store used to reuse
  17252. // a store handle the previous TLS context had already freed (use-after-free
  17253. // under the OpenSSL backend). The context now lives as long as the client.
  17254. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  17255. ws::WebSocketClient client(url());
  17256. std::string cert;
  17257. read_file(SERVER_CERT2_FILE, cert);
  17258. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  17259. ASSERT_TRUE(client.connect());
  17260. client.close();
  17261. ASSERT_TRUE(client.connect());
  17262. ASSERT_TRUE(client.send("again"));
  17263. std::string msg;
  17264. EXPECT_EQ(ws::Text, client.read(msg));
  17265. EXPECT_EQ("again", msg);
  17266. client.close();
  17267. }
  17268. // Regression test: a certificate with a trusted chain but no identity match
  17269. // for the server IP must be rejected. The Mbed TLS backend used to skip
  17270. // verification entirely for IP hosts, so this connection succeeded there.
  17271. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  17272. // chain verification while the identity check must still fail.
  17273. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  17274. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17275. ASSERT_TRUE(svr.is_valid());
  17276. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17277. std::string msg;
  17278. while (ws.read(msg)) {
  17279. ws.send(msg);
  17280. }
  17281. });
  17282. auto port = svr.bind_to_any_port("127.0.0.1");
  17283. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17284. auto se = detail::scope_exit([&] {
  17285. svr.stop();
  17286. t.join();
  17287. });
  17288. svr.wait_until_ready();
  17289. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  17290. "/echo");
  17291. std::string cert;
  17292. read_file(SERVER_CERT_FILE, cert);
  17293. client.load_ca_cert_store(cert.c_str(), cert.size());
  17294. ASSERT_FALSE(client.connect());
  17295. }
  17296. #endif
  17297. #if !defined(_WIN32)
  17298. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  17299. auto secret_dir = std::string("./symlink_test_secret");
  17300. auto served_dir = std::string("./symlink_test_served");
  17301. auto secret_file = secret_dir + "/secret.txt";
  17302. auto symlink_path = served_dir + "/escape";
  17303. // Setup: create directories and files
  17304. mkdir(secret_dir.c_str(), 0755);
  17305. mkdir(served_dir.c_str(), 0755);
  17306. {
  17307. std::ofstream ofs(secret_file);
  17308. ofs << "SECRET_DATA";
  17309. }
  17310. // Create symlink using absolute path so it resolves correctly
  17311. #ifdef PATH_MAX
  17312. char abs_secret[PATH_MAX];
  17313. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  17314. #else
  17315. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  17316. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  17317. ASSERT_NE(nullptr, abs_secret);
  17318. #endif
  17319. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  17320. auto se = detail::scope_exit([&] {
  17321. unlink(symlink_path.c_str());
  17322. unlink(secret_file.c_str());
  17323. rmdir(served_dir.c_str());
  17324. rmdir(secret_dir.c_str());
  17325. });
  17326. Server svr;
  17327. svr.set_mount_point("/", served_dir);
  17328. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17329. auto se2 = detail::scope_exit([&] {
  17330. svr.stop();
  17331. listen_thread.join();
  17332. });
  17333. svr.wait_until_ready();
  17334. Client cli("localhost", PORT);
  17335. // Symlink pointing outside base dir should be blocked
  17336. auto res = cli.Get("/escape/secret.txt");
  17337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17338. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17339. }
  17340. #endif
  17341. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  17342. // A GET request with Content-Length to a static file handler must have its
  17343. // body drained before the keep-alive connection is reused. Otherwise the
  17344. // unread body bytes are interpreted as the next HTTP request.
  17345. //
  17346. // The body is sent AFTER receiving the first response (as in the original
  17347. // PoC) so that the stream_line_reader cannot buffer it together with the
  17348. // headers of the first request.
  17349. Server svr;
  17350. svr.set_mount_point("/", "./www");
  17351. std::atomic<int> smuggled_count(0);
  17352. svr.Get("/smuggled", [&](const Request &, Response &res) {
  17353. smuggled_count++;
  17354. res.set_content("oops", "text/plain");
  17355. });
  17356. auto port = svr.bind_to_any_port("localhost");
  17357. thread t = thread([&] { svr.listen_after_bind(); });
  17358. auto se = detail::scope_exit([&] {
  17359. svr.stop();
  17360. t.join();
  17361. });
  17362. svr.wait_until_ready();
  17363. auto error = Error::Success;
  17364. auto sock = detail::create_client_socket(
  17365. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  17366. /*connection_timeout_sec=*/2, 0,
  17367. /*read_timeout_sec=*/2, 0,
  17368. /*write_timeout_sec=*/2, 0, std::string(), error);
  17369. ASSERT_NE(INVALID_SOCKET, sock);
  17370. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17371. // The "smuggled" request will be sent as the body of the outer GET
  17372. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  17373. "Host: localhost\r\n"
  17374. "Connection: close\r\n"
  17375. "\r\n";
  17376. // Step 1: Send only the outer request headers (no body yet)
  17377. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  17378. "Host: localhost\r\n"
  17379. "Content-Length: " +
  17380. std::to_string(smuggled.size()) +
  17381. "\r\n"
  17382. "\r\n";
  17383. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  17384. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  17385. // Step 2: Read the first response (server serves file without reading body)
  17386. std::string first_response;
  17387. char buf[4096];
  17388. for (;;) {
  17389. auto n = recv(sock, buf, sizeof(buf), 0);
  17390. if (n <= 0) break;
  17391. first_response.append(buf, static_cast<size_t>(n));
  17392. // Stop once we have a complete response (headers + body)
  17393. auto hdr_end = first_response.find("\r\n\r\n");
  17394. if (hdr_end != std::string::npos) {
  17395. // Check for Content-Length to know when the body is complete
  17396. auto cl_pos = first_response.find("Content-Length:");
  17397. if (cl_pos != std::string::npos) {
  17398. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  17399. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  17400. auto cl = std::stoul(
  17401. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  17402. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  17403. } else {
  17404. break; // No Content-Length, assume headers-only response
  17405. }
  17406. }
  17407. }
  17408. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  17409. // Step 3: Now send the body, which looks like a new HTTP request.
  17410. // On a vulnerable server the keep-alive loop reads this as a second request.
  17411. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  17412. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  17413. // Step 4: Try to read a second response (should NOT exist after fix)
  17414. std::string second_response;
  17415. for (;;) {
  17416. auto n = recv(sock, buf, sizeof(buf), 0);
  17417. if (n <= 0) break;
  17418. second_response.append(buf, static_cast<size_t>(n));
  17419. }
  17420. // The smuggled request must NOT have been processed
  17421. EXPECT_EQ(0, smuggled_count.load());
  17422. }
  17423. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17424. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  17425. // must be rejected with 400 Bad Request.
  17426. Server svr;
  17427. svr.Post("/test", [&](const Request &, Response &res) {
  17428. res.set_content("ok", "text/plain");
  17429. });
  17430. thread t = thread([&] { svr.listen(HOST, PORT); });
  17431. auto se = detail::scope_exit([&] {
  17432. svr.stop();
  17433. t.join();
  17434. ASSERT_FALSE(svr.is_running());
  17435. });
  17436. svr.wait_until_ready();
  17437. // Exact "chunked"
  17438. {
  17439. auto req = "POST /test HTTP/1.1\r\n"
  17440. "Host: localhost\r\n"
  17441. "Content-Length: 5\r\n"
  17442. "Transfer-Encoding: chunked\r\n"
  17443. "Connection: close\r\n"
  17444. "\r\n"
  17445. "hello";
  17446. std::string response;
  17447. ASSERT_TRUE(send_request(1, req, &response));
  17448. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17449. response.substr(0, response.find("\r\n")));
  17450. }
  17451. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  17452. {
  17453. auto req = "POST /test HTTP/1.1\r\n"
  17454. "Host: localhost\r\n"
  17455. "Content-Length: 5\r\n"
  17456. "Transfer-Encoding: gzip, chunked\r\n"
  17457. "Connection: close\r\n"
  17458. "\r\n"
  17459. "hello";
  17460. std::string response;
  17461. ASSERT_TRUE(send_request(1, req, &response));
  17462. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17463. response.substr(0, response.find("\r\n")));
  17464. }
  17465. }
  17466. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  17467. Server svr;
  17468. svr.Post("/test", [&](const Request &, Response &res) {
  17469. res.set_content("ok", "text/plain");
  17470. });
  17471. thread t = thread([&] { svr.listen(HOST, PORT); });
  17472. auto se = detail::scope_exit([&] {
  17473. svr.stop();
  17474. t.join();
  17475. ASSERT_FALSE(svr.is_running());
  17476. });
  17477. svr.wait_until_ready();
  17478. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  17479. // length cannot be determined, so the server must answer 400 and close
  17480. // rather than treat the request as bodyless and leave the body in the
  17481. // socket for the next request to pick up.
  17482. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  17483. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  17484. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  17485. std::string response;
  17486. ASSERT_TRUE(send_request(1, req, &response));
  17487. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17488. response.substr(0, response.find("\r\n")))
  17489. << transfer_encoding;
  17490. }
  17491. // A sequence ending in chunked stays valid.
  17492. auto req = "POST /test HTTP/1.1\r\n"
  17493. "Host: localhost\r\n"
  17494. "Transfer-Encoding: gzip, chunked\r\n"
  17495. "Connection: close\r\n"
  17496. "\r\n"
  17497. "0\r\n\r\n";
  17498. std::string response;
  17499. ASSERT_TRUE(send_request(1, req, &response));
  17500. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17501. }
  17502. // Regression for issue #2450: a DELETE without Content-Length on a
  17503. // keep-alive connection must not let the post-response drain consume the
  17504. // next request's bytes.
  17505. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  17506. Server svr;
  17507. std::atomic<int> delete_count(0);
  17508. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  17509. delete_count++;
  17510. res.status = StatusCode::NoContent_204;
  17511. });
  17512. auto port = svr.bind_to_any_port(HOST);
  17513. thread t = thread([&] { svr.listen_after_bind(); });
  17514. auto se = detail::scope_exit([&] {
  17515. svr.stop();
  17516. t.join();
  17517. });
  17518. svr.wait_until_ready();
  17519. auto error = Error::Success;
  17520. auto sock = detail::create_client_socket(
  17521. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17522. /*connection_timeout_sec=*/2, 0,
  17523. /*read_timeout_sec=*/2, 0,
  17524. /*write_timeout_sec=*/2, 0, std::string(), error);
  17525. ASSERT_NE(INVALID_SOCKET, sock);
  17526. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17527. auto send_request_and_read_response = [&](const std::string &req,
  17528. std::string &out) -> bool {
  17529. auto sent = send(sock, req.data(), req.size(), 0);
  17530. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  17531. char buf[4096];
  17532. for (;;) {
  17533. auto n = recv(sock, buf, sizeof(buf), 0);
  17534. if (n <= 0) { return !out.empty(); }
  17535. out.append(buf, static_cast<size_t>(n));
  17536. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  17537. }
  17538. };
  17539. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  17540. "Host: localhost\r\n"
  17541. "\r\n";
  17542. std::string resp1;
  17543. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  17544. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  17545. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  17546. "Host: localhost\r\n"
  17547. "Connection: close\r\n"
  17548. "\r\n";
  17549. std::string resp2;
  17550. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  17551. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  17552. EXPECT_EQ(2, delete_count.load());
  17553. }
  17554. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  17555. Server svr;
  17556. svr.Post("/ingest", [&](const Request &, Response &res,
  17557. const ContentReader &content_reader) {
  17558. auto consumed = content_reader([](const char *, size_t) { return false; });
  17559. EXPECT_FALSE(consumed);
  17560. res.status = StatusCode::Conflict_409;
  17561. res.set_header("Connection", "close");
  17562. });
  17563. auto port = svr.bind_to_any_port(HOST);
  17564. thread t = thread([&] { svr.listen_after_bind(); });
  17565. auto se = detail::scope_exit([&] {
  17566. svr.stop();
  17567. t.join();
  17568. });
  17569. svr.wait_until_ready();
  17570. auto error = Error::Success;
  17571. auto sock = detail::create_client_socket(
  17572. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17573. /*connection_timeout_sec=*/2, 0,
  17574. /*read_timeout_sec=*/1, 0,
  17575. /*write_timeout_sec=*/2, 0, std::string(), error);
  17576. ASSERT_NE(INVALID_SOCKET, sock);
  17577. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17578. std::string request = "POST /ingest HTTP/1.1\r\n"
  17579. "Host: localhost\r\n"
  17580. "Transfer-Encoding: chunked\r\n"
  17581. "\r\n"
  17582. "4\r\n"
  17583. "data\r\n";
  17584. auto sent = send(sock, request.data(), request.size(), 0);
  17585. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  17586. std::string response;
  17587. ssize_t received = 0;
  17588. do {
  17589. char buf[4096];
  17590. received = recv(sock, buf, sizeof(buf), 0);
  17591. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  17592. } while (received > 0);
  17593. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  17594. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  17595. EXPECT_EQ(0, received);
  17596. }
  17597. namespace no_proxy_test {
  17598. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  17599. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  17600. // calling listen().
  17601. class ScopedServer {
  17602. public:
  17603. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  17604. ~ScopedServer() {
  17605. svr_.stop();
  17606. if (th_.joinable()) { th_.join(); }
  17607. }
  17608. Server &svr() { return svr_; }
  17609. int port() const { return port_; }
  17610. void listen() {
  17611. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17612. svr_.wait_until_ready();
  17613. }
  17614. private:
  17615. Server svr_;
  17616. std::thread th_;
  17617. int port_ = 0;
  17618. };
  17619. class ProxyAndTargetServers {
  17620. public:
  17621. ProxyAndTargetServers() {
  17622. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  17623. proxy_hits_++;
  17624. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17625. res.set_content("via-proxy", "text/plain");
  17626. });
  17627. target_.Get(".*", [this](const Request &req, Response &res) {
  17628. target_hits_++;
  17629. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17630. res.set_content("direct", "text/plain");
  17631. });
  17632. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  17633. target_port_ = target_.bind_to_any_port("127.0.0.1");
  17634. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  17635. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  17636. proxy_mock_.wait_until_ready();
  17637. target_.wait_until_ready();
  17638. }
  17639. ~ProxyAndTargetServers() {
  17640. proxy_mock_.stop();
  17641. target_.stop();
  17642. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  17643. if (target_thread_.joinable()) { target_thread_.join(); }
  17644. }
  17645. Server &proxy_mock() { return proxy_mock_; }
  17646. Server &target() { return target_; }
  17647. int proxy_port() const { return proxy_port_; }
  17648. int target_port() const { return target_port_; }
  17649. int proxy_hits() const { return proxy_hits_.load(); }
  17650. int target_hits() const { return target_hits_.load(); }
  17651. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  17652. void reset_counters() {
  17653. proxy_hits_ = 0;
  17654. target_hits_ = 0;
  17655. last_had_proxy_authz_ = false;
  17656. }
  17657. private:
  17658. Server proxy_mock_;
  17659. Server target_;
  17660. std::thread proxy_thread_;
  17661. std::thread target_thread_;
  17662. int proxy_port_ = 0;
  17663. int target_port_ = 0;
  17664. std::atomic<int> proxy_hits_{0};
  17665. std::atomic<int> target_hits_{0};
  17666. std::atomic<bool> last_had_proxy_authz_{false};
  17667. };
  17668. inline std::unique_ptr<Client> make_client(const std::string &host,
  17669. ProxyAndTargetServers &s) {
  17670. auto cli = detail::make_unique<Client>(host, s.target_port());
  17671. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  17672. cli->set_proxy("127.0.0.1", s.proxy_port());
  17673. return cli;
  17674. }
  17675. } // namespace no_proxy_test
  17676. using no_proxy_test::make_client;
  17677. using no_proxy_test::ProxyAndTargetServers;
  17678. TEST(NoProxyTest, ExactHostnameBypasses) {
  17679. ProxyAndTargetServers s;
  17680. auto cli = make_client("example.com", s);
  17681. cli->set_no_proxy({"example.com"});
  17682. auto res = cli->Get("/");
  17683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17684. EXPECT_EQ(0, s.proxy_hits());
  17685. EXPECT_EQ(1, s.target_hits());
  17686. }
  17687. TEST(NoProxyTest, SubdomainBypasses) {
  17688. ProxyAndTargetServers s;
  17689. auto cli = make_client("foo.example.com", s);
  17690. cli->set_no_proxy({"example.com"});
  17691. auto res = cli->Get("/");
  17692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17693. EXPECT_EQ(0, s.proxy_hits());
  17694. EXPECT_EQ(1, s.target_hits());
  17695. }
  17696. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  17697. // Regression guard: "evilexample.com" must not be considered a subdomain
  17698. // of "example.com". Without the dot-boundary rule, a naive endsWith
  17699. // check would let traffic bypass the proxy and leak credentials direct
  17700. // to the attacker host.
  17701. ProxyAndTargetServers s;
  17702. auto cli = make_client("evilexample.com", s);
  17703. cli->set_no_proxy({"example.com"});
  17704. auto res = cli->Get("/");
  17705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17706. EXPECT_GE(s.proxy_hits(), 1);
  17707. EXPECT_EQ(0, s.target_hits());
  17708. }
  17709. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  17710. ProxyAndTargetServers s;
  17711. auto cli = make_client("example.com.evil.com", s);
  17712. cli->set_no_proxy({"example.com"});
  17713. auto res = cli->Get("/");
  17714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17715. EXPECT_GE(s.proxy_hits(), 1);
  17716. EXPECT_EQ(0, s.target_hits());
  17717. }
  17718. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  17719. ProxyAndTargetServers s;
  17720. auto cli = make_client("example.com", s);
  17721. cli->set_no_proxy({".example.com"});
  17722. auto res = cli->Get("/");
  17723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17724. EXPECT_EQ(0, s.proxy_hits());
  17725. EXPECT_EQ(1, s.target_hits());
  17726. }
  17727. TEST(NoProxyTest, CaseInsensitiveHostname) {
  17728. ProxyAndTargetServers s;
  17729. auto cli = make_client("Example.COM", s);
  17730. cli->set_no_proxy({"EXAMPLE.com"});
  17731. auto res = cli->Get("/");
  17732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17733. EXPECT_EQ(0, s.proxy_hits());
  17734. EXPECT_EQ(1, s.target_hits());
  17735. }
  17736. TEST(NoProxyTest, TrailingDotIsNormalized) {
  17737. ProxyAndTargetServers s;
  17738. auto cli = make_client("example.com.", s);
  17739. cli->set_no_proxy({"example.com"});
  17740. auto res = cli->Get("/");
  17741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17742. EXPECT_EQ(0, s.proxy_hits());
  17743. EXPECT_EQ(1, s.target_hits());
  17744. }
  17745. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  17746. // Trailing dots must be normalized on BOTH sides — host and entry.
  17747. // An implementation that only strips the host-side trailing dot would
  17748. // fail to match host "example.com" against entry "example.com." because
  17749. // a literal substring search would compare 11 chars against 12.
  17750. ProxyAndTargetServers s;
  17751. auto cli = make_client("example.com", s);
  17752. cli->set_no_proxy({"example.com."});
  17753. auto res = cli->Get("/");
  17754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17755. EXPECT_EQ(0, s.proxy_hits());
  17756. EXPECT_EQ(1, s.target_hits());
  17757. }
  17758. TEST(NoProxyTest, WildcardBypassesEverything) {
  17759. ProxyAndTargetServers s;
  17760. auto cli = make_client("anything.invalid.test", s);
  17761. cli->set_no_proxy({"*"});
  17762. auto res = cli->Get("/");
  17763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17764. EXPECT_EQ(0, s.proxy_hits());
  17765. EXPECT_EQ(1, s.target_hits());
  17766. }
  17767. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  17768. ProxyAndTargetServers s;
  17769. Client cli("127.0.0.1", s.target_port());
  17770. cli.set_proxy("127.0.0.1", s.proxy_port());
  17771. cli.set_no_proxy({"127.0.0.1"});
  17772. auto res = cli.Get("/");
  17773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17774. EXPECT_EQ(0, s.proxy_hits());
  17775. EXPECT_EQ(1, s.target_hits());
  17776. }
  17777. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  17778. ProxyAndTargetServers s;
  17779. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  17780. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  17781. cli.set_proxy("127.0.0.1", s.proxy_port());
  17782. cli.set_no_proxy({"::1"});
  17783. auto res = cli.Get("/");
  17784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17785. EXPECT_EQ(0, s.proxy_hits());
  17786. EXPECT_EQ(1, s.target_hits());
  17787. }
  17788. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  17789. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  17790. // must still be recognized as IPv6 for CIDR matching. Implementations
  17791. // that detect IPv6 only when the host begins with '[' would parse the
  17792. // host as a hostname and miss the match.
  17793. ProxyAndTargetServers s;
  17794. Client cli("fe80::1", s.target_port());
  17795. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17796. cli.set_proxy("127.0.0.1", s.proxy_port());
  17797. cli.set_no_proxy({"fe80::/10"});
  17798. auto res = cli.Get("/");
  17799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17800. EXPECT_EQ(0, s.proxy_hits());
  17801. EXPECT_EQ(1, s.target_hits());
  17802. }
  17803. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  17804. ProxyAndTargetServers s;
  17805. Client cli("::1", s.target_port());
  17806. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  17807. cli.set_proxy("127.0.0.1", s.proxy_port());
  17808. cli.set_no_proxy({"[::1]"});
  17809. auto res = cli.Get("/");
  17810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17811. EXPECT_EQ(0, s.proxy_hits());
  17812. EXPECT_EQ(1, s.target_hits());
  17813. }
  17814. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  17815. ProxyAndTargetServers s;
  17816. Client cli("fe80::1", s.target_port());
  17817. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17818. cli.set_proxy("127.0.0.1", s.proxy_port());
  17819. cli.set_no_proxy({"[fe80::]/10"});
  17820. auto res = cli.Get("/");
  17821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17822. EXPECT_EQ(0, s.proxy_hits());
  17823. EXPECT_EQ(1, s.target_hits());
  17824. }
  17825. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  17826. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  17827. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  17828. // tricks via address-family conversion.
  17829. ProxyAndTargetServers s;
  17830. Client cli("::ffff:127.0.0.1", s.target_port());
  17831. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  17832. cli.set_proxy("127.0.0.1", s.proxy_port());
  17833. cli.set_no_proxy({"127.0.0.1"});
  17834. auto res = cli.Get("/");
  17835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17836. EXPECT_GE(s.proxy_hits(), 1);
  17837. EXPECT_EQ(0, s.target_hits());
  17838. }
  17839. TEST(NoProxyTest, IPv4CidrMatch) {
  17840. ProxyAndTargetServers s;
  17841. Client cli("127.0.0.1", s.target_port());
  17842. cli.set_proxy("127.0.0.1", s.proxy_port());
  17843. cli.set_no_proxy({"127.0.0.0/8"});
  17844. auto res = cli.Get("/");
  17845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17846. EXPECT_EQ(0, s.proxy_hits());
  17847. EXPECT_EQ(1, s.target_hits());
  17848. }
  17849. TEST(NoProxyTest, IPv4CidrNonMatch) {
  17850. ProxyAndTargetServers s;
  17851. Client cli("127.0.0.1", s.target_port());
  17852. cli.set_proxy("127.0.0.1", s.proxy_port());
  17853. cli.set_no_proxy({"10.0.0.0/8"});
  17854. auto res = cli.Get("/");
  17855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17856. EXPECT_GE(s.proxy_hits(), 1);
  17857. EXPECT_EQ(0, s.target_hits());
  17858. }
  17859. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  17860. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  17861. // IPv4 target matches.
  17862. ProxyAndTargetServers s;
  17863. Client cli("127.0.0.1", s.target_port());
  17864. cli.set_proxy("127.0.0.1", s.proxy_port());
  17865. cli.set_no_proxy({"0.0.0.0/0"});
  17866. auto res = cli.Get("/");
  17867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17868. EXPECT_EQ(0, s.proxy_hits());
  17869. EXPECT_EQ(1, s.target_hits());
  17870. }
  17871. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  17872. ProxyAndTargetServers s;
  17873. Client cli("127.0.0.1", s.target_port());
  17874. cli.set_proxy("127.0.0.1", s.proxy_port());
  17875. cli.set_no_proxy({"127.0.0.1"});
  17876. auto res = cli.Get("/");
  17877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17878. EXPECT_EQ(0, s.proxy_hits());
  17879. EXPECT_EQ(1, s.target_hits());
  17880. }
  17881. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  17882. ProxyAndTargetServers s;
  17883. Client cli("127.0.0.1", s.target_port());
  17884. cli.set_proxy("127.0.0.1", s.proxy_port());
  17885. cli.set_no_proxy({"127.0.0.0/33"});
  17886. auto res = cli.Get("/");
  17887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17888. EXPECT_GE(s.proxy_hits(), 1);
  17889. EXPECT_EQ(0, s.target_hits());
  17890. }
  17891. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  17892. // Empty prefix after the slash must be rejected, not silently treated as /32.
  17893. ProxyAndTargetServers s;
  17894. Client cli("127.0.0.1", s.target_port());
  17895. cli.set_proxy("127.0.0.1", s.proxy_port());
  17896. cli.set_no_proxy({"127.0.0.1/"});
  17897. auto res = cli.Get("/");
  17898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17899. EXPECT_GE(s.proxy_hits(), 1);
  17900. EXPECT_EQ(0, s.target_hits());
  17901. }
  17902. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  17903. ProxyAndTargetServers s;
  17904. auto cli = make_client("internal.corp", s);
  17905. cli->set_proxy_basic_auth("u", "p");
  17906. cli->set_no_proxy({"internal.corp"});
  17907. auto res = cli->Get("/");
  17908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17909. EXPECT_EQ(1, s.target_hits());
  17910. EXPECT_EQ(0, s.proxy_hits());
  17911. EXPECT_FALSE(s.last_had_proxy_authz())
  17912. << "Proxy-Authorization must not be sent direct to the target";
  17913. }
  17914. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  17915. ProxyAndTargetServers s;
  17916. auto cli = make_client("public.example", s);
  17917. cli->set_proxy_basic_auth("u", "p");
  17918. cli->set_no_proxy({"internal.corp"}); // does not match
  17919. auto res = cli->Get("/");
  17920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17921. EXPECT_GE(s.proxy_hits(), 1);
  17922. EXPECT_TRUE(s.last_had_proxy_authz());
  17923. }
  17924. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  17925. ProxyAndTargetServers s;
  17926. auto cli = make_client("anything.test", s);
  17927. auto res = cli->Get("/");
  17928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17929. EXPECT_GE(s.proxy_hits(), 1);
  17930. EXPECT_EQ(0, s.target_hits());
  17931. }
  17932. TEST(NoProxyTest, PortSpecificEntryRejected) {
  17933. ProxyAndTargetServers s;
  17934. auto cli = make_client("example.com", s);
  17935. cli->set_no_proxy({"example.com:8080"});
  17936. auto res = cli->Get("/");
  17937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17938. EXPECT_GE(s.proxy_hits(), 1);
  17939. EXPECT_EQ(0, s.target_hits());
  17940. }
  17941. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  17942. ProxyAndTargetServers s;
  17943. auto cli = make_client("anything.test", s);
  17944. cli->set_no_proxy({"", " ", "\t"});
  17945. auto res = cli->Get("/");
  17946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17947. EXPECT_GE(s.proxy_hits(), 1);
  17948. EXPECT_EQ(0, s.target_hits());
  17949. }
  17950. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  17951. // An entry with leading/trailing whitespace must still match — env-style
  17952. // values are commonly pasted with stray spaces and an implementation
  17953. // that feeds the raw token directly to inet_pton would fail to match
  17954. // valid CIDRs because of the spaces.
  17955. ProxyAndTargetServers s;
  17956. Client cli("127.0.0.1", s.target_port());
  17957. cli.set_proxy("127.0.0.1", s.proxy_port());
  17958. cli.set_no_proxy({" 127.0.0.0/8 "});
  17959. auto res = cli.Get("/");
  17960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17961. EXPECT_EQ(0, s.proxy_hits());
  17962. EXPECT_EQ(1, s.target_hits());
  17963. }
  17964. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  17965. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  17966. // go direct and must NOT carry Proxy-Authorization.
  17967. std::atomic<int> proxy_hits{0};
  17968. std::atomic<int> target_hits{0};
  17969. std::atomic<bool> target_saw_authz{false};
  17970. no_proxy_test::ScopedServer proxy_mock, target;
  17971. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17972. proxy_hits++;
  17973. res.status = 302;
  17974. res.set_header("Location", "http://127.0.0.1:" +
  17975. std::to_string(target.port()) + "/landed");
  17976. });
  17977. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17978. target_hits++;
  17979. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  17980. res.set_content("direct", "text/plain");
  17981. });
  17982. proxy_mock.listen();
  17983. target.listen();
  17984. Client cli("public.example", target.port());
  17985. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17986. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17987. cli.set_proxy_basic_auth("u", "p");
  17988. cli.set_no_proxy({"127.0.0.1"});
  17989. cli.set_follow_location(true);
  17990. auto res = cli.Get("/redir");
  17991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17992. EXPECT_GE(proxy_hits.load(), 1);
  17993. EXPECT_GE(target_hits.load(), 1);
  17994. EXPECT_FALSE(target_saw_authz.load());
  17995. }
  17996. #ifdef CPPHTTPLIB_SSL_ENABLED
  17997. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  17998. // Direct origin replying 407 must not trigger the digest retry; otherwise
  17999. // proxy creds would be sent to the (possibly hostile) origin.
  18000. std::atomic<int> target_hits{0};
  18001. std::atomic<bool> target_saw_proxy_authz{false};
  18002. no_proxy_test::ScopedServer target;
  18003. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18004. target_hits++;
  18005. if (req.has_header("Proxy-Authorization")) {
  18006. target_saw_proxy_authz = true;
  18007. }
  18008. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18009. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  18010. "nonce=\"abc\", algorithm=MD5");
  18011. });
  18012. target.listen();
  18013. // The proxy address is set to the target's port: the bypass MUST kick in;
  18014. // if it doesn't, the test still routes "via proxy" to the same server and
  18015. // the Proxy-Authorization assertion below catches the leak.
  18016. Client cli("evil.example", target.port());
  18017. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  18018. cli.set_proxy("127.0.0.1", target.port());
  18019. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18020. cli.set_no_proxy({"evil.example"});
  18021. auto res = cli.Get("/x");
  18022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18023. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18024. EXPECT_EQ(1, target_hits.load());
  18025. EXPECT_FALSE(target_saw_proxy_authz.load());
  18026. }
  18027. #endif
  18028. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  18029. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  18030. std::atomic<int> proxy_hits{0};
  18031. std::atomic<int> bypass_hits{0};
  18032. std::atomic<bool> proxy_saw_c_url{false};
  18033. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  18034. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  18035. proxy_hits++;
  18036. if (req.path.find("/start") != std::string::npos) {
  18037. res.status = 302;
  18038. res.set_header("Location", "http://127.0.0.1:" +
  18039. std::to_string(bypass_server.port()) +
  18040. "/middle");
  18041. return;
  18042. }
  18043. if (req.path.find("/end") != std::string::npos) {
  18044. proxy_saw_c_url = true;
  18045. res.set_content("c-via-proxy", "text/plain");
  18046. return;
  18047. }
  18048. res.set_content("unexpected", "text/plain");
  18049. });
  18050. // public.example's "advertised" port is arbitrary (the request never lands
  18051. // there — it goes through the proxy), but use a dynamic value to stay
  18052. // friendly with sharded parallel runs.
  18053. int public_port = bypass_server.port();
  18054. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  18055. bypass_hits++;
  18056. res.status = 302;
  18057. res.set_header("Location", "http://public.example:" +
  18058. std::to_string(public_port) + "/end");
  18059. });
  18060. proxy_mock.listen();
  18061. bypass_server.listen();
  18062. Client cli("public.example", public_port);
  18063. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18064. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18065. cli.set_no_proxy({"127.0.0.1"});
  18066. cli.set_follow_location(true);
  18067. auto res = cli.Get("/start");
  18068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18069. EXPECT_EQ(StatusCode::OK_200, res->status);
  18070. EXPECT_EQ("c-via-proxy", res->body);
  18071. EXPECT_GE(proxy_hits.load(), 2);
  18072. EXPECT_GE(bypass_hits.load(), 1);
  18073. EXPECT_TRUE(proxy_saw_c_url.load());
  18074. }
  18075. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  18076. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  18077. // request reconnects to the correct endpoint.
  18078. std::atomic<int> proxy_hits{0};
  18079. std::atomic<int> target_hits{0};
  18080. no_proxy_test::ScopedServer proxy_mock, target;
  18081. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18082. proxy_hits++;
  18083. res.set_content("via-proxy", "text/plain");
  18084. });
  18085. target.svr().Get(".*", [&](const Request &, Response &res) {
  18086. target_hits++;
  18087. res.set_content("direct", "text/plain");
  18088. });
  18089. proxy_mock.listen();
  18090. target.listen();
  18091. Client cli("public.example", target.port());
  18092. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18093. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18094. cli.set_keep_alive(true);
  18095. auto res1 = cli.Get("/a");
  18096. ASSERT_TRUE(res1);
  18097. EXPECT_EQ("via-proxy", res1->body);
  18098. EXPECT_EQ(1, proxy_hits.load());
  18099. EXPECT_EQ(0, target_hits.load());
  18100. cli.set_no_proxy({"public.example"});
  18101. auto res2 = cli.Get("/b");
  18102. ASSERT_TRUE(res2);
  18103. EXPECT_EQ("direct", res2->body);
  18104. EXPECT_EQ(1, proxy_hits.load());
  18105. EXPECT_EQ(1, target_hits.load());
  18106. }
  18107. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  18108. namespace proxy_tunnel_test {
  18109. // SSLServer counterpart to no_proxy_test::ScopedServer.
  18110. class ScopedSSLServer {
  18111. public:
  18112. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  18113. port_ = svr_.bind_to_any_port("127.0.0.1");
  18114. }
  18115. ~ScopedSSLServer() {
  18116. svr_.stop();
  18117. if (th_.joinable()) { th_.join(); }
  18118. }
  18119. SSLServer &svr() { return svr_; }
  18120. int port() const { return port_; }
  18121. void listen() {
  18122. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18123. svr_.wait_until_ready();
  18124. }
  18125. private:
  18126. SSLServer svr_;
  18127. std::thread th_;
  18128. int port_ = 0;
  18129. };
  18130. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  18131. class ScopedConnectProxy {
  18132. public:
  18133. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  18134. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  18135. if (listen_fd_ < 0) { return; }
  18136. int yes = 1;
  18137. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  18138. sockaddr_in a{};
  18139. a.sin_family = AF_INET;
  18140. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18141. a.sin_port = 0;
  18142. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  18143. return;
  18144. }
  18145. socklen_t alen = sizeof(a);
  18146. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  18147. 0) {
  18148. return;
  18149. }
  18150. port_ = ntohs(a.sin_port);
  18151. if (::listen(listen_fd_, 1) != 0) { return; }
  18152. th_ = std::thread([this] { run(); });
  18153. }
  18154. ~ScopedConnectProxy() {
  18155. stop_ = true;
  18156. if (listen_fd_ >= 0) {
  18157. ::shutdown(listen_fd_, SHUT_RDWR);
  18158. ::close(listen_fd_);
  18159. }
  18160. if (th_.joinable()) { th_.join(); }
  18161. }
  18162. int port() const { return port_; }
  18163. int connect_hits() const { return connect_hits_.load(); }
  18164. private:
  18165. void run() {
  18166. while (!stop_.load()) {
  18167. fd_set rfds;
  18168. FD_ZERO(&rfds);
  18169. FD_SET(listen_fd_, &rfds);
  18170. timeval tv{0, 100 * 1000};
  18171. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  18172. if (sel <= 0) { continue; }
  18173. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  18174. if (client_fd < 0) { continue; }
  18175. std::string req;
  18176. char buf[2048];
  18177. while (req.find("\r\n\r\n") == std::string::npos) {
  18178. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  18179. if (n <= 0) { break; }
  18180. req.append(buf, static_cast<size_t>(n));
  18181. }
  18182. if (req.compare(0, 7, "CONNECT") != 0) {
  18183. ::close(client_fd);
  18184. continue;
  18185. }
  18186. connect_hits_++;
  18187. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  18188. ::send(client_fd, ok, std::strlen(ok), 0);
  18189. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  18190. sockaddr_in o{};
  18191. o.sin_family = AF_INET;
  18192. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18193. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  18194. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  18195. 0) {
  18196. ::close(client_fd);
  18197. ::close(origin_fd);
  18198. continue;
  18199. }
  18200. auto forward = [](int from, int to) {
  18201. char b[8192];
  18202. for (;;) {
  18203. ssize_t n = ::recv(from, b, sizeof(b), 0);
  18204. if (n <= 0) { break; }
  18205. ssize_t off = 0;
  18206. while (off < n) {
  18207. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  18208. if (s <= 0) {
  18209. off = n;
  18210. break;
  18211. }
  18212. off += s;
  18213. }
  18214. }
  18215. ::shutdown(to, SHUT_WR);
  18216. };
  18217. std::thread t1([&] { forward(client_fd, origin_fd); });
  18218. std::thread t2([&] { forward(origin_fd, client_fd); });
  18219. t1.join();
  18220. t2.join();
  18221. ::close(client_fd);
  18222. ::close(origin_fd);
  18223. }
  18224. }
  18225. int forward_port_ = -1;
  18226. int listen_fd_ = -1;
  18227. int port_ = 0;
  18228. std::thread th_;
  18229. std::atomic<bool> stop_{false};
  18230. std::atomic<int> connect_hits_{0};
  18231. };
  18232. } // namespace proxy_tunnel_test
  18233. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  18234. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  18235. // retry; otherwise proxy creds would be sent to the origin.
  18236. std::atomic<int> origin_hits{0};
  18237. std::atomic<bool> origin_saw_proxy_authz{false};
  18238. proxy_tunnel_test::ScopedSSLServer origin;
  18239. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  18240. origin_hits++;
  18241. if (req.has_header("Proxy-Authorization")) {
  18242. origin_saw_proxy_authz = true;
  18243. }
  18244. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18245. res.set_header("Proxy-Authenticate",
  18246. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  18247. "algorithm=MD5");
  18248. });
  18249. origin.listen();
  18250. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  18251. ASSERT_NE(0, proxy.port());
  18252. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  18253. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  18254. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  18255. // and answer with its own status, making this test flaky.
  18256. SSLClient cli("127.0.0.1", origin.port());
  18257. cli.enable_server_certificate_verification(false);
  18258. cli.set_proxy("127.0.0.1", proxy.port());
  18259. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18260. auto res = cli.Get("/x");
  18261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18262. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18263. EXPECT_EQ(1, origin_hits.load());
  18264. EXPECT_FALSE(origin_saw_proxy_authz.load());
  18265. EXPECT_EQ(1, proxy.connect_hits());
  18266. }
  18267. #endif